@runtypelabs/persona 4.23.0 → 4.23.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-9Vxm-PPz.d.cts → types-CI7OckWI.d.cts} +23 -2
- package/dist/animations/{types-9Vxm-PPz.d.ts → types-CI7OckWI.d.ts} +23 -2
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/animations-extra.d.cts +23 -2
- package/dist/animations-extra.d.ts +23 -2
- package/dist/approval-ui.d.cts +46 -3
- package/dist/approval-ui.d.ts +46 -3
- package/dist/artifacts-ui.d.cts +46 -3
- package/dist/artifacts-ui.d.ts +46 -3
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +46 -3
- package/dist/context-mentions.d.ts +46 -3
- package/dist/event-stream-view.d.cts +46 -3
- package/dist/event-stream-view.d.ts +46 -3
- package/dist/forms-ui.d.cts +46 -3
- package/dist/forms-ui.d.ts +46 -3
- package/dist/history-view.d.cts +23 -2
- package/dist/history-view.d.ts +23 -2
- package/dist/index.cjs +43 -43
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +67 -12
- package/dist/index.d.ts +67 -12
- package/dist/index.global.js +28 -28
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +43 -43
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +46 -3
- package/dist/session-reconnect.d.ts +46 -3
- package/dist/smart-dom-reader.d.cts +46 -3
- package/dist/smart-dom-reader.d.ts +46 -3
- package/dist/theme-editor-preview.cjs +49 -49
- package/dist/theme-editor-preview.d.cts +46 -3
- package/dist/theme-editor-preview.d.ts +46 -3
- package/dist/theme-editor-preview.js +33 -33
- package/dist/theme-editor.d.cts +46 -3
- package/dist/theme-editor.d.ts +46 -3
- package/package.json +1 -1
- package/src/client-session-renewal.test.ts +268 -0
- package/src/client.interrupt.test.ts +1 -1
- package/src/client.tool-pair-replay.test.ts +325 -0
- package/src/client.ts +93 -49
- package/src/generated/runtype-openapi-contract.ts +26 -11
- package/src/session.ts +32 -3
- package/src/types.ts +43 -1
- package/src/utils/tool-pair-replay.ts +100 -0
package/dist/index.global.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var
|
|
2
|
-
\r `.includes(e[n]);)n++};return i()},
|
|
3
|
-
`),o=!1;for(let n=0;n<t.length-1;n++){let r=t[n],a=t[n+1];if(!
|
|
4
|
-
`):e};var Av="var(--persona-md-table-scroll-fade, 24px)",Mv=new WeakSet;function Ev(e){e.querySelectorAll("table").forEach(o=>{if(o.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",o.replaceWith(r),r.appendChild(o)})}function Tv(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let n=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty("--persona-fade-l",n<=1?"0px":Av),e.style.setProperty("--persona-fade-r",r<=1?"0px":Av)}function Hf(e){Mv.has(e)||(Mv.add(e),e.addEventListener("scroll",t=>{let o=t.target;o?.classList?.contains("persona-table-scroll")&&Tv(o)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Tv)}var Ji="webmcp:",Wf=new Map,kv=e=>{Wf.clear();for(let t of e){let o=t.title?.trim();o&&Wf.set(t.name,o)}},lc=e=>Wf.get(Of(e)),Bf=null,Lv=e=>{Bf=e};function Iv(e){if(e.length===0)return"0:empty";let t=e.map(o=>[o.name,o.description??"",o.parametersSchema?JSON.stringify(o.parametersSchema):"",o.origin??"",o.annotations?JSON.stringify(o.annotations):""].join("")).sort();return`${e.length}:${_T(t.join(""))}`}function Pv(e,t){let o=3735928559^t,n=1103547991^t;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);o=Math.imul(o^a,2654435761),n=Math.imul(n^a,1597334677)}return o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),4294967296*(2097151&n)+(o>>>0)}function _T(e){let t=Pv(e,0).toString(36),o=Pv(e,2654435761).toString(36);return`${t}.${o}`}var Of=e=>e.startsWith(Ji)?e.slice(Ji.length):e,_r=e=>e.startsWith(Ji),Rv=()=>Bf?Bf():import("@mcp-b/webmcp-polyfill");var{setLoader:NT,load:FT}=mt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),Hv=NT,Wv=FT;function Bo(e){return e==="card"?"collapsed":e}function Nr(e){return e.split(";",1)[0].trim().toLowerCase()}function UT(e,t){if(!e)return;let o=Object.entries(e);for(let[r,a]of o)if(Nr(r)===t)return{mode:Bo(a),selector:Nr(r)};let n=`${t.split("/",1)[0]}/*`;for(let[r,a]of o)if(Nr(r)===n)return{mode:Bo(a),selector:n}}function Df(e,t){let o=e?.display,n=typeof o=="string"?{default:o}:o??{};if(t.file&&n.files){if(typeof n.files=="string")return{mode:Bo(n.files),matchedBy:{type:"files"}};let d=t.file.mimeType?Nr(t.file.mimeType):void 0,c=d?UT(n.files.byMediaType,d):void 0;if(d&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:d,selector:c.selector}};if(n.files.default)return{mode:Bo(n.files.default),matchedBy:{type:"files"}}}let r=n.byKind?.[t.artifactType];if(r)return{mode:Bo(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:Bo(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Bo(i),matchedBy:{type:"preferredMode"}}:n.default?{mode:Bo(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Dn(e,t){return Df(e,t).mode}function Zi(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var qT="agent_",VT="flow_";function Bv(e){return e.startsWith(qT)?{kind:"agentId",agentId:e}:e.startsWith(VT)?{kind:"flowId",flowId:e}:null}function Ov(e,t){let o=e.trim();if(!o)throw new Error("[Persona] `target` is empty.");let n=o.indexOf(":");if(n>0){let i=o.slice(0,n),d=o.slice(n+1);if(i==="runtype"){let u=Bv(d);if(u)return u;throw new Error(`[Persona] target "runtype:${d}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(d).payload}}let r=Bv(o);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(o).payload};throw new Error(`[Persona] target "${o}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${o}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Dv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ka(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Fr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function _v(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var Ur=Yt(uc(),1);var R=(e,t)=>{let o=document.createElement(e);return t&&(o.className=t),o};var Q=(e,t={},...o)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text),t.attrs)for(let[a,i]of Object.entries(t.attrs))n.setAttribute(a,i);if(t.style){let a=n.style,i=t.style;for(let d of Object.keys(i)){let c=i[d];c!=null&&(a[d]=c)}}let r=o.filter(a=>a!=null);return r.length>0&&n.append(...r),n},yo=(...e)=>e.filter(Boolean).join(" ");var tl="ask_user_question",el=8,La="data-persona-ask-sheet-for",GT="Other",XT="Other\u2026",Uv="Type your own answer here",qv="Send",QT="Next",YT="Back",JT="Submit all",ZT="Skip",eE=3,Nf="data-ask-current-index",Ff="data-ask-question-count",Vv="data-ask-answers",Uf="data-ask-grouped",$v="data-ask-layout",tE=e=>e.layout==="pills"?"pills":"rows",oE=e=>e.getAttribute($v)==="pills"?"pills":"rows",Fv=!1,jv=e=>e.replace(/["\\]/g,"\\$&"),cr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===tl,pc=e=>e?.features?.askUserQuestion??{},ur=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:o};let n=t.chunks;if(!n||n.length===0)return{payload:null,complete:o};try{let r=n.join(""),a=(0,Ur.parse)(r,Ur.STR|Ur.OBJ|Ur.ARR);if(a&&typeof a=="object")return{payload:a,complete:o}}catch{}return{payload:null,complete:o}},ol=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>el&&!Fv&&(Fv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${el}.`)),t.slice(0,el)},nE=e=>ol(e)[0]??null,rE=(e,t)=>ol(e)[t]??null,zv=(e,t)=>{let o=t.styles;o&&(o.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",o.sheetBackground),o.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",o.sheetBorder),o.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",o.sheetShadow),o.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",o.pillBackground),o.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",o.pillBackgroundSelected),o.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",o.pillTextColor),o.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",o.pillTextColorSelected),o.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",o.pillBorderRadius),o.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",o.customInputBackground))},Kv=(e,t,o)=>{if(e!=="rows")return null;let n=R("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let r=R("span","persona-ask-row-check");n.appendChild(r)}else{let r=R("span","persona-ask-row-badge");r.textContent=String(o+1),n.appendChild(r)}return n},sE=(e,t,o,n)=>{let a=R("button",o==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),o==="rows"){let i=R("span","persona-ask-row-content"),d=R("span","persona-ask-row-label");if(d.textContent=e.label,i.appendChild(d),e.description){let u=R("span","persona-ask-row-description");u.textContent=e.description,i.appendChild(u)}a.appendChild(i);let c=Kv(o,n,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},aE=e=>{let o=R("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 o.setAttribute("aria-hidden","true"),o},iE=(e,t,o,n)=>{let a=R("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(c.length===0&&!o){for(let p=0;p<eE;p++)a.appendChild(aE(n));return a}if(c.forEach((p,m)=>{a.appendChild(sE(p,m,n,i))}),e?.allowFreeText!==!1){let p=n==="rows"?GT:XT;if(n==="rows"){let m=R("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(c.length)),m.setAttribute("data-ask-other-row","true");let h=R("span","persona-ask-row-content"),y=document.createElement("input");y.type="text",y.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",y.placeholder=t.freeTextPlaceholder??Uv,y.setAttribute("data-ask-free-text-input","true"),y.setAttribute("aria-label",t.freeTextLabel??p),h.appendChild(y),m.appendChild(h);let x=Kv(n,i,c.length);x&&m.appendChild(x),a.appendChild(m)}else{let m=R("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??p,a.appendChild(m)}}return a},Gv=(e,t)=>{let n=R("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");n.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Uv,r.setAttribute("data-ask-free-text-input","true"),n.appendChild(r),t!=="rows"){let a=R("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??qv,a.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(a)}return n},lE=e=>{let t=R("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let o=R("button","persona-ask-multi-submit persona-pointer-events-auto");return o.type="button",o.textContent=e.submitLabel??qv,o.setAttribute("data-ask-user-action","submit-multi"),o.disabled=!0,t.appendChild(o),t},dE=(e,t,o)=>{let n=R("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let r=R("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=o.backLabel??YT,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,n.appendChild(r);let a=R("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=R("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=o.skipLabel??ZT,i.setAttribute("data-ask-user-action","skip"),a.appendChild(i);let d=R("button","persona-ask-nav-next persona-pointer-events-auto");d.type="button";let c=e===t-1;return d.textContent=c?o.submitAllLabel??JT:o.nextLabel??QT,d.setAttribute("data-ask-user-action",c?"submit-all":"next"),d.disabled=!0,a.appendChild(d),n.appendChild(a),n},Ls=e=>{let t=e.getAttribute(Vv);if(!t)return{};try{let o=JSON.parse(t);return o&&typeof o=="object"?o:{}}catch{return{}}},Xv=(e,t)=>{e.setAttribute(Vv,JSON.stringify(t))},sn=e=>{let t=Number(e.getAttribute(Nf)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},cE=(e,t)=>{e.setAttribute(Nf,String(Math.max(0,Math.floor(t))))},Ia=e=>{let t=Number(e.getAttribute(Ff)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},qr=e=>e.getAttribute(Uf)==="true",uE=(e,t)=>{let o=e.agentMetadata?.askUserQuestionAnswers;if(!o||typeof o!="object")return{};let n={};return t.forEach((r,a)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(o,i)){let d=o[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},pE=(e,t)=>{let o=e.agentMetadata?.askUserQuestionIndex;return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(t-1,Math.floor(o)))},fc=(e,t)=>{let{payload:o}=ur(t),n=ol(o),r=Ls(e),a={},i=new Set;return n.forEach((d,c)=>{let u=typeof d?.question=="string"?d.question:"";u&&(i.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),i.add(u),Object.prototype.hasOwnProperty.call(r,c)&&(a[u]=r[c]))}),a},Qv=e=>{let t=Ls(e),o=sn(e),n=t[o],r=new Set;typeof n=="string"?r.add(n):Array.isArray(n)&&n.forEach(c=>r.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{let u=c.getAttribute("data-option-label")??"",p=r.has(u);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(a).map(c=>c.getAttribute("data-option-label")??"")),d=e.querySelector('[data-ask-free-text-input="true"]');d&&(typeof n=="string"&&n.length>0&&!i.has(n)?(d.value=n,d.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):d.value="")},Yv=e=>{if(!qr(e))return;let t=Ls(e),o=sn(e),n=t[o],r=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let d=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=d.length===0}},qf=(e,t,o)=>{let n=pc(o),r=oE(e),{payload:a,complete:i}=ur(t),d=qr(e),c=sn(e),u=Ia(e),p=d?rE(a,c):nE(a),m=!!p?.multiSelect,h=e.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=d?`${c+1}/${u}`:"");let y=e.querySelector('[data-ask-stepper="true"]');y&&y.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let P=typeof p?.question=="string"?p.question:"";x.textContent=P,x.classList.toggle("persona-ask-question-skeleton",!P&&!i)}let M=e.querySelector('[data-ask-pill-list="true"]');if(M){let P=iE(p,n,i,r);M.replaceWith(P)}if(r!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Gv(n,r))}let S=e.querySelector('[data-ask-multi-actions="true"]');!d&&m&&!S?e.appendChild(lE(n)):(!m||d)&&S&&S.remove(),e.setAttribute("data-multi-select",m?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(d){let P=dE(c,u,n);k?k.replaceWith(P):e.appendChild(P)}else k&&k.remove();Qv(e),Yv(e)},fE=(e,t,o)=>{let n=pc(t),r=tE(n),a=e.toolCall.id,i=ol(o),d=Math.max(1,i.length),c=d>1,u=uE(e,i),p=c?pE(e,d):0,m=R("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(La,a),m.setAttribute("data-tool-call-id",a),m.setAttribute("data-message-id",e.id),m.setAttribute(Ff,String(d)),m.setAttribute(Nf,String(p)),m.setAttribute(Uf,c?"true":"false"),m.setAttribute($v,r),Xv(m,u),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),zv(m,n);let h=R("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),y=R("div","persona-ask-sheet-question persona-flex-1");y.setAttribute("data-ask-question","true"),y.textContent="",h.appendChild(y);let x=R("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",h.appendChild(x),m.appendChild(h);let S=R("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");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),m.appendChild(S),r!=="rows"&&m.appendChild(Gv(n,r)),qf(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},mE=(e,t,o)=>{let{payload:n}=ur(t),r=Math.max(1,ol(n).length);r>Ia(e)&&(e.setAttribute(Ff,String(r)),r>1&&!qr(e)&&e.setAttribute(Uf,"true")),qf(e,t,o)},Jv=(e,t)=>{let o=R("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.setAttribute("data-bubble-type","ask-user-question");let n=pc(t);zv(o,n);let r=R("span","persona-ask-stub-label"),{complete:a}=ur(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",o.appendChild(r),o},Ra=(e,t,o)=>{if(!o||!cr(e)||pc(t).enabled===!1)return;let r=e.toolCall.id;o.querySelectorAll(`[${La}]`).forEach(u=>{u.getAttribute(La)!==r&&u.remove()});let i=o.querySelector(`[${La}="${jv(r)}"]`);if(i){mE(i,e,t);return}let{payload:d}=ur(e),c=fE(e,t,d);o.appendChild(c)},Vr=(e,t)=>{if(!e)return;let o=t?`[${La}="${jv(t)}"]`:`[${La}]`;e.querySelectorAll(o).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},Vf=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),$r=(e,t)=>{let o=Ls(e),n=sn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete o[n]:o[n]=t,Xv(e,o),Qv(e),Yv(e)},mc=(e,t,o,n)=>{let r=Ia(e),a=Math.max(0,Math.min(r-1,n));cE(e,a),qf(e,t,o)};var _n="suggest_replies";var $f={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:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},gc={name:_n,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. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:$f,origin:"sdk",annotations:{readOnlyHint:!0}},ex=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Is=e=>e.variant==="tool"&&e.toolCall?.name===_n,jf=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let o=t?.suggestions;if(!Array.isArray(o))return[];let n=o.flatMap(r=>{if(typeof r=="string"){let d=r.trim();return d?[d]:[]}if(!r||typeof r!="object")return[];let a=r;if(typeof a.label!="string"||!a.label.trim())return[];let i={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(i.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(i.description=a.description.trim()),[i]});return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},hc=e=>{for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user")return null;if(!Is(o))continue;let n=jf(o.toolCall?.args);return n.length>0?n:null}return null},Zv=new Set,gE=(e,t,o)=>{let n=`${e}:${t}:${o}`;Zv.has(n)||(Zv.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},jr=e=>{let t=e?.suggestions?.followUps,o=e?.features?.suggestReplies,n=i=>{let d=t?.[i],c=o?.[i];d===void 0||c===void 0||d!==c&&gE(i,c,d)};e&&(n("enabled"),n("expose"));let r=t?.enabled??o?.enabled??!0,a=r?t?.expose??o?.expose??!1:!1;return{enabled:r,expose:a}};var zf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:el,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Kf={name:tl,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:zf,origin:"sdk",annotations:{readOnlyHint:!0}},Ha=e=>{let t=[],o=e?.features?.askUserQuestion;return o?.expose===!0&&o.enabled!==!1&&t.push(Kf),jr(e).expose&&t.push(gc),t};var pr=Yt(uc(),1),yc=e=>e.replace(/\\n/g,`
|
|
5
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),bc=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)}},
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var wT=Object.create;var rc=Object.defineProperty;var AT=Object.getOwnPropertyDescriptor;var MT=Object.getOwnPropertyNames;var TT=Object.getPrototypeOf,ET=Object.prototype.hasOwnProperty;var go=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var uv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),PT=(e,t)=>{for(var o in t)rc(e,o,{get:t[o],enumerable:!0})},pv=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of MT(t))!ET.call(e,r)&&r!==o&&rc(e,r,{get:()=>t[r],enumerable:!(n=AT(t,r))||n.enumerable});return e};var Yt=(e,t,o)=>(o=e!=null?wT(TT(e)):{},pv(t||!e||!e.__esModule?rc(o,"default",{value:e,enumerable:!0}):o,e)),kT=e=>pv(rc({},"__esModule",{value:!0}),e);var _f=uv(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.Allow=me.ALL=me.COLLECTION=me.ATOM=me.SPECIAL=me.INF=me._INFINITY=me.INFINITY=me.NAN=me.BOOL=me.NULL=me.OBJ=me.ARR=me.NUM=me.STR=void 0;me.STR=1;me.NUM=2;me.ARR=4;me.OBJ=8;me.NULL=16;me.BOOL=32;me.NAN=64;me.INFINITY=128;me._INFINITY=256;me.INF=me.INFINITY|me._INFINITY;me.SPECIAL=me.NULL|me.BOOL|me.INF|me.NAN;me.ATOM=me.STR|me.NUM|me.SPECIAL;me.COLLECTION=me.ARR|me.OBJ;me.ALL=me.ATOM|me.COLLECTION;me.Allow={STR:me.STR,NUM:me.NUM,ARR:me.ARR,OBJ:me.OBJ,NULL:me.NULL,BOOL:me.BOOL,NAN:me.NAN,INFINITY:me.INFINITY,_INFINITY:me._INFINITY,INF:me.INF,SPECIAL:me.SPECIAL,ATOM:me.ATOM,COLLECTION:me.COLLECTION,ALL:me.ALL};me.default=me.Allow});var uc=uv(no=>{"use strict";var KT=no&&no.__createBinding||(Object.create?(function(e,t,o,n){n===void 0&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}):(function(e,t,o,n){n===void 0&&(n=o),e[n]=t[o]})),GT=no&&no.__exportStar||function(e,t){for(var o in e)o!=="default"&&!Object.prototype.hasOwnProperty.call(t,o)&&KT(t,e,o)};Object.defineProperty(no,"__esModule",{value:!0});no.Allow=no.MalformedJSON=no.PartialJSON=no.parseJSON=no.parse=void 0;var ho=_f();Object.defineProperty(no,"Allow",{enumerable:!0,get:function(){return ho.Allow}});GT(_f(),no);var dc=class extends Error{};no.PartialJSON=dc;var cc=class extends Error{};no.MalformedJSON=cc;function Fv(e,t=ho.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return XT(e.trim(),t)}no.parseJSON=Fv;var XT=(e,t)=>{let o=e.length,n=0,r=h=>{throw new dc(`${h} at position ${n}`)},a=h=>{throw new cc(`${h} at position ${n}`)},i=()=>(m(),n>=o&&r("Unexpected end of input"),e[n]==='"'?d():e[n]==="{"?c():e[n]==="["?u():e.substring(n,n+4)==="null"||ho.Allow.NULL&t&&o-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||ho.Allow.BOOL&t&&o-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||ho.Allow.BOOL&t&&o-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||ho.Allow.INFINITY&t&&o-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||ho.Allow._INFINITY&t&&1<o-n&&o-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||ho.Allow.NAN&t&&o-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):p()),d=()=>{let h=n,y=!1;for(n++;n<o&&(e[n]!=='"'||y&&e[n-1]==="\\");)y=e[n]==="\\"?!y:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(h,++n-Number(y)))}catch(C){a(String(C))}else if(ho.Allow.STR&t)try{return JSON.parse(e.substring(h,n-Number(y))+'"')}catch{return JSON.parse(e.substring(h,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{n++,m();let h={};try{for(;e[n]!=="}";){if(m(),n>=o&&ho.Allow.OBJ&t)return h;let y=d();m(),n++;try{let C=i();h[y]=C}catch(C){if(ho.Allow.OBJ&t)return h;throw C}m(),e[n]===","&&n++}}catch{if(ho.Allow.OBJ&t)return h;r("Expected '}' at end of object")}return n++,h},u=()=>{n++;let h=[];try{for(;e[n]!=="]";)h.push(i()),m(),e[n]===","&&n++}catch{if(ho.Allow.ARR&t)return h;r("Expected ']' at end of array")}return n++,h},p=()=>{if(n===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(y){if(ho.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(y))}}let h=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==o&&!(ho.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(h,n))}catch{e.substring(h,n)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(h,e.lastIndexOf("e")))}catch(C){a(String(C))}}},m=()=>{for(;n<o&&`
|
|
2
|
+
\r `.includes(e[n]);)n++};return i()},QT=Fv;no.parse=QT});var $L={};PT($L,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Kf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>zf,ASK_USER_QUESTION_TOOL_NAME:()=>tl,AgentWidgetClient:()=>Rs,AgentWidgetSession:()=>Da,AttachmentManager:()=>Os,BrowserSpeechEngine:()=>Hs,DEFAULT_COMPONENTS:()=>fg,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Vc,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Ko,DEFAULT_PALETTE:()=>ug,DEFAULT_SEMANTIC:()=>pg,DEFAULT_WIDGET_CONFIG:()=>rt,HistoryProviderError:()=>ln,PRESETS:()=>Th,PRESET_FULLSCREEN:()=>Mh,PRESET_MINIMAL:()=>Ah,PRESET_SHOP:()=>wh,ReadAloudController:()=>Oa,SUGGEST_REPLIES_CLIENT_TOOL:()=>gc,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>$f,SUGGEST_REPLIES_TOOL_NAME:()=>_n,THEME_ZONES:()=>GC,VERSION:()=>fr,WEBMCP_TOOL_PREFIX:()=>Ji,applyFeaturePreferences:()=>sh,applyThemeVariables:()=>Ds,attachHeaderToContainer:()=>Fs,buildComposer:()=>Vs,buildDefaultHeader:()=>Lg,buildHeader:()=>gr,buildHeaderWithLayout:()=>Qa,buildMinimalHeader:()=>Ig,builtInClientToolsForDispatch:()=>Ha,canonicalArtifactDisplayMode:()=>Bo,collectEnrichedPageContext:()=>Jw,componentRegistry:()=>Sn,createActionManager:()=>Ul,createAgentExperience:()=>Vu,createAskUserQuestionBubble:()=>Zv,createBubbleWithLayout:()=>IS,createCSATFeedback:()=>Fu,createComboButton:()=>yu,createComponentMiddleware:()=>Lw,createComponentStreamParser:()=>Du,createDefaultSanitizer:()=>Rf,createDirectivePostprocessor:()=>vv,createDropdownMenu:()=>Us,createFlexibleJsonStreamParser:()=>sx,createIconButton:()=>qs,createImagePart:()=>Ec,createJsonStreamParser:()=>Ac,createLabelButton:()=>kg,createLocalStorageAdapter:()=>Bu,createMarkdownProcessor:()=>Qi,createMarkdownProcessorFromConfig:()=>Yi,createMessageActions:()=>Dg,createNPSFeedback:()=>Uu,createPlainTextParser:()=>Sc,createRegexJsonParser:()=>wc,createSplitButton:()=>wS,createStandardBubble:()=>Ya,createTextPart:()=>an,createTheme:()=>Sl,createThemeObserver:()=>za,createToggleGroup:()=>SS,createTypingIndicator:()=>$s,createWidgetHostLayout:()=>Vl,createXmlParser:()=>Mc,defaultActionHandlers:()=>Ks,defaultJsonActionParser:()=>Fl,defaultParseRules:()=>Ch,detectColorScheme:()=>wl,directivePostprocessor:()=>xv,ensureAskUserQuestionSheet:()=>Ra,escapeHtml:()=>dr,extractComponentDirectiveFromMessage:()=>Nu,fileToImagePart:()=>dx,formatEnrichedContext:()=>Zw,generateAssistantMessageId:()=>Fr,generateMessageId:()=>_v,generateStableSelector:()=>Sh,generateUserMessageId:()=>ka,getActiveTheme:()=>Kr,getAgentWidgetHandles:()=>Fw,getColorScheme:()=>iu,getDisplayText:()=>Tc,getHeaderLayout:()=>Rg,getImageParts:()=>lx,getPreset:()=>tA,hasComponentDirective:()=>ql,hasImages:()=>Ba,headerLayouts:()=>bu,initAgentWidget:()=>Uw,isAskUserQuestionMessage:()=>cr,isComponentDirectiveType:()=>kw,isDockedMountMode:()=>Ct,isHistoryProviderError:()=>Hx,isSuggestRepliesMessage:()=>Is,isWebMcpToolName:()=>_r,isWelcomeVisible:()=>Yr,latestAgentSuggestions:()=>hc,listRegisteredStreamAnimations:()=>Sg,loadMarkdownParsers:()=>ac,markdownPostprocessor:()=>If,mergeWithDefaults:()=>$a,normalizeContent:()=>ix,normalizeMediaType:()=>Nr,onMarkdownParsersReady:()=>Pa,parseAskUserQuestionPayload:()=>ur,parseSuggestRepliesPayload:()=>jf,parseWidgetPreferenceSlice:()=>rh,pickBestVoice:()=>ll,pluginRegistry:()=>Nl,registerIcons:()=>$x,registerStreamAnimationPlugin:()=>Ka,removeAskUserQuestionSheet:()=>Vr,renderComponentDirective:()=>_u,renderLoadingIndicatorWithFallback:()=>Og,renderLucideIcon:()=>le,resolveArtifactDisplay:()=>Df,resolveArtifactDisplayMode:()=>Dn,resolveConfigPreferences:()=>_l,resolveDockConfig:()=>Do,resolveSanitizer:()=>ic,resolveTokens:()=>su,resolveWelcomeConfig:()=>Cn,stripWebMcpPrefix:()=>Of,themeToCssVariables:()=>au,unregisterStreamAnimationPlugin:()=>Cg,validateImageFile:()=>cx,validateTheme:()=>mg});function fv(e,t){let o=e.voiceRecognition,n=t.voiceRecognition;return o?.enabled===!0!=(n?.enabled===!0)||o?.provider?.type!==n?.provider?.type||o?.provider?.custom!==n?.provider?.custom||o?.provider?.runtype?.createPlaybackEngine!==n?.provider?.runtype?.createPlaybackEngine||JSON.stringify(o?.provider?.runtype)!==JSON.stringify(n?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Wo(e){return e?.type==="runtype"||e?.type==="custom"}var LT=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function mv(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,o=typeof t=="function"?t():t;return!!o&&typeof o.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:LT()}catch{return!1}}var mt=e=>{let{fallbackImport:t,resetOnSetLoader:o=!1}=e,n=null,r=null,a=null;return{setLoader:p=>{n=p,o&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(n??t)().then(m=>(r=m,m)).catch(m=>{throw a=null,m}),a),provide:p=>{r=p},getSync:()=>r}};var{setLoader:IT,load:RT,provide:eI,getSync:Lf}=mt({fallbackImport:()=>import("./markdown-parsers-entry")}),sc=new Set,HT=()=>{let e=[...sc];sc.clear();for(let t of e)try{t()}catch{}},gv=IT,ac=()=>{let e=Lf();return e?Promise.resolve(e):RT().then(t=>(HT(),t))},Pa=e=>Lf()?()=>{}:(sc.add(e),()=>{sc.delete(e)});var On=Lf;var WT=e=>{if(!e)return;let t={},o=e;if(o.heading){let n=o.heading;t.heading=(r,a,i)=>n({type:"heading",raw:i,depth:a,text:r,tokens:[]})}if(o.code){let n=o.code;t.code=(r,a,i)=>n({type:"code",raw:"",text:r,lang:a,escaped:i})}if(o.blockquote){let n=o.blockquote;t.blockquote=r=>n({type:"blockquote",raw:"",text:r,tokens:[]})}if(o.table){let n=o.table;t.table=(r,a)=>n({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:a})}if(o.link){let n=o.link;t.link=(r,a,i)=>n({type:"link",raw:"",href:r,title:a??null,text:i,tokens:[]})}if(o.image){let n=o.image;t.image=(r,a,i)=>n({type:"image",raw:"",href:r,title:a??null,text:i})}if(o.list){let n=o.list;t.list=(r,a,i)=>n({type:"list",raw:"",ordered:a,start:i,loose:!1,items:[],itemsHtml:r})}if(o.listitem){let n=o.listitem;t.listitem=(r,a,i)=>n({type:"list_item",raw:"",task:a,checked:i,loose:!1,text:r,tokens:[]})}if(o.paragraph){let n=o.paragraph;t.paragraph=r=>n({type:"paragraph",raw:"",text:r,tokens:[]})}if(o.codespan){let n=o.codespan;t.codespan=r=>n({type:"codespan",raw:"",text:r})}if(o.strong){let n=o.strong;t.strong=r=>n({type:"strong",raw:"",text:r,tokens:[]})}if(o.em){let n=o.em;t.em=r=>n({type:"em",raw:"",text:r,tokens:[]})}if(o.del){let n=o.del;t.del=r=>n({type:"del",raw:"",text:r,tokens:[]})}if(o.html){let n=o.html;t.html=r=>n({type:"html",raw:r,text:r})}if(o.text){let n=o.text;t.text=r=>n({type:"text",raw:r,text:r})}if(o.checkbox){let n=o.checkbox;t.checkbox=r=>n({checked:r})}return o.hr&&(t.hr=o.hr),o.br&&(t.br=o.br),t},Qi=e=>{let t=null;return o=>{let n=On();if(!n)return dr(o);if(!t){let{Marked:r}=n,a=e?.markedOptions;t=new r({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let i=WT(e?.renderer);i&&t.use({renderer:i})}return t.parse(o)}},Yi=e=>e?Qi({markedOptions:e.options,renderer:e.renderer}):Qi(),BT=Qi(),If=e=>BT(e),dr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),yv=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),hv=e=>`%%FORM_PLACEHOLDER_${e}%%`,bv=(e,t)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,r)=>{try{let a=JSON.parse(r.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let i=hv(t.length);return t.push({token:i,type:String(a.type)}),i}}catch{return n}return n}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,r)=>{let a=hv(t.length);return t.push({token:a,type:r}),a}),o},vv=e=>{let t=Yi(e);return o=>{let n=[],r=bv(o,n),a=t(r);return n.forEach(({token:i,type:d})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${yv(d)}"></div>`;a=a.replace(c,p)}),a}},xv=e=>{let t=[],o=bv(e,t),n=If(o);return t.forEach(({token:r,type:a})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${yv(a)}"></div>`;n=n.replace(i,c)}),n};var OT={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},DT=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Rf=()=>{let e=null;return t=>{let o=On();if(!o)return dr(t);if(!e){let{DOMPurify:n}=o;e=n(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,a)=>{if(a.attrName==="src"||a.attrName==="href"){let i=a.attrValue;i.toLowerCase().startsWith("data:")&&!DT.test(i)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,OT)}},ic=e=>e===!1?null:typeof e=="function"?e:Rf();var Cv=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Sv=e=>e.includes("|"),wv=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(o=>o.trim())},_T=e=>`| ${e.join(" | ")} |`,NT=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,FT=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Av=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
3
|
+
`),o=!1;for(let n=0;n<t.length-1;n++){let r=t[n],a=t[n+1];if(!Sv(r)||Cv.test(r)||!Cv.test(a))continue;let i=wv(r).length;if(i<1)continue;let d=NT(i);t[n+1]!==d&&(t[n+1]=d,o=!0);let c=n+2;for(;c<t.length;c++){let u=t[c];if(u.trim()===""||!Sv(u))break;let p=_T(FT(wv(u),i));t[c]!==p&&(t[c]=p,o=!0)}n=c-1}return o?t.join(`
|
|
4
|
+
`):e};var Mv="var(--persona-md-table-scroll-fade, 24px)",Tv=new WeakSet;function Pv(e){e.querySelectorAll("table").forEach(o=>{if(o.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",o.replaceWith(r),r.appendChild(o)})}function Ev(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let n=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty("--persona-fade-l",n<=1?"0px":Mv),e.style.setProperty("--persona-fade-r",r<=1?"0px":Mv)}function Hf(e){Tv.has(e)||(Tv.add(e),e.addEventListener("scroll",t=>{let o=t.target;o?.classList?.contains("persona-table-scroll")&&Ev(o)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Ev)}var Ji="webmcp:",Wf=new Map,Lv=e=>{Wf.clear();for(let t of e){let o=t.title?.trim();o&&Wf.set(t.name,o)}},lc=e=>Wf.get(Of(e)),Bf=null,Iv=e=>{Bf=e};function Rv(e){if(e.length===0)return"0:empty";let t=e.map(o=>[o.name,o.description??"",o.parametersSchema?JSON.stringify(o.parametersSchema):"",o.origin??"",o.annotations?JSON.stringify(o.annotations):""].join("")).sort();return`${e.length}:${UT(t.join(""))}`}function kv(e,t){let o=3735928559^t,n=1103547991^t;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);o=Math.imul(o^a,2654435761),n=Math.imul(n^a,1597334677)}return o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),4294967296*(2097151&n)+(o>>>0)}function UT(e){let t=kv(e,0).toString(36),o=kv(e,2654435761).toString(36);return`${t}.${o}`}var Of=e=>e.startsWith(Ji)?e.slice(Ji.length):e,_r=e=>e.startsWith(Ji),Hv=()=>Bf?Bf():import("@mcp-b/webmcp-polyfill");var{setLoader:qT,load:VT}=mt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),Wv=qT,Bv=VT;function Bo(e){return e==="card"?"collapsed":e}function Nr(e){return e.split(";",1)[0].trim().toLowerCase()}function $T(e,t){if(!e)return;let o=Object.entries(e);for(let[r,a]of o)if(Nr(r)===t)return{mode:Bo(a),selector:Nr(r)};let n=`${t.split("/",1)[0]}/*`;for(let[r,a]of o)if(Nr(r)===n)return{mode:Bo(a),selector:n}}function Df(e,t){let o=e?.display,n=typeof o=="string"?{default:o}:o??{};if(t.file&&n.files){if(typeof n.files=="string")return{mode:Bo(n.files),matchedBy:{type:"files"}};let d=t.file.mimeType?Nr(t.file.mimeType):void 0,c=d?$T(n.files.byMediaType,d):void 0;if(d&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:d,selector:c.selector}};if(n.files.default)return{mode:Bo(n.files.default),matchedBy:{type:"files"}}}let r=n.byKind?.[t.artifactType];if(r)return{mode:Bo(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:Bo(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Bo(i),matchedBy:{type:"preferredMode"}}:n.default?{mode:Bo(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Dn(e,t){return Df(e,t).mode}function Zi(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var jT="agent_",zT="flow_";function Ov(e){return e.startsWith(jT)?{kind:"agentId",agentId:e}:e.startsWith(zT)?{kind:"flowId",flowId:e}:null}function Dv(e,t){let o=e.trim();if(!o)throw new Error("[Persona] `target` is empty.");let n=o.indexOf(":");if(n>0){let i=o.slice(0,n),d=o.slice(n+1);if(i==="runtype"){let u=Ov(d);if(u)return u;throw new Error(`[Persona] target "runtype:${d}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(d).payload}}let r=Ov(o);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(o).payload};throw new Error(`[Persona] target "${o}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${o}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function _v(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ka(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Fr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Nv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var Ur=Yt(uc(),1);var H=(e,t)=>{let o=document.createElement(e);return t&&(o.className=t),o};var Q=(e,t={},...o)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text),t.attrs)for(let[a,i]of Object.entries(t.attrs))n.setAttribute(a,i);if(t.style){let a=n.style,i=t.style;for(let d of Object.keys(i)){let c=i[d];c!=null&&(a[d]=c)}}let r=o.filter(a=>a!=null);return r.length>0&&n.append(...r),n},yo=(...e)=>e.filter(Boolean).join(" ");var tl="ask_user_question",el=8,La="data-persona-ask-sheet-for",YT="Other",JT="Other\u2026",qv="Type your own answer here",Vv="Send",ZT="Next",eE="Back",tE="Submit all",oE="Skip",nE=3,Nf="data-ask-current-index",Ff="data-ask-question-count",$v="data-ask-answers",Uf="data-ask-grouped",jv="data-ask-layout",rE=e=>e.layout==="pills"?"pills":"rows",sE=e=>e.getAttribute(jv)==="pills"?"pills":"rows",Uv=!1,zv=e=>e.replace(/["\\]/g,"\\$&"),cr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===tl,pc=e=>e?.features?.askUserQuestion??{},ur=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:o};let n=t.chunks;if(!n||n.length===0)return{payload:null,complete:o};try{let r=n.join(""),a=(0,Ur.parse)(r,Ur.STR|Ur.OBJ|Ur.ARR);if(a&&typeof a=="object")return{payload:a,complete:o}}catch{}return{payload:null,complete:o}},ol=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>el&&!Uv&&(Uv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${el}.`)),t.slice(0,el)},aE=e=>ol(e)[0]??null,iE=(e,t)=>ol(e)[t]??null,Kv=(e,t)=>{let o=t.styles;o&&(o.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",o.sheetBackground),o.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",o.sheetBorder),o.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",o.sheetShadow),o.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",o.pillBackground),o.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",o.pillBackgroundSelected),o.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",o.pillTextColor),o.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",o.pillTextColorSelected),o.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",o.pillBorderRadius),o.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",o.customInputBackground))},Gv=(e,t,o)=>{if(e!=="rows")return null;let n=H("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let r=H("span","persona-ask-row-check");n.appendChild(r)}else{let r=H("span","persona-ask-row-badge");r.textContent=String(o+1),n.appendChild(r)}return n},lE=(e,t,o,n)=>{let a=H("button",o==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),o==="rows"){let i=H("span","persona-ask-row-content"),d=H("span","persona-ask-row-label");if(d.textContent=e.label,i.appendChild(d),e.description){let u=H("span","persona-ask-row-description");u.textContent=e.description,i.appendChild(u)}a.appendChild(i);let c=Gv(o,n,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},dE=e=>{let o=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 o.setAttribute("aria-hidden","true"),o},cE=(e,t,o,n)=>{let a=H("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(c.length===0&&!o){for(let p=0;p<nE;p++)a.appendChild(dE(n));return a}if(c.forEach((p,m)=>{a.appendChild(lE(p,m,n,i))}),e?.allowFreeText!==!1){let p=n==="rows"?YT:JT;if(n==="rows"){let m=H("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(c.length)),m.setAttribute("data-ask-other-row","true");let h=H("span","persona-ask-row-content"),y=document.createElement("input");y.type="text",y.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",y.placeholder=t.freeTextPlaceholder??qv,y.setAttribute("data-ask-free-text-input","true"),y.setAttribute("aria-label",t.freeTextLabel??p),h.appendChild(y),m.appendChild(h);let C=Gv(n,i,c.length);C&&m.appendChild(C),a.appendChild(m)}else{let m=H("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??p,a.appendChild(m)}}return a},Xv=(e,t)=>{let n=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");n.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??qv,r.setAttribute("data-ask-free-text-input","true"),n.appendChild(r),t!=="rows"){let a=H("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Vv,a.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(a)}return n},uE=e=>{let t=H("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let o=H("button","persona-ask-multi-submit persona-pointer-events-auto");return o.type="button",o.textContent=e.submitLabel??Vv,o.setAttribute("data-ask-user-action","submit-multi"),o.disabled=!0,t.appendChild(o),t},pE=(e,t,o)=>{let n=H("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let r=H("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=o.backLabel??eE,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,n.appendChild(r);let a=H("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=H("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=o.skipLabel??oE,i.setAttribute("data-ask-user-action","skip"),a.appendChild(i);let d=H("button","persona-ask-nav-next persona-pointer-events-auto");d.type="button";let c=e===t-1;return d.textContent=c?o.submitAllLabel??tE:o.nextLabel??ZT,d.setAttribute("data-ask-user-action",c?"submit-all":"next"),d.disabled=!0,a.appendChild(d),n.appendChild(a),n},Ls=e=>{let t=e.getAttribute($v);if(!t)return{};try{let o=JSON.parse(t);return o&&typeof o=="object"?o:{}}catch{return{}}},Qv=(e,t)=>{e.setAttribute($v,JSON.stringify(t))},sn=e=>{let t=Number(e.getAttribute(Nf)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},fE=(e,t)=>{e.setAttribute(Nf,String(Math.max(0,Math.floor(t))))},Ia=e=>{let t=Number(e.getAttribute(Ff)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},qr=e=>e.getAttribute(Uf)==="true",mE=(e,t)=>{let o=e.agentMetadata?.askUserQuestionAnswers;if(!o||typeof o!="object")return{};let n={};return t.forEach((r,a)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(o,i)){let d=o[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},gE=(e,t)=>{let o=e.agentMetadata?.askUserQuestionIndex;return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(t-1,Math.floor(o)))},fc=(e,t)=>{let{payload:o}=ur(t),n=ol(o),r=Ls(e),a={},i=new Set;return n.forEach((d,c)=>{let u=typeof d?.question=="string"?d.question:"";u&&(i.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),i.add(u),Object.prototype.hasOwnProperty.call(r,c)&&(a[u]=r[c]))}),a},Yv=e=>{let t=Ls(e),o=sn(e),n=t[o],r=new Set;typeof n=="string"?r.add(n):Array.isArray(n)&&n.forEach(c=>r.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{let u=c.getAttribute("data-option-label")??"",p=r.has(u);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(a).map(c=>c.getAttribute("data-option-label")??"")),d=e.querySelector('[data-ask-free-text-input="true"]');d&&(typeof n=="string"&&n.length>0&&!i.has(n)?(d.value=n,d.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):d.value="")},Jv=e=>{if(!qr(e))return;let t=Ls(e),o=sn(e),n=t[o],r=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let d=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=d.length===0}},qf=(e,t,o)=>{let n=pc(o),r=sE(e),{payload:a,complete:i}=ur(t),d=qr(e),c=sn(e),u=Ia(e),p=d?iE(a,c):aE(a),m=!!p?.multiSelect,h=e.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=d?`${c+1}/${u}`:"");let y=e.querySelector('[data-ask-stepper="true"]');y&&y.remove();let C=e.querySelector('[data-ask-question="true"]');if(C){let T=typeof p?.question=="string"?p.question:"";C.textContent=T,C.classList.toggle("persona-ask-question-skeleton",!T&&!i)}let A=e.querySelector('[data-ask-pill-list="true"]');if(A){let T=cE(p,n,i,r);A.replaceWith(T)}if(r!=="rows"){let T=e.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(Xv(n,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!d&&m&&!M?e.appendChild(uE(n)):(!m||d)&&M&&M.remove(),e.setAttribute("data-multi-select",m?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(d){let T=pE(c,u,n);E?E.replaceWith(T):e.appendChild(T)}else E&&E.remove();Yv(e),Jv(e)},hE=(e,t,o)=>{let n=pc(t),r=rE(n),a=e.toolCall.id,i=ol(o),d=Math.max(1,i.length),c=d>1,u=mE(e,i),p=c?gE(e,d):0,m=H("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(La,a),m.setAttribute("data-tool-call-id",a),m.setAttribute("data-message-id",e.id),m.setAttribute(Ff,String(d)),m.setAttribute(Nf,String(p)),m.setAttribute(Uf,c?"true":"false"),m.setAttribute(jv,r),Qv(m,u),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Kv(m,n);let h=H("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),y=H("div","persona-ask-sheet-question persona-flex-1");y.setAttribute("data-ask-question","true"),y.textContent="",h.appendChild(y);let C=H("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",h.appendChild(C),m.appendChild(h);let M=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");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),r!=="rows"&&m.appendChild(Xv(n,r)),qf(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},yE=(e,t,o)=>{let{payload:n}=ur(t),r=Math.max(1,ol(n).length);r>Ia(e)&&(e.setAttribute(Ff,String(r)),r>1&&!qr(e)&&e.setAttribute(Uf,"true")),qf(e,t,o)},Zv=(e,t)=>{let o=H("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.setAttribute("data-bubble-type","ask-user-question");let n=pc(t);Kv(o,n);let r=H("span","persona-ask-stub-label"),{complete:a}=ur(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",o.appendChild(r),o},Ra=(e,t,o)=>{if(!o||!cr(e)||pc(t).enabled===!1)return;let r=e.toolCall.id;o.querySelectorAll(`[${La}]`).forEach(u=>{u.getAttribute(La)!==r&&u.remove()});let i=o.querySelector(`[${La}="${zv(r)}"]`);if(i){yE(i,e,t);return}let{payload:d}=ur(e),c=hE(e,t,d);o.appendChild(c)},Vr=(e,t)=>{if(!e)return;let o=t?`[${La}="${zv(t)}"]`:`[${La}]`;e.querySelectorAll(o).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},Vf=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),$r=(e,t)=>{let o=Ls(e),n=sn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete o[n]:o[n]=t,Qv(e,o),Yv(e),Jv(e)},mc=(e,t,o,n)=>{let r=Ia(e),a=Math.max(0,Math.min(r-1,n));fE(e,a),qf(e,t,o)};var _n="suggest_replies";var $f={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:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},gc={name:_n,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. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:$f,origin:"sdk",annotations:{readOnlyHint:!0}},tx=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Is=e=>e.variant==="tool"&&e.toolCall?.name===_n,jf=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let o=t?.suggestions;if(!Array.isArray(o))return[];let n=o.flatMap(r=>{if(typeof r=="string"){let d=r.trim();return d?[d]:[]}if(!r||typeof r!="object")return[];let a=r;if(typeof a.label!="string"||!a.label.trim())return[];let i={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(i.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(i.description=a.description.trim()),[i]});return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},hc=e=>{for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user")return null;if(!Is(o))continue;let n=jf(o.toolCall?.args);return n.length>0?n:null}return null},ex=new Set,bE=(e,t,o)=>{let n=`${e}:${t}:${o}`;ex.has(n)||(ex.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},jr=e=>{let t=e?.suggestions?.followUps,o=e?.features?.suggestReplies,n=i=>{let d=t?.[i],c=o?.[i];d===void 0||c===void 0||d!==c&&bE(i,c,d)};e&&(n("enabled"),n("expose"));let r=t?.enabled??o?.enabled??!0,a=r?t?.expose??o?.expose??!1:!1;return{enabled:r,expose:a}};var zf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:el,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Kf={name:tl,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:zf,origin:"sdk",annotations:{readOnlyHint:!0}},Ha=e=>{let t=[],o=e?.features?.askUserQuestion;return o?.expose===!0&&o.enabled!==!1&&t.push(Kf),jr(e).expose&&t.push(gc),t};var vE=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),xE=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),CE=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let o=vE(t.toolName);return o?{call:{toolCallId:t.toolCallId,toolName:o,args:xE(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:o,result:t.result}}:null},Gf=(e,t)=>{let o=[],n=[],r=[],a="",i,d=()=>{n.length!==0&&(o.push({role:"assistant",content:"",createdAt:a,toolCalls:n},{role:"tool",content:"",createdAt:a,toolResults:r}),n=[],r=[])};for(let c of e){let u=CE(c);if(u){let m=c.agentMetadata?.clientToolAnswer?.batch;n.length>0&&(m===void 0||m!==i)&&d(),n.length===0&&(a=c.createdAt,i=m),n.some(h=>h.toolCallId===u.call.toolCallId)||(n.push(u.call),r.push(u.result));continue}let p=t(c);p&&(d(),o.push(p))}return d(),o};var pr=Yt(uc(),1),yc=e=>e.replace(/\\n/g,`
|
|
5
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),bc=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)}},SE=e=>{let t=e.completedAt??Date.now(),o=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},ox=e=>e.status==="complete"?SE(e):e.status==="pending"?"Waiting":"",wE=15e3,AE=1200,nx=(e,t)=>{let o=t?.durationMs??wE,n=t?.chars??AE;return typeof e.durationMs=="number"?e.durationMs<o:(e.chunks??[]).join("").length<n},ME=e=>{let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var rx=e=>e.status==="complete"?ME(e):"Using tool...",vc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},rl=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return vc(t)},xc=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return vc(t)},Xf=(e,t,o)=>{if(!t)return o;let n=e.name?.trim()||"tool",r=rl(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,r)},Cc=(e,t)=>{let o=e.replace(/\{toolName\}/g,t),n=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,i;for(;(i=r.exec(o))!==null;)i.index>a&&nl(n,o.slice(a,i.index),[]),i[1]!==void 0?nl(n,i[1],["bold"]):i[2]!==void 0?nl(n,i[2],["italic"]):i[3]!==void 0&&nl(n,i[3],["dim"]),a=i.index+i[0].length;return a<o.length&&nl(n,o.slice(a),[]),n},nl=(e,t,o)=>{let n=t.split("{duration}");for(let r=0;r<n.length;r++)n[r]&&e.push({text:n[r],styles:o}),r<n.length-1&&e.push({text:"{duration}",styles:o,isDuration:!0})},TE=()=>{let e=null,t=0,o=n=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=n.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
6
6
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,d=n.match(i);if(d&&d[1])try{return d[1].replace(/\\n/g,`
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return d[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=t)return e!==null?{text:e,raw:n}:null;let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=o(n);return a!==null&&(e=a),t=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},sl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Sc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},wc=()=>{let e=xE();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Ac=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,pr.parse)(o,pr.STR|pr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?yc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=yc(r.text)))}catch{}return t=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},rx=e=>{let t=null,o=0,r=e||(a=>{if(!a||typeof a!="object")return null;let i=d=>typeof d=="string"?yc(d):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?yc(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return i(a.on_load_text)||i(a.text)||null;case"message":case"message_and_click":case"checkout":return i(a.text)||null;default:return i(a.text)||i(a.display_text)||i(a.message)||null}return i(a.text)||i(a.display_text)||i(a.message)||i(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let i=a.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(a.length<=o)return t!==null?{text:t,raw:a}:null;try{let d=(0,pr.parse)(a,pr.STR|pr.OBJ),c=r(d);c!==null&&(t=c)}catch{}return o=a.length,{text:t||"",raw:a}},close:()=>{}}},Mc=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var sx="4.23.0";var fr=sx;var Wa="[Image]";function ax(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Tc(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ba(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ix(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function an(e){return{type:"text",text:e}}function Ec(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function lx(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function dx(e,t=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var cx=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],SE=["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"],mr=[...cx,...SE];function wE(e){return cx.includes(e)||e.startsWith("image/")}function Pc(e){return wE(e.type)}function ux(e,t,o){return{type:"file",data:e,mimeType:t,filename:o}}async function px(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;Pc(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function fx(e,t=mr,o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function AE(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function mx(e,t){let o=AE(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]||o||"FILE"}var ME=["user","assistant","system"],TE=0;function gx(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function kc(e){return typeof e=="string"?e:void 0}function EE(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?an(t.text):null;case"image":return typeof t.image=="string"?Ec(t.image,{mimeType:kc(t.mimeType),alt:kc(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?ux(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...kc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...kc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function PE(e,t){let o=gx(t),n=e.map(i=>gx(i.timestamp)),r=new Array(e.length),a=0;for(;a<n.length;){let i=n[a];if(i!==null){r[a]=i,a+=1;continue}let d=a;for(;d+1<n.length&&n[d+1]===null;)d+=1;let c=d-a+1,u=a>0?r[a-1]:null,p=d+1<n.length?n[d+1]:null,m=p!==null&&o!==null?Math.min(p,o):p??o;for(let h=0;h<c;h+=1)r[a+h]=m!==null?m-(c-h):u!==null?u+h+1:TE+h;a=d+1}return r.map(i=>new Date(i).toISOString())}function hx(e,t){let o=PE(e,t?.beforeCreatedAt),n=[];return e.forEach((r,a)=>{if(typeof r?.id!="string"||r.id===""||!ME.includes(r.role))return;let i=r.role,d=o[a];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};n.push({id:r.id,role:i,content:"",createdAt:d,agentMetadata:c});return}if(typeof r.displayContent=="string"){n.push({id:r.id,role:i,content:r.displayContent,createdAt:d});return}if(typeof r.content=="string"){n.push({id:r.id,role:i,content:r.content,createdAt:d});return}if(Array.isArray(r.content)){let c=r.content.map(EE).filter(p=>p!==null),u=Tc(c);n.push({id:r.id,role:i,content:u||(Ba(c)?Wa:""),createdAt:d,...c.length>0&&{contentParts:c}});return}n.push({id:r.id,role:i,content:"",createdAt:d})}),n}function al(e){let t=e.content;if(typeof t!="string"||t==="")return;let o=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof o=="string"&&o===t))return t}function il(e,t){let o=new Map;for(let n of e)o.set(n.id,n);for(let n of t)o.set(n.id,n);return[...o.values()].sort((n,r)=>{let a=new Date(n.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(a)&&!Number.isNaN(i)&&a!==i)return a-i;let d=n.sequence??0,c=r.sequence??0;return d!==c?d-c:n.id.localeCompare(r.id)})}var kE="https://api.runtype.com/v1/dispatch",yx="https://api.runtype.com",_e=class extends Error{constructor(t,o,n){super(o),this.name="HistoryClientError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}},bx=32768,Xf=49152,vx=e=>{let t=e??{},o=typeof t.targetId=="string"?t.targetId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:o,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},xx=e=>"reason"in e?e.reason:void 0,Cx="The identity proof was not admitted; account history is unavailable",Sx="The identity proof was rejected",wx="The request carried no visitor credential",Ax="The stored visitor belongs to a different signed-in user",Qf=(e,t)=>e instanceof _e&&e.code===t;function LE(e){let t=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(n)return`attachment.${n}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var Yf=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 IE(e){switch(e){case"json":return Ac;case"regex-json":return wc;case"xml":return Mc;default:return Sc}}var Mx=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function RE(e,t){if(!e)return t;let o=e.trim(),n=t.trim();if(o.length===0)return t;if(n.length===0)return e;let r=Mx(o);if(!Mx(n))return e;if(!r||n===o||n.startsWith(o))return t;let i=sl(e);return sl(t)!==null&&i===null?t:e}var Rs=class{constructor(t={},o={}){this.config=t;this.historyInternals=o;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??kE,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??IE(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,t.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(t.webmcp))}createWebMcpBridge(t){return Wv().then(o=>{let n=new o.WebMcpBridge(t,{recordToolDisplayTitles:kv,getToolDisplayTitle:lc,loadPolyfill:Rv});return this.pendingWebMcpConfirmHandler!==void 0&&n.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=n,n}).catch(o=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",o),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.pendingWebMcpConfirmHandler=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,o,n){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(t,o,n):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:o,target:n,targetProviders:r}=this.config;if(!n)return{agentId:t,flowId:o};let a=Ov(n,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||yx}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let o=await this.initSession(),n=!1;for(;;){let r=o.conversationId,a=await this.readVisitorToken();if(o.durableRecovery?.enabled!==!0||!r||!a)throw new _e("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,d=new URLSearchParams({sessionId:o.sessionId,after:t.after}),c=await fetch(`${i}?${d}`,{method:"GET",headers:{"X-Persona-Version":fr,"X-Visitor-Token":a},signal:t.signal});if(c.status===401&&!n){n=!0,o=await this.recoverFromUnauthorized(await this.readErrorCode(c),null,!0);continue}if(!c.ok)throw await this.historyErrorFor(c,!0);return c}}async initSession(){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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let o=this.getHistoryIdentityStatus(),n=o.state===t.state&&xx(o)===xx(t);if(this.historyIdentityStatus=t,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let o=this.isHistoryCapable()&&!t.omitVisitorFields,n=!t.omitVisitorFields,r=null;(o||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let a=this.routing(),i=a.agentId??a.flowId,d=o||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...o&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(o||n)&&r?{visitorToken:r}:{},...o&&t.identityProof?{identityProof:t.identityProof}:{},...d?{conversationId:d}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(c)});if(!u.ok){let m=await u.json().catch(()=>({error:"Session initialization failed"}));if(o&&u.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),d)throw new _e("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw u.status===403&&m.error==="durable_recovery_disabled"?new _e("history_disabled","Durable recovery is disabled for this surface"):(o||t.durableResume)&&u.status===401&&m.error==="visitor_required"?new _e("visitor_required","Visitor credential no longer resolves"):d&&u.status===404?new _e("not_found","Conversation not found"):u.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):u.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let p=await u.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId?{targetId:p.targetId}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.durableRecovery?{durableRecovery:p.durableRecovery}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,o=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!o)return this.ordinaryInit(t,!1);let n=await this.readVisitorToken();if(t&&n)try{let r=await this.createClientSession({conversationId:t,durableResume:o});return o&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!Qf(r,"not_found")&&!Qf(r,"visitor_required")&&!Qf(r,"history_disabled"))throw r;return o&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,o){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.doOrdinaryInit(t,o)):this.doOrdinaryInit(t,o)}async doOrdinaryInit(t,o){let n=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),a=await this.claimFirstConversation(r);return this.finishInit(a,t,o)}async reinitWithProof(t){let o=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:o,identityProof:t}),a=this.finishInit(r,n,!1);return this.clientSession=a,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),a}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,o,n){let r=t.conversationId;return r&&o&&(n||r!==o)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:o,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let o=!1;return{session:t,commit:()=>{o||(o=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{o=!0}}}async prepareConversationSession(t,o){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new _e("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let n=o?.proof??null;if(!await this.readVisitorToken()&&!n)throw new _e("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let a=await this.createClientSession({conversationId:t,identityProof:n});return this.prepared(a)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){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 r={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(r)});if(!a.ok){let i=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:t,type:o})}async submitCSATFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:t,comment:o})}async submitNPSFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:t,comment:o})}historyUrl(t,o){let n=new URLSearchParams;for(let[a,i]of Object.entries(o))i===void 0||i===""||n.set(a,String(i));let r=n.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let o=this.config.features?.history?.scope;return o||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,o){let n=this.config.getIdentityProof;if(!n)return o&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;o&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await n()??null}catch{throw o&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new _e("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new _e("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return o&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,o,n){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(o);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new _e("proof_not_admitted",Cx);return r}async readErrorCode(t){let o=await t.json().catch(()=>({}));return typeof o.error=="string"?o.error:typeof o.message=="string"?o.message:""}async recoverFromUnauthorized(t,o,n){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new _e("invalid_identity_proof",Sx);if(r.includes("visitor token required"))throw new _e("visitor_token_missing",wx);if(r.includes("visitor_identity_mismatch")){if(!o)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new _e("visitor_identity_mismatch",Ax);return this.reinitWithProof(o)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new _e("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,o){let n=await this.readErrorCode(t);if(t.status===404)return new _e("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new _e("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&n.includes("identity_proof_not_admitted"))return o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new _e("proof_not_admitted",Cx);if(t.status===401){let r=n.toLowerCase();return r.includes("invalid_identity_proof")?(o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new _e("invalid_identity_proof",Sx)):r.includes("visitor token required")?new _e("visitor_token_missing",wx):r.includes("visitor_identity_mismatch")?new _e("visitor_identity_mismatch",Ax):new _e("unauthorized",n||"History request was not authorized")}return new _e("request_failed",n||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,o,n){let r=t?.toLowerCase()??null;if(o){if(r==="admitted"){n&&this.setHistoryIdentityStatus({state:"verified"});return}throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new _e("identity_contract_violation","Server reported an ignored identity proof on a success response"):new _e("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new _e("identity_contract_violation","Server admitted an identity proof that was never sent");n&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,o){this.assertHistoryUsable();let n=o.trackIdentity!==!1,r=await this.initSession(),a=null;this.resolveHistoryScope(o.scope)==="verified-user"&&(a=await this.resolveIdentityProof(r,n),a&&(r=await this.bindIdentity(r,a,n)));let i=this.historyInternals.visitorStore,d=!1;for(;;){let c=i?.revision()??0,u=await this.readVisitorToken();if(!u&&!o.visitorTokenOptional)throw new _e("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...o.query,sessionId:r.sessionId}),{method:o.method,headers:{"X-Persona-Version":fr,...u?{"X-Visitor-Token":u}:{},...a?{"X-Identity-Proof":a}:{},...o.body!==void 0?{"Content-Type":"application/json"}:{}},...o.body!==void 0?{body:JSON.stringify(o.body)}:{},...o.keepalive?{keepalive:!0}:{}});if(p.status===401&&!d){d=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),a,n);continue}if(!p.ok)throw await this.historyErrorFor(p,n);let m=p.headers.get("X-History-Identity-Status"),h=await p.json().catch(()=>{});if(i&&i.revision()!==c)throw new _e("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,a!==null,n),h}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new _e("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let o=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(o?.data)?o.data:[]).map(vx),nextCursor:typeof o?.nextCursor=="string"?o.nextCursor:null}}async getConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...o?.messageCursor?{messageCursor:o.messageCursor}:{}},...o?.scope?{scope:o.scope}:{}});return{summary:vx(n),messages:Array.isArray(n?.messages)?n.messages:[],nextMessageCursor:typeof n?.nextMessageCursor=="string"?n.nextMessageCursor:null,conversationRevision:typeof n?.conversationRevision=="string"?n.conversationRevision:null}}async finalizeDisplayProjections(t,o){this.assertHistoryUsable();let n=0;for(let c of o){let u=c.displayContent.length;if(u>bx)throw new _e("payload_too_large",`displayContent exceeds the ${bx} character limit`);n+=u}if(n>Xf)throw new _e("payload_too_large",`Display projection batch exceeds the ${Xf} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,a=r?.revision()??0,i=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:o},scope:"browser",keepalive:n<=Xf,trackIdentity:!1}),d=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return d&&this.clientSession?.conversationId===t&&(r?.revision()??0)===a&&this.historyInternals.setStoredConversationRevision?.(d),{conversationRevision:d}}async deleteConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...o?.scope?{scope:o.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async deleteAllConversations(t){let o=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(t,o){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,o):this.isAgentMode()?this.dispatchAgent(t,o):this.dispatchProxy(t,o)}async dispatchClientToken(t,o){let n=_v();this.currentClientTurnId=n;let r=()=>this.currentClientTurnId===n,a=i=>{r()&&o(i)};o({type:"status",status:"connecting"});try{let i=await this.initSession();if(new Date>=new Date(i.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let x=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:x}),x}let d=await this.buildPayload(t.messages),c=i.durableRecovery?.enabled===!0?await this.readVisitorToken():null,u=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,p=this.isHistoryCapable(),m={sessionId:i.sessionId,messages:t.messages.filter(Yf).map(x=>{let M=p?al(x):void 0;return{id:x.id,role:x.role,content:x.contentParts??x.llmContent??x.rawContent??x.content,...M!==void 0&&{displayContent:M}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:n,...t.interrupt&&{submitMode:"interrupt"}},{response:h,commit:y}=await this.sendWithClientToolsDiff(i.sessionId,d.clientTools,x=>{let M={...m,...x};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",M),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr,...c?{"X-Visitor-Token":c}:{}},body:JSON.stringify(M),signal:t.signal})});if(!h.ok){let x=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let S=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:S}),S}if(h.status===429){let S=new Error(x.hint||"Message limit reached for this session.");throw a({type:"error",error:S}),S}if(h.status===410&&x.error==="conversation_deleted"){let S=new _e("conversation_deleted","This conversation was deleted");throw a({type:"error",error:S}),S}let M=new Error(x.error||"Failed to send message");throw a({type:"error",error:M}),M}if(!h.body){let x=new Error("No response body received");throw a({type:"error",error:x}),x}y(),a({type:"status",status:"connected"});try{await this.streamResponse(h.body,a,t.assistantMessageId)}finally{a({type:"status",status:"idle"})}}catch(i){let d=i instanceof Error?i:new Error(String(i));throw!(d instanceof _e)&&!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&a({type:"error",error:d}),d}}async dispatchProxy(t,o){o({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o)}finally{o({type:"status",status:"idle"})}}async dispatchAgent(t,o){o({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}async processStream(t,o,n,r){o({type:"status",status:"connected"});try{await this.streamResponse(t,o,n,r)}finally{o({type:"status",status:"idle"})}}async resolveApproval(t,o){let n=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(n,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:o,streamResponse:!0})})}async sendWithClientToolsDiff(t,o,n,r){let a=!!(o&&o.length>0),i=a?Iv(o):void 0,d=this.clientToolsFingerprintSessionId===t,c=a&&d&&this.lastSentClientToolsFingerprint===i,u=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,m;for(let h=0;;h++){if(m=await n({...a&&(p||!c)&&o?{clientTools:o}:{},...u?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),m.status===409&&h===0&&a&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,o,n){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||yx}/resume`,i,d=null;if(r){let p=await this.initSession();i=p.sessionId,p.durableRecovery?.enabled===!0&&(d=await this.readVisitorToken())}let c={"Content-Type":"application/json",...d?{"X-Visitor-Token":d}:{},...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let u={executionId:t,toolOutputs:o,streamResponse:n?.streamResponse??!0,...n?.after?{after:n.after}:{}};if(i&&(u.sessionId=i),r&&i){let p=[...Ha(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(i,p,y=>{let x={...u,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",x),fetch(a,{method:"POST",headers:c,body:JSON.stringify(x),signal:n?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),m}return fetch(a,{method:"POST",headers:c,body:JSON.stringify(u),signal:n?.signal})}latestMentionContext(t){for(let o=t.length-1;o>=0;o--){let n=t[o];if(n.role==="user")return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async buildContextAggregate(t){let o={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let n=this.latestMentionContext(t);return n&&Object.assign(o,n),Object.keys(o).length?o:null}normalizeComposerOptions(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}applyInlineAgentModel(t,o){let n=o?.selectedModelId;return!n||!("model"in t)?t:this.config.composer?.models?.some(a=>a.id===n)?{...t,model:n}:t}async buildAgentPayload(t,o){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Yf).filter(u=>u.role==="user"||u.role==="assistant"||u.role==="system").filter(u=>!u.variant||u.variant==="assistant").sort((u,p)=>{let m=new Date(u.createdAt).getTime(),h=new Date(p.createdAt).getTime();return m-h}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),a=this.normalizeComposerOptions(o),i={agent:this.applyInlineAgentModel(this.config.agent??{agentId:n},a),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};a&&(i.composerOptions=a);let d=[...Ha(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];d.length>0&&(i.clientTools=d);let c=await this.buildContextAggregate(t);return c&&(i.context=c),i}async buildPayload(t,o){let n=t.slice().filter(Yf).sort((u,p)=>{let m=new Date(u.createdAt).getTime(),h=new Date(p.createdAt).getTime();return m-h}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),r=this.routing(),a={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[u,p]of Object.entries(r.targetPayload))u!=="messages"&&(a[u]=p);let i=[...Ha(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];i.length>0&&(a.clientTools=i);let d=await this.buildContextAggregate(t);d&&(a.context=d);let c=this.normalizeComposerOptions(o);if(c&&(a.composerOptions=c),this.requestMiddleware)try{let u=await this.requestMiddleware({payload:{...a},config:this.config});if(u&&typeof u=="object"){let p=u;return a.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=a.clientTools),p}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",u)}return a}async handleCustomSSEEvent(t,o,n,r,a,i){if(!this.parseSSEEvent)return!1;try{let d=await this.parseSSEEvent(t);if(d===null)return!1;let c=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return n.current=m,r(m),m},u=p=>n.current?n.current:c(p);if(d.text!==void 0){d.partId!==void 0&&i.current!==null&&d.partId!==i.current&&(n.current&&(n.current.streaming=!1,r(n.current)),c(d.partId)),d.partId!==void 0&&(i.current=d.partId);let p=u(d.partId);d.partId!==void 0&&!p.partId&&(p.partId=d.partId),p.content+=d.text,r(p)}return d.done&&(n.current&&(n.current.streaming=!1,r(n.current)),i.current=null,o({type:"status",status:"idle"})),d.error&&(i.current=null,o({type:"error",error:new Error(d.error)})),!0}catch(d){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",d),!1}}async streamResponse(t,o,n,r){let a=t.getReader(),i=new TextDecoder,d="",c=Date.now(),u=0,p=()=>c+u++,m=z=>{let E=z.reasoning?{...z.reasoning,chunks:[...z.reasoning.chunks]}:void 0,F=z.toolCall?{...z.toolCall,chunks:z.toolCall.chunks?[...z.toolCall.chunks]:void 0}:void 0,K=z.tools?z.tools.map(Y=>({...Y,chunks:Y.chunks?[...Y.chunks]:void 0})):void 0;return{...z,reasoning:E,toolCall:F,tools:K}},h=z=>{if(z.role!=="assistant"||z.variant)return!0;let E=Array.isArray(z.contentParts)&&z.contentParts.length>0,F=typeof z.rawContent=="string"&&z.rawContent.trim()!=="";return typeof z.content=="string"&&z.content.trim()!==""||E||F||!!z.stopReason},y=z=>{h(z)&&o({type:"message",message:m(z)})},x=null,M=null,S={current:null},k={current:null},P=null,H="",b=new Map,w=new Map,C=new Map,L=new Map,N=new Map,X=n,V=!1,T=()=>{if(x)return x;let z,E="",F=P;return!V&&X?(z=X,V=!0,E=r??""):X&&F?z=`${X}_${F}`:z=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:z,role:"assistant",content:E,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},y(x),x},O=z=>{let E=L.get(z);if(E)return E;let F={id:`reason-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:z,status:"streaming",chunks:[]}};return L.set(z,F),y(F),F},D=new Set,W=new Map,ee=new Set,G=new Map,ue=z=>{if(!z)return!1;let E=z.replace(/_+/g,"_").replace(/^_|_$/g,"");return E==="emit_artifact_markdown"||E==="emit_artifact_component"},ae=z=>{let E=N.get(z);if(E)return E;let F={id:`tool-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:z,status:"pending"}};return N.set(z,F),y(F),F},ye=z=>{if(typeof z=="number"&&Number.isFinite(z))return z;if(typeof z=="string"){let E=Number(z);if(!Number.isNaN(E)&&Number.isFinite(E))return E;let F=Date.parse(z);if(!Number.isNaN(F))return F}return Date.now()},Re=z=>{if(typeof z=="string")return z;if(z==null)return"";try{return JSON.stringify(z)}catch{return String(z)}},be=new Map,pe=new Map,yt=(z,E)=>{let F=Re(E),K=pe.get(z.id),Y=RE(K,F);z.rawContent=Y;let te=be.get(z.id),ge=Ke=>{let Ve=z.content??"";Ke.trim()!==""&&(Ve.trim().length===0||Ke.startsWith(Ve)||Ke.trimStart().startsWith(Ve.trim()))&&(z.content=Ke)},Me=()=>{if(te){let Ke=te.close?.();Ke instanceof Promise&&Ke.catch(()=>{})}be.delete(z.id),pe.delete(z.id),z.streaming=!1,y(z)};if(!te){ge(F),Me();return}let Ee=sl(Y);if(Ee!==null&&Ee.trim()!==""){ge(Ee),Me();return}let We=Ke=>{let Ve=typeof Ke=="string"?Ke:Ke?.text??null;if(Ve!==null&&Ve.trim()!=="")return Ve;let gt=te.getExtractedText();return gt!==null&>.trim()!==""?gt:F},st;try{st=te.processChunk(Y)}catch{ge(F),Me();return}if(st instanceof Promise){st.then(Ke=>{ge(We(Ke)),Me()}).catch(()=>{ge(F),Me()});return}ge(We(st)),Me()},Pe=null,q=(z,E,F,K)=>{z.rawContent=E,be.has(z.id)||be.set(z.id,this.createStreamParser());let Y=be.get(z.id),te=E.trim().startsWith("{")||E.trim().startsWith("[");if(te&&pe.set(z.id,E),Y.__isPlainTextParser===!0){z.content=K!==void 0?E:z.content+F,pe.delete(z.id),be.delete(z.id),z.rawContent=void 0,y(z);return}let Me=Y.processChunk(E);if(Me instanceof Promise)Me.then(Ee=>{let We=typeof Ee=="string"?Ee:Ee?.text??null;We!==null&&We.trim()!==""?(z.content=We,y(z)):!te&&!E.trim().startsWith("<")&&(z.content=K!==void 0?E:z.content+F,pe.delete(z.id),be.delete(z.id),z.rawContent=void 0,y(z))}).catch(()=>{z.content=K!==void 0?E:z.content+F,pe.delete(z.id),be.delete(z.id),z.rawContent=void 0,y(z)});else{let Ee=typeof Me=="string"?Me:Me?.text??null;Ee!==null&&Ee.trim()!==""?(z.content=Ee,y(z)):!te&&!E.trim().startsWith("<")&&(z.content=K!==void 0?E:z.content+F,pe.delete(z.id),be.delete(z.id),z.rawContent=void 0,y(z))}},Ue=(z,E)=>{let F=E??z.content;if(F==null||F===""){z.streaming=!1,y(z);return}let Y=pe.get(z.id)??Re(F);z.rawContent=Y;let te=be.get(z.id),ge=null,Me=!1;if(te&&(ge=te.getExtractedText(),ge===null&&(ge=sl(Y)),ge===null)){let Ee=te.processChunk(Y);Ee instanceof Promise?(Me=!0,Ee.then(We=>{let st=typeof We=="string"?We:We?.text??null;st!==null&&(z.content=st,z.streaming=!1,be.delete(z.id),pe.delete(z.id),y(z))}).catch(()=>{})):ge=typeof Ee=="string"?Ee:Ee?.text??null}if(!Me){ge!==null&&ge.trim()!==""?z.content=ge:pe.has(z.id)||(z.content=Re(F));let Ee=be.get(z.id);if(Ee){let We=Ee.close?.();We instanceof Promise&&We.catch(()=>{}),be.delete(z.id)}pe.delete(z.id),z.streaming=!1,y(z)}},Je=(z,E,F)=>{let K=w.get(z);if(K)return K;let Y={id:`nested-${E}-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...F?{variant:F}:{},...F==="reasoning"?{reasoning:{id:z,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:E}};return w.set(z,Y),y(Y),Y},so=[],Le,qe=new Map,ve=0,po="agent",dn=!1,Vn=null,wt=null,$n=this.config.iterationDisplay??"separate";for(Le=()=>{for(let z=0;z<so.length;z++){let E=so[z];if(!dn&&po!=="flow"&&typeof E.stepType=="string"&&(po="flow"),E.type==="reasoning_start"){let F=typeof E.id=="string"?E.id:null,K=typeof E.parentToolCallId=="string"&&E.parentToolCallId?E.parentToolCallId:null;if(F&&K){b.set(F,K),Je(F,K,"reasoning");continue}let Y=E.id,te=O(Y);te.reasoning=te.reasoning??{id:Y,status:"streaming",chunks:[]},te.reasoning.startedAt=te.reasoning.startedAt??Date.now(),te.reasoning.completedAt=void 0,te.reasoning.durationMs=void 0,(E.scope==="loop"||E.scope==="turn")&&(te.reasoning.scope=E.scope),te.streaming=!0,te.reasoning.status="streaming",y(te)}else if(E.type==="reasoning_delta"){let F=typeof E.id=="string"?E.id:null;if(F&&b.has(F)&&w.has(F)){let te=w.get(F),ge=E.delta;ge&&te.reasoning&&(te.reasoning.chunks.push(String(ge)),y(te));continue}let K=E.id,Y=O(K);Y.reasoning=Y.reasoning??{id:K,status:"streaming",chunks:[]},Y.reasoning.startedAt=Y.reasoning.startedAt??Date.now(),E.delta&&Y.reasoning.chunks.push(E.delta),Y.reasoning.status="streaming",Y.streaming=!0,y(Y)}else if(E.type==="reasoning_complete"){let F=typeof E.id=="string"?E.id:null;if(F&&b.has(F)&&w.has(F)){let ge=w.get(F);if(ge.reasoning){let Me=typeof E.text=="string"?E.text:"";Me&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(Me),ge.reasoning.status="complete",ge.streaming=!1,y(ge)}b.delete(F),w.delete(F);continue}let K=E.id,Y=typeof E.text=="string"?E.text:"";!L.get(K)&&(Y||E.scope==="loop")&&O(K);let te=L.get(K);if(te?.reasoning){(E.scope==="loop"||E.scope==="turn")&&(te.reasoning.scope=E.scope),Y&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push(Y),te.reasoning.status="complete",te.reasoning.completedAt=Date.now();let ge=te.reasoning.startedAt??Date.now();te.reasoning.durationMs=Math.max(0,(te.reasoning.completedAt??Date.now())-ge),te.streaming=!1,y(te)}}else if(E.type==="tool_start"){x&&(x.streaming=!1,y(x),x=null),typeof E.iteration=="number"&&(ve=E.iteration);let F=E.toolCallId,K=E.toolName;if(ue(K)){D.add(F);continue}let Y=ae(F),te=Y.toolCall??{id:F,status:"pending"};te.name=K??te.name,te.status="running",te.success=void 0,te.error=void 0,te.duration=void 0,E.parameters!==void 0&&(te.args=E.parameters),te.startedAt=te.startedAt??ye(E.startedAt),te.completedAt=void 0,te.durationMs=void 0,Y.toolCall=te,Y.streaming=!0,E.executionId&&(Y.agentMetadata={executionId:E.executionId,iteration:E.iteration}),y(Y)}else if(E.type==="tool_output_delta"){let F=E.toolCallId;if(D.has(F))continue;let K=ae(F),Y=K.toolCall??{id:F,status:"running"};Y.startedAt=Y.startedAt??Date.now();let te=E.delta;te&&(Y.chunks=Y.chunks??[],Y.chunks.push(String(te))),Y.status="running",K.toolCall=Y,K.streaming=!0,E.executionId&&(K.agentMetadata=K.agentMetadata??{executionId:E.executionId,iteration:ve}),y(K)}else if(E.type==="tool_complete"){let F=E.toolCallId;if(D.has(F)){D.delete(F);continue}let K=ae(F),Y=K.toolCall??{id:F,status:"running"};Y.status="complete",E.result!==void 0&&(Y.result=E.result),Y.name=E.toolName??Y.name,Y.success=E.success,Y.error=E.error,Y.completedAt=Date.now();let te=E.executionTime;if(typeof te=="number")Y.durationMs=te,Y.duration=te;else{let ge=Y.startedAt??Date.now();Y.durationMs=Math.max(0,(Y.completedAt??Date.now())-ge)}K.toolCall=Y,K.streaming=!1,E.executionId&&(K.agentMetadata=K.agentMetadata??{executionId:E.executionId,iteration:E.iteration??ve}),y(K)}else if(E.type==="await"&&E.toolName){let F=typeof E.toolCallId=="string"&&E.toolCallId.length>0?E.toolCallId:void 0,K=F??E.toolId??`local-${p()}`,Y=ae(K),te=E.toolName,ge=E.origin==="webmcp"&&!_r(te)?`webmcp:${te}`:te,Me=_r(ge),Ee=Y.toolCall??{id:K,status:"pending"};Ee.name=ge,Ee.args=E.parameters,Ee.status=Me?"running":"complete",Ee.chunks=Ee.chunks??[],Ee.startedAt=Ee.startedAt??ye(E.awaitedAt),Me?(Ee.completedAt=void 0,Ee.duration=void 0,Ee.durationMs=void 0):Ee.completedAt=Ee.completedAt??Ee.startedAt,Y.toolCall=Ee,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:E.executionId??Y.agentMetadata?.executionId,awaitingLocalTool:!0,...F?{webMcpToolCallId:F}:{}},y(Y)}else if(E.type==="text_start"){let F=typeof E.id=="string"?E.id:null,K=typeof E.parentToolCallId=="string"&&E.parentToolCallId?E.parentToolCallId:null;if(F&&K){b.set(F,K);continue}let Y=x;Y&&(po==="flow"?(Ue(Y),Pe=Y):(Y.streaming=!1,y(Y)),x=null),P=typeof E.id=="string"?E.id:P,H=""}else if(E.type==="text_delta"){let F=typeof E.id=="string"?E.id:null,K=F?b.get(F):void 0;if(F&&K){let ge=typeof E.delta=="string"?E.delta:"",Me=(C.get(F)??"")+ge;if(C.set(F,Me),Me.trim()==="")continue;let Ee=Je(F,K);Ee.agentMetadata={...Ee.agentMetadata,executionId:E.executionId,parentToolId:K},q(Ee,Me,ge,void 0);continue}if(P=typeof E.id=="string"?E.id:P,po==="flow"){let ge=typeof E.delta=="string"?E.delta:"";if(H+=ge,H.trim()==="")continue;let Me=T();Me.agentMetadata={executionId:E.executionId,iteration:ve},q(Me,H,ge,void 0),M=Me;continue}let Y=typeof E.delta=="string"?E.delta:"";H+=Y;let te=T();te.agentMetadata={executionId:E.executionId,iteration:ve,turnId:Vn??void 0,agentName:wt?.agentName},q(te,H,Y,void 0),M=te}else if(E.type==="text_complete"){let F=typeof E.id=="string"?E.id:null;if(F&&b.has(F)){let Y=w.get(F);Y&&Ue(Y),b.delete(F),C.delete(F),w.delete(F);continue}let K=x;K&&(po==="flow"?(Ue(K),Pe=K):((K.content??"")===""&&typeof E.text=="string"&&(K.content=E.text),K.streaming=!1,y(K)),x=null),P=null,H=""}else if(E.type==="step_complete"){if(E.stepType==="tool")continue;if(E.success===!1){let F=E.error||"Step failed";o({type:"error",error:new Error(F)});let K=x;K&&K.streaming&&(K.streaming=!1,y(K)),o({type:"status",status:"idle"});continue}{let F=Pe;Pe=null;let K=E.stopReason,te=(E.result&&typeof E.result=="object"?E.result:null)?.response;if(F)K&&(F.stopReason=K),te!=null?yt(F,te):F.streaming!==!1&&(be.delete(F.id),pe.delete(F.id),F.streaming=!1,y(F));else{let ge=te!=null&&te!=="";if(ge||K){let Me=T();K&&(Me.stopReason=K),ge?Ue(Me,te):(Me.streaming=!1,y(Me))}}continue}}else if(E.type==="execution_start")po=E.kind==="flow"?"flow":"agent",dn=!0,po==="agent"&&(wt={executionId:E.executionId,agentId:E.agentId??"virtual",agentName:E.agentName??""});else if(E.type==="turn_start"){let F=typeof E.iteration=="number"?E.iteration:ve;if(F!==ve){if($n==="separate"&&F>1){let K=x;K&&(K.streaming=!1,y(K),x=null)}ve=F}Vn=typeof E.id=="string"?E.id:null,M=null}else if(E.type==="tool_input_delta"){let F=E.toolCallId;if(F){let K=N.get(F);K?.toolCall&&(K.toolCall.chunks=K.toolCall.chunks??[],K.toolCall.chunks.push(E.delta??""),y(K))}}else if(E.type==="tool_input_complete"){if(D.has(E.toolCallId))continue;let F=ae(E.toolCallId),K=F.toolCall;K.args=E.parameters,K.name=E.toolName??K.name,y(F)}else if(E.type==="turn_complete"){let F=E.stopReason,K=x??M;if(F&&K!==null){let Y=E.id;(!Y||K.agentMetadata?.turnId===Y)&&(K.stopReason=F,y(K))}Vn===E.id&&(Vn=null)}else if(E.type==="media_start"){let F=String(E.id);qe.set(F,{mediaType:typeof E.mediaType=="string"?E.mediaType:void 0,toolCallId:E.toolCallId,parts:[]})}else if(E.type==="media_delta"){let F=qe.get(String(E.id));F&&typeof E.delta=="string"&&F.parts.push(E.delta)}else if(E.type==="media_complete"){let F=String(E.id),K=qe.get(F);qe.delete(F);let Y=(typeof E.mediaType=="string"?E.mediaType:void 0)??K?.mediaType??"application/octet-stream",te=typeof E.data=="string"?E.data:void 0,ge=typeof E.url=="string"?E.url:K&&K.parts.length>0?K.parts.join(""):void 0,Me=null;if(te)Me={type:"media",data:te,mediaType:Y};else if(ge){let Ke=Y.toLowerCase();Me={type:Ke==="image"||Ke.startsWith("image/")?"image-url":"file-url",url:ge,mediaType:Y}}let Ee=E.toolCallId??K?.toolCallId,We=Me?[Me]:[],st=[];for(let Ke of We){if(!Ke||typeof Ke!="object")continue;let Ve=Ke,gt=typeof Ve.type=="string"?Ve.type:void 0,zt=typeof Ve.mediaType=="string"?Ve.mediaType.toLowerCase():"",It=null,ao="";if(gt==="media"){let wo=typeof Ve.data=="string"?Ve.data:void 0;if(!wo)continue;ao=zt.length>0?zt:"application/octet-stream",It=`data:${ao};base64,${wo}`}else if(gt==="image-url"){let wo=typeof Ve.url=="string"?Ve.url:void 0;if(!wo)continue;ao=zt,It=wo}else if(gt==="file-url"){let wo=typeof Ve.url=="string"?Ve.url:void 0;if(!wo)continue;ao=zt,It=wo}else continue;if(It)if(gt==="image-url"||ao.startsWith("image/"))st.push({type:"image",image:It,...ao.includes("/")?{mimeType:ao}:{}});else if(ao.startsWith("audio/"))st.push({type:"audio",audio:It,mimeType:ao});else if(ao.startsWith("video/"))st.push({type:"video",video:It,mimeType:ao});else{let wo=ao||"application/octet-stream";st.push({type:"file",data:It,mimeType:wo,filename:LE(wo)})}}if(st.length>0){let Ke=p(),Ve=Ee,zt={id:`agent-media-${typeof Ve=="string"&&Ve.length>0?`${Ve}-${Ke}`:String(Ke)}`,role:"assistant",content:"",contentParts:st,createdAt:new Date().toISOString(),streaming:!1,sequence:Ke,agentMetadata:{executionId:E.executionId,iteration:ve}};y(zt);let It=x;It&&(It.streaming=!1,y(It)),x=null,S.current=null}}else if(E.type==="execution_complete"){let F=x;F&&(E.kind==="flow"&&F.streaming!==!1?Ue(F):(F.streaming=!1,y(F)),x=null),P=null,H="",Pe=null,o({type:"status",status:"idle",terminal:!0})}else if(E.type==="execution_error"){let F=typeof E.error=="string"?E.error:E.error?.message??"Execution error";o({type:"error",error:new Error(F)})}else if(E.type!=="ping"){if(E.type==="approval_start"){let F=E.approvalId??`approval-${p()}`,K={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:F,status:"pending",agentId:wt?.agentId??"virtual",executionId:E.executionId??wt?.executionId??"",toolName:E.toolName??"",toolType:E.toolType,description:E.description??`Execute ${E.toolName??"tool"}`,...typeof E.reason=="string"&&E.reason?{reason:E.reason}:{},parameters:E.parameters}};y(K)}else if(E.type==="approval_complete"){let F=E.approvalId;if(F){let Y={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:F,status:E.decision??"approved",agentId:wt?.agentId??"virtual",executionId:E.executionId??wt?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};y(Y)}}else if(E.type==="artifact_start"||E.type==="artifact_delta"||E.type==="artifact_update"||E.type==="artifact_complete"){if(E.type==="artifact_start"){let F=E.artifactType,K=String(E.id),Y=typeof E.title=="string"?E.title:void 0,te=E.file,ge;if(te&&typeof te=="object"&&!Array.isArray(te)&&typeof te.path=="string"&&typeof te.mimeType=="string"&&(ge={path:te.path,mimeType:te.mimeType,...typeof te.language=="string"?{language:te.language}:{}}),o({type:"artifact_start",id:K,artifactType:F,title:Y,component:typeof E.component=="string"?E.component:void 0,...ge?{file:ge}:{}}),G.set(K,{markdown:"",title:Y,file:ge}),!ee.has(K)){ee.add(K);let Me=Dn(this.config.features?.artifacts,{artifactType:F,...ge?{file:ge}:{}}),Ee=typeof E.component=="string"?E.component:void 0,We={id:`artifact-ref-${K}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:Zi(Me,{artifactId:K,title:Y,artifactType:F,status:"streaming",...ge?{file:ge}:{},...Ee?{component:Ee}:{}})};W.set(K,We),y(We)}}else if(E.type==="artifact_delta"){let F=String(E.id),K=typeof E.delta=="string"?E.delta:String(E.delta??"");o({type:"artifact_delta",id:F,artDelta:K});let Y=G.get(F);Y&&(Y.markdown+=K)}else if(E.type==="artifact_update"){let F=E.props&&typeof E.props=="object"&&!Array.isArray(E.props)?E.props:{};o({type:"artifact_update",id:String(E.id),props:F,component:typeof E.component=="string"?E.component:void 0});let K=G.get(String(E.id));K&&(K.props={...K.props??{},...F})}else if(E.type==="artifact_complete"){let F=String(E.id);o({type:"artifact_complete",id:F});let K=W.get(F);if(K){K.streaming=!1;try{let Y=JSON.parse(K.rawContent??"{}");if(Y.props){Y.props.status="complete";let te=G.get(F);te?.markdown&&(Y.props.markdown=te.markdown),te?.file&&(Y.props.file=te.file),Y.component==="PersonaArtifactInline"&&te?.props&&Object.keys(te.props).length>0&&(Y.props.componentProps=te.props)}K.rawContent=JSON.stringify(Y)}catch{}G.delete(F),y(K),W.delete(F)}}}else if(E.type==="error"&&E.recoverable===!1&&E.error!=null&&E.error!==""){let F=typeof E.error=="string"?E.error:E.error?.message!=null?String(E.error.message):"Execution error";o({type:"error",error:new Error(F)});let K=x;K&&K.streaming&&(K.streaming=!1,y(K)),o({type:"status",status:"idle"})}}}so.length=0};;){let{done:z,value:E}=await a.read();if(z)break;d+=i.decode(E,{stream:!0});let F=d.split(`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return d[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=t)return e!==null?{text:e,raw:n}:null;let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=o(n);return a!==null&&(e=a),t=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},sl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Sc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},wc=()=>{let e=TE();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Ac=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,pr.parse)(o,pr.STR|pr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?yc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=yc(r.text)))}catch{}return t=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},sx=e=>{let t=null,o=0,r=e||(a=>{if(!a||typeof a!="object")return null;let i=d=>typeof d=="string"?yc(d):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?yc(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return i(a.on_load_text)||i(a.text)||null;case"message":case"message_and_click":case"checkout":return i(a.text)||null;default:return i(a.text)||i(a.display_text)||i(a.message)||null}return i(a.text)||i(a.display_text)||i(a.message)||i(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let i=a.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(a.length<=o)return t!==null?{text:t,raw:a}:null;try{let d=(0,pr.parse)(a,pr.STR|pr.OBJ),c=r(d);c!==null&&(t=c)}catch{}return o=a.length,{text:t||"",raw:a}},close:()=>{}}},Mc=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ax="4.23.2";var fr=ax;var Wa="[Image]";function ix(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Tc(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ba(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function lx(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function an(e){return{type:"text",text:e}}function Ec(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function dx(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function cx(e,t=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var ux=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],PE=["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"],mr=[...ux,...PE];function kE(e){return ux.includes(e)||e.startsWith("image/")}function Pc(e){return kE(e.type)}function px(e,t,o){return{type:"file",data:e,mimeType:t,filename:o}}async function fx(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;Pc(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function mx(e,t=mr,o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function LE(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function gx(e,t){let o=LE(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]||o||"FILE"}var IE=["user","assistant","system"],RE=0;function hx(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function kc(e){return typeof e=="string"?e:void 0}function HE(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?an(t.text):null;case"image":return typeof t.image=="string"?Ec(t.image,{mimeType:kc(t.mimeType),alt:kc(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?px(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...kc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...kc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function WE(e,t){let o=hx(t),n=e.map(i=>hx(i.timestamp)),r=new Array(e.length),a=0;for(;a<n.length;){let i=n[a];if(i!==null){r[a]=i,a+=1;continue}let d=a;for(;d+1<n.length&&n[d+1]===null;)d+=1;let c=d-a+1,u=a>0?r[a-1]:null,p=d+1<n.length?n[d+1]:null,m=p!==null&&o!==null?Math.min(p,o):p??o;for(let h=0;h<c;h+=1)r[a+h]=m!==null?m-(c-h):u!==null?u+h+1:RE+h;a=d+1}return r.map(i=>new Date(i).toISOString())}function yx(e,t){let o=WE(e,t?.beforeCreatedAt),n=[];return e.forEach((r,a)=>{if(typeof r?.id!="string"||r.id===""||!IE.includes(r.role))return;let i=r.role,d=o[a];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};n.push({id:r.id,role:i,content:"",createdAt:d,agentMetadata:c});return}if(typeof r.displayContent=="string"){n.push({id:r.id,role:i,content:r.displayContent,createdAt:d});return}if(typeof r.content=="string"){n.push({id:r.id,role:i,content:r.content,createdAt:d});return}if(Array.isArray(r.content)){let c=r.content.map(HE).filter(p=>p!==null),u=Tc(c);n.push({id:r.id,role:i,content:u||(Ba(c)?Wa:""),createdAt:d,...c.length>0&&{contentParts:c}});return}n.push({id:r.id,role:i,content:"",createdAt:d})}),n}function al(e){let t=e.content;if(typeof t!="string"||t==="")return;let o=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof o=="string"&&o===t))return t}function il(e,t){let o=new Map;for(let n of e)o.set(n.id,n);for(let n of t)o.set(n.id,n);return[...o.values()].sort((n,r)=>{let a=new Date(n.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(a)&&!Number.isNaN(i)&&a!==i)return a-i;let d=n.sequence??0,c=r.sequence??0;return d!==c?d-c:n.id.localeCompare(r.id)})}var BE="https://api.runtype.com/v1/dispatch",bx="https://api.runtype.com",_e=class extends Error{constructor(t,o,n){super(o),this.name="HistoryClientError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}},vx=32768,Qf=49152,xx=e=>{let t=e??{},o=typeof t.targetId=="string"?t.targetId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:o,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},Cx=e=>"reason"in e?e.reason:void 0,Sx="The identity proof was not admitted; account history is unavailable",wx="The identity proof was rejected",Ax="The request carried no visitor credential",Mx="The stored visitor belongs to a different signed-in user",Yf=(e,t)=>e instanceof _e&&e.code===t;function OE(e){let t=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(n)return`attachment.${n}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var Jf=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),Tx=e=>e.slice().sort((t,o)=>new Date(t.createdAt).getTime()-new Date(o.createdAt).getTime()),Ex=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function DE(e){switch(e){case"json":return Ac;case"regex-json":return wc;case"xml":return Mc;default:return Sc}}var Px=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function _E(e,t){if(!e)return t;let o=e.trim(),n=t.trim();if(o.length===0)return t;if(n.length===0)return e;let r=Px(o);if(!Px(n))return e;if(!r||n===o||n.startsWith(o))return t;let i=sl(e);return sl(t)!==null&&i===null?t:e}var Rs=class{constructor(t={},o={}){this.config=t;this.historyInternals=o;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??BE,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??DE(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,t.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(t.webmcp))}createWebMcpBridge(t){return Bv().then(o=>{let n=new o.WebMcpBridge(t,{recordToolDisplayTitles:Lv,getToolDisplayTitle:lc,loadPolyfill:Hv});return this.pendingWebMcpConfirmHandler!==void 0&&n.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=n,n}).catch(o=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",o),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.pendingWebMcpConfirmHandler=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,o,n){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(t,o,n):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:o,target:n,targetProviders:r}=this.config;if(!n)return{agentId:t,flowId:o};let a=Dv(n,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||bx}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let o=await this.initSession(),n=!1;for(;;){let r=o.conversationId,a=await this.readVisitorToken();if(o.durableRecovery?.enabled!==!0||!r||!a)throw new _e("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,d=new URLSearchParams({sessionId:o.sessionId,after:t.after}),c=await fetch(`${i}?${d}`,{method:"GET",headers:{"X-Persona-Version":fr,"X-Visitor-Token":a},signal:t.signal});if(c.status===401&&!n){n=!0,o=await this.recoverFromUnauthorized(await this.readErrorCode(c),null,!0);continue}if(!c.ok)throw await this.historyErrorFor(c,!0);return c}}async initSession(){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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let o=this.getHistoryIdentityStatus(),n=o.state===t.state&&Cx(o)===Cx(t);if(this.historyIdentityStatus=t,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let o=this.isHistoryCapable()&&!t.omitVisitorFields,n=!t.omitVisitorFields,r=null;(o||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let a=this.routing(),i=a.agentId??a.flowId,d=o||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...o&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(o||n)&&r?{visitorToken:r}:{},...o&&t.identityProof?{identityProof:t.identityProof}:{},...d?{conversationId:d}:t.storedSessionId?{sessionId:t.storedSessionId}:{}};t.signal?.throwIfAborted();let u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(c),signal:t.signal});if(!u.ok){let m=await u.json().catch(()=>({error:"Session initialization failed"}));if(o&&u.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),d)throw new _e("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw u.status===403&&m.error==="durable_recovery_disabled"?new _e("history_disabled","Durable recovery is disabled for this surface"):(o||t.durableResume)&&u.status===401&&m.error==="visitor_required"?new _e("visitor_required","Visitor credential no longer resolves"):d&&u.status===404?new _e("not_found","Conversation not found"):u.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):u.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let p=await u.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId?{targetId:p.targetId}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.durableRecovery?{durableRecovery:p.durableRecovery}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,o=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!o)return this.ordinaryInit(t,!1);let n=await this.readVisitorToken();if(t&&n)try{let r=await this.createClientSession({conversationId:t,durableResume:o});return o&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!Yf(r,"not_found")&&!Yf(r,"visitor_required")&&!Yf(r,"history_disabled"))throw r;return o&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,o){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.doOrdinaryInit(t,o)):this.doOrdinaryInit(t,o)}async doOrdinaryInit(t,o){let n=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),a=await this.claimFirstConversation(r);return this.finishInit(a,t,o)}async reinitWithProof(t){let o=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:o,identityProof:t}),a=this.finishInit(r,n,!1);return this.clientSession=a,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),a}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,o,n){let r=t.conversationId;return r&&o&&(n||r!==o)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:o,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let o=!1;return{session:t,commit:()=>{o||(o=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{o=!0}}}async prepareConversationSession(t,o){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new _e("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let n=o?.proof??null;if(!await this.readVisitorToken()&&!n)throw new _e("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let a=await this.createClientSession({conversationId:t,identityProof:n});return this.prepared(a)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){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 r={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(r)});if(!a.ok){let i=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:t,type:o})}async submitCSATFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:t,comment:o})}async submitNPSFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:t,comment:o})}historyUrl(t,o){let n=new URLSearchParams;for(let[a,i]of Object.entries(o))i===void 0||i===""||n.set(a,String(i));let r=n.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let o=this.config.features?.history?.scope;return o||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,o){let n=this.config.getIdentityProof;if(!n)return o&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;o&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await n()??null}catch{throw o&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new _e("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new _e("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return o&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,o,n){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(o);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new _e("proof_not_admitted",Sx);return r}async readErrorCode(t){let o=await t.json().catch(()=>({}));return typeof o.error=="string"?o.error:typeof o.message=="string"?o.message:""}async recoverFromUnauthorized(t,o,n){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new _e("invalid_identity_proof",wx);if(r.includes("visitor token required"))throw new _e("visitor_token_missing",Ax);if(r.includes("visitor_identity_mismatch")){if(!o)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new _e("visitor_identity_mismatch",Mx);return this.reinitWithProof(o)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new _e("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,o){let n=await this.readErrorCode(t);if(t.status===404)return new _e("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new _e("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&n.includes("identity_proof_not_admitted"))return o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new _e("proof_not_admitted",Sx);if(t.status===401){let r=n.toLowerCase();return r.includes("invalid_identity_proof")?(o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new _e("invalid_identity_proof",wx)):r.includes("visitor token required")?new _e("visitor_token_missing",Ax):r.includes("visitor_identity_mismatch")?new _e("visitor_identity_mismatch",Mx):new _e("unauthorized",n||"History request was not authorized")}return new _e("request_failed",n||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,o,n){let r=t?.toLowerCase()??null;if(o){if(r==="admitted"){n&&this.setHistoryIdentityStatus({state:"verified"});return}throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new _e("identity_contract_violation","Server reported an ignored identity proof on a success response"):new _e("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new _e("identity_contract_violation","Server admitted an identity proof that was never sent");n&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,o){this.assertHistoryUsable();let n=o.trackIdentity!==!1,r=await this.initSession(),a=null;this.resolveHistoryScope(o.scope)==="verified-user"&&(a=await this.resolveIdentityProof(r,n),a&&(r=await this.bindIdentity(r,a,n)));let i=this.historyInternals.visitorStore,d=!1;for(;;){let c=i?.revision()??0,u=await this.readVisitorToken();if(!u&&!o.visitorTokenOptional)throw new _e("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...o.query,sessionId:r.sessionId}),{method:o.method,headers:{"X-Persona-Version":fr,...u?{"X-Visitor-Token":u}:{},...a?{"X-Identity-Proof":a}:{},...o.body!==void 0?{"Content-Type":"application/json"}:{}},...o.body!==void 0?{body:JSON.stringify(o.body)}:{},...o.keepalive?{keepalive:!0}:{}});if(p.status===401&&!d){d=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),a,n);continue}if(!p.ok)throw await this.historyErrorFor(p,n);let m=p.headers.get("X-History-Identity-Status"),h=await p.json().catch(()=>{});if(i&&i.revision()!==c)throw new _e("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,a!==null,n),h}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new _e("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let o=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(o?.data)?o.data:[]).map(xx),nextCursor:typeof o?.nextCursor=="string"?o.nextCursor:null}}async getConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...o?.messageCursor?{messageCursor:o.messageCursor}:{}},...o?.scope?{scope:o.scope}:{}});return{summary:xx(n),messages:Array.isArray(n?.messages)?n.messages:[],nextMessageCursor:typeof n?.nextMessageCursor=="string"?n.nextMessageCursor:null,conversationRevision:typeof n?.conversationRevision=="string"?n.conversationRevision:null}}async finalizeDisplayProjections(t,o){this.assertHistoryUsable();let n=0;for(let c of o){let u=c.displayContent.length;if(u>vx)throw new _e("payload_too_large",`displayContent exceeds the ${vx} character limit`);n+=u}if(n>Qf)throw new _e("payload_too_large",`Display projection batch exceeds the ${Qf} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,a=r?.revision()??0,i=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:o},scope:"browser",keepalive:n<=Qf,trackIdentity:!1}),d=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return d&&this.clientSession?.conversationId===t&&(r?.revision()??0)===a&&this.historyInternals.setStoredConversationRevision?.(d),{conversationRevision:d}}async deleteConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...o?.scope?{scope:o.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async deleteAllConversations(t){let o=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(t,o){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,o):this.isAgentMode()?this.dispatchAgent(t,o):this.dispatchProxy(t,o)}async dispatchClientToken(t,o){let n=Nv();this.currentClientTurnId=n;let r=()=>this.currentClientTurnId===n,a=i=>{r()&&o(i)};o({type:"status",status:"connecting"});try{let i=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},d=this.clientSession??await this.initSession();i();let c=async()=>{i();let E=d,T=E.durableRecovery?.enabled===!0;if(T&&(!E.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let I=await this.createClientSession({...T||this.isHistoryCapable()?{conversationId:E.conversationId,durableResume:T}:{storedSessionId:E.sessionId},signal:t.signal});if(i(),E.conversationId&&I.conversationId!==E.conversationId||T&&I.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");d=this.finishInit(I,E.conversationId??null,!1),this.clientSession=d,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(d)};Date.now()>=d.expiresAt.getTime()-6e4&&await c();let u=await this.buildPayload(t.messages),p=u.metadata?Object.fromEntries(Object.entries(u.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,m=this.isHistoryCapable(),h={sessionId:d.sessionId,messages:t.messages.filter(Jf).map(E=>{let T=m?al(E):void 0;return{id:E.id,role:E.role,content:E.contentParts??E.llmContent??E.rawContent??E.content,...T!==void 0&&{displayContent:T}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...u.inputs&&Object.keys(u.inputs).length>0&&{inputs:u.inputs},...u.context&&{context:u.context},turnId:n,...t.interrupt&&{submitMode:"interrupt"}},y=async()=>{i();let E=d.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.sendWithClientToolsDiff(d.sessionId,u.clientTools,T=>{let I={...h,sessionId:d.sessionId,...T};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",I),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr,...E?{"X-Visitor-Token":E}:{}},body:JSON.stringify(I),signal:t.signal})})},C=await y();if(i(),C.response.status===401){let E=await C.response.clone().json().catch(()=>null);i(),E?.error==="Session not found or expired"&&(await c(),C=await y(),i())}let{response:A,commit:M}=C;if(!A.ok){let E=await A.json().catch(()=>({error:"Chat request failed"}));if(A.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let I=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:I}),I}if(A.status===429){let I=new Error(E.hint||"Message limit reached for this session.");throw a({type:"error",error:I}),I}if(A.status===410&&E.error==="conversation_deleted"){let I=new _e("conversation_deleted","This conversation was deleted");throw a({type:"error",error:I}),I}let T=new Error(E.error||"Failed to send message");throw a({type:"error",error:T}),T}if(!A.body){let E=new Error("No response body received");throw a({type:"error",error:E}),E}M(),a({type:"status",status:"connected"});try{await this.streamResponse(A.body,a,t.assistantMessageId)}finally{a({type:"status",status:"idle"})}}catch(i){let d=i instanceof Error?i:new Error(String(i));throw!(d instanceof _e)&&!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&a({type:"error",error:d}),d}}async dispatchProxy(t,o){o({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o)}finally{o({type:"status",status:"idle"})}}async dispatchAgent(t,o){o({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}async processStream(t,o,n,r){o({type:"status",status:"connected"});try{await this.streamResponse(t,o,n,r)}finally{o({type:"status",status:"idle"})}}async resolveApproval(t,o){let n=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(n,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:o,streamResponse:!0})})}async sendWithClientToolsDiff(t,o,n,r){let a=!!(o&&o.length>0),i=a?Rv(o):void 0,d=this.clientToolsFingerprintSessionId===t,c=a&&d&&this.lastSentClientToolsFingerprint===i,u=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,m;for(let h=0;;h++){if(m=await n({...a&&(p||!c)&&o?{clientTools:o}:{},...u?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),m.status===409&&h===0&&a&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,o,n){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||bx}/resume`,i,d=null;if(r){let p=await this.initSession();i=p.sessionId,p.durableRecovery?.enabled===!0&&(d=await this.readVisitorToken())}let c={"Content-Type":"application/json",...d?{"X-Visitor-Token":d}:{},...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let u={executionId:t,toolOutputs:o,streamResponse:n?.streamResponse??!0,...n?.after?{after:n.after}:{}};if(i&&(u.sessionId=i),r&&i){let p=[...Ha(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(i,p,y=>{let C={...u,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",C),fetch(a,{method:"POST",headers:c,body:JSON.stringify(C),signal:n?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),m}return fetch(a,{method:"POST",headers:c,body:JSON.stringify(u),signal:n?.signal})}latestMentionContext(t){for(let o=t.length-1;o>=0;o--){let n=t[o];if(n.role==="user")return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async buildContextAggregate(t){let o={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let n=this.latestMentionContext(t);return n&&Object.assign(o,n),Object.keys(o).length?o:null}normalizeComposerOptions(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}applyInlineAgentModel(t,o){let n=o?.selectedModelId;return!n||!("model"in t)?t:this.config.composer?.models?.some(a=>a.id===n)?{...t,model:n}:t}async buildAgentPayload(t,o){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=Gf(Tx(t),u=>Jf(u)&&(u.role==="user"||u.role==="assistant"||u.role==="system")&&(!u.variant||u.variant==="assistant")?Ex(u):null),a=this.normalizeComposerOptions(o),i={agent:this.applyInlineAgentModel(this.config.agent??{agentId:n},a),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};a&&(i.composerOptions=a);let d=[...Ha(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];d.length>0&&(i.clientTools=d);let c=await this.buildContextAggregate(t);return c&&(i.context=c),i}async buildPayload(t,o){let n=Gf(Tx(t),u=>Jf(u)?Ex(u):null),r=this.routing(),a={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[u,p]of Object.entries(r.targetPayload))u!=="messages"&&(a[u]=p);let i=[...Ha(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];i.length>0&&(a.clientTools=i);let d=await this.buildContextAggregate(t);d&&(a.context=d);let c=this.normalizeComposerOptions(o);if(c&&(a.composerOptions=c),this.requestMiddleware)try{let u=await this.requestMiddleware({payload:{...a},config:this.config});if(u&&typeof u=="object"){let p=u;return a.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=a.clientTools),p}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",u)}return a}async handleCustomSSEEvent(t,o,n,r,a,i){if(!this.parseSSEEvent)return!1;try{let d=await this.parseSSEEvent(t);if(d===null)return!1;let c=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return n.current=m,r(m),m},u=p=>n.current?n.current:c(p);if(d.text!==void 0){d.partId!==void 0&&i.current!==null&&d.partId!==i.current&&(n.current&&(n.current.streaming=!1,r(n.current)),c(d.partId)),d.partId!==void 0&&(i.current=d.partId);let p=u(d.partId);d.partId!==void 0&&!p.partId&&(p.partId=d.partId),p.content+=d.text,r(p)}return d.done&&(n.current&&(n.current.streaming=!1,r(n.current)),i.current=null,o({type:"status",status:"idle"})),d.error&&(i.current=null,o({type:"error",error:new Error(d.error)})),!0}catch(d){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",d),!1}}async streamResponse(t,o,n,r){let a=t.getReader(),i=new TextDecoder,d="",c=Date.now(),u=0,p=()=>c+u++,m=z=>{let k=z.reasoning?{...z.reasoning,chunks:[...z.reasoning.chunks]}:void 0,F=z.toolCall?{...z.toolCall,chunks:z.toolCall.chunks?[...z.toolCall.chunks]:void 0}:void 0,K=z.tools?z.tools.map(Y=>({...Y,chunks:Y.chunks?[...Y.chunks]:void 0})):void 0;return{...z,reasoning:k,toolCall:F,tools:K}},h=z=>{if(z.role!=="assistant"||z.variant)return!0;let k=Array.isArray(z.contentParts)&&z.contentParts.length>0,F=typeof z.rawContent=="string"&&z.rawContent.trim()!=="";return typeof z.content=="string"&&z.content.trim()!==""||k||F||!!z.stopReason},y=z=>{h(z)&&o({type:"message",message:m(z)})},C=null,A=null,M={current:null},E={current:null},T=null,I="",b=new Map,S=new Map,x=new Map,L=new Map,N=new Map,X=n,V=!1,P=()=>{if(C)return C;let z,k="",F=T;return!V&&X?(z=X,V=!0,k=r??""):X&&F?z=`${X}_${F}`:z=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,C={id:z,role:"assistant",content:k,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},y(C),C},O=z=>{let k=L.get(z);if(k)return k;let F={id:`reason-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:z,status:"streaming",chunks:[]}};return L.set(z,F),y(F),F},D=new Set,W=new Map,ee=new Set,G=new Map,ue=z=>{if(!z)return!1;let k=z.replace(/_+/g,"_").replace(/^_|_$/g,"");return k==="emit_artifact_markdown"||k==="emit_artifact_component"},ae=z=>{let k=N.get(z);if(k)return k;let F={id:`tool-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:z,status:"pending"}};return N.set(z,F),y(F),F},ye=z=>{if(typeof z=="number"&&Number.isFinite(z))return z;if(typeof z=="string"){let k=Number(z);if(!Number.isNaN(k)&&Number.isFinite(k))return k;let F=Date.parse(z);if(!Number.isNaN(F))return F}return Date.now()},Re=z=>{if(typeof z=="string")return z;if(z==null)return"";try{return JSON.stringify(z)}catch{return String(z)}},be=new Map,pe=new Map,yt=(z,k)=>{let F=Re(k),K=pe.get(z.id),Y=_E(K,F);z.rawContent=Y;let te=be.get(z.id),ge=Ke=>{let Ve=z.content??"";Ke.trim()!==""&&(Ve.trim().length===0||Ke.startsWith(Ve)||Ke.trimStart().startsWith(Ve.trim()))&&(z.content=Ke)},Me=()=>{if(te){let Ke=te.close?.();Ke instanceof Promise&&Ke.catch(()=>{})}be.delete(z.id),pe.delete(z.id),z.streaming=!1,y(z)};if(!te){ge(F),Me();return}let Ee=sl(Y);if(Ee!==null&&Ee.trim()!==""){ge(Ee),Me();return}let We=Ke=>{let Ve=typeof Ke=="string"?Ke:Ke?.text??null;if(Ve!==null&&Ve.trim()!=="")return Ve;let gt=te.getExtractedText();return gt!==null&>.trim()!==""?gt:F},st;try{st=te.processChunk(Y)}catch{ge(F),Me();return}if(st instanceof Promise){st.then(Ke=>{ge(We(Ke)),Me()}).catch(()=>{ge(F),Me()});return}ge(We(st)),Me()},Pe=null,q=(z,k,F,K)=>{z.rawContent=k,be.has(z.id)||be.set(z.id,this.createStreamParser());let Y=be.get(z.id),te=k.trim().startsWith("{")||k.trim().startsWith("[");if(te&&pe.set(z.id,k),Y.__isPlainTextParser===!0){z.content=K!==void 0?k:z.content+F,pe.delete(z.id),be.delete(z.id),z.rawContent=void 0,y(z);return}let Me=Y.processChunk(k);if(Me instanceof Promise)Me.then(Ee=>{let We=typeof Ee=="string"?Ee:Ee?.text??null;We!==null&&We.trim()!==""?(z.content=We,y(z)):!te&&!k.trim().startsWith("<")&&(z.content=K!==void 0?k:z.content+F,pe.delete(z.id),be.delete(z.id),z.rawContent=void 0,y(z))}).catch(()=>{z.content=K!==void 0?k:z.content+F,pe.delete(z.id),be.delete(z.id),z.rawContent=void 0,y(z)});else{let Ee=typeof Me=="string"?Me:Me?.text??null;Ee!==null&&Ee.trim()!==""?(z.content=Ee,y(z)):!te&&!k.trim().startsWith("<")&&(z.content=K!==void 0?k:z.content+F,pe.delete(z.id),be.delete(z.id),z.rawContent=void 0,y(z))}},Ue=(z,k)=>{let F=k??z.content;if(F==null||F===""){z.streaming=!1,y(z);return}let Y=pe.get(z.id)??Re(F);z.rawContent=Y;let te=be.get(z.id),ge=null,Me=!1;if(te&&(ge=te.getExtractedText(),ge===null&&(ge=sl(Y)),ge===null)){let Ee=te.processChunk(Y);Ee instanceof Promise?(Me=!0,Ee.then(We=>{let st=typeof We=="string"?We:We?.text??null;st!==null&&(z.content=st,z.streaming=!1,be.delete(z.id),pe.delete(z.id),y(z))}).catch(()=>{})):ge=typeof Ee=="string"?Ee:Ee?.text??null}if(!Me){ge!==null&&ge.trim()!==""?z.content=ge:pe.has(z.id)||(z.content=Re(F));let Ee=be.get(z.id);if(Ee){let We=Ee.close?.();We instanceof Promise&&We.catch(()=>{}),be.delete(z.id)}pe.delete(z.id),z.streaming=!1,y(z)}},Je=(z,k,F)=>{let K=S.get(z);if(K)return K;let Y={id:`nested-${k}-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...F?{variant:F}:{},...F==="reasoning"?{reasoning:{id:z,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:k}};return S.set(z,Y),y(Y),Y},so=[],Le,qe=new Map,ve=0,po="agent",dn=!1,Vn=null,wt=null,$n=this.config.iterationDisplay??"separate";for(Le=()=>{for(let z=0;z<so.length;z++){let k=so[z];if(!dn&&po!=="flow"&&typeof k.stepType=="string"&&(po="flow"),k.type==="reasoning_start"){let F=typeof k.id=="string"?k.id:null,K=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if(F&&K){b.set(F,K),Je(F,K,"reasoning");continue}let Y=k.id,te=O(Y);te.reasoning=te.reasoning??{id:Y,status:"streaming",chunks:[]},te.reasoning.startedAt=te.reasoning.startedAt??Date.now(),te.reasoning.completedAt=void 0,te.reasoning.durationMs=void 0,(k.scope==="loop"||k.scope==="turn")&&(te.reasoning.scope=k.scope),te.streaming=!0,te.reasoning.status="streaming",y(te)}else if(k.type==="reasoning_delta"){let F=typeof k.id=="string"?k.id:null;if(F&&b.has(F)&&S.has(F)){let te=S.get(F),ge=k.delta;ge&&te.reasoning&&(te.reasoning.chunks.push(String(ge)),y(te));continue}let K=k.id,Y=O(K);Y.reasoning=Y.reasoning??{id:K,status:"streaming",chunks:[]},Y.reasoning.startedAt=Y.reasoning.startedAt??Date.now(),k.delta&&Y.reasoning.chunks.push(k.delta),Y.reasoning.status="streaming",Y.streaming=!0,y(Y)}else if(k.type==="reasoning_complete"){let F=typeof k.id=="string"?k.id:null;if(F&&b.has(F)&&S.has(F)){let ge=S.get(F);if(ge.reasoning){let Me=typeof k.text=="string"?k.text:"";Me&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(Me),ge.reasoning.status="complete",ge.streaming=!1,y(ge)}b.delete(F),S.delete(F);continue}let K=k.id,Y=typeof k.text=="string"?k.text:"";!L.get(K)&&(Y||k.scope==="loop")&&O(K);let te=L.get(K);if(te?.reasoning){(k.scope==="loop"||k.scope==="turn")&&(te.reasoning.scope=k.scope),Y&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push(Y),te.reasoning.status="complete",te.reasoning.completedAt=Date.now();let ge=te.reasoning.startedAt??Date.now();te.reasoning.durationMs=Math.max(0,(te.reasoning.completedAt??Date.now())-ge),te.streaming=!1,y(te)}}else if(k.type==="tool_start"){C&&(C.streaming=!1,y(C),C=null),typeof k.iteration=="number"&&(ve=k.iteration);let F=k.toolCallId,K=k.toolName;if(ue(K)){D.add(F);continue}let Y=ae(F),te=Y.toolCall??{id:F,status:"pending"};te.name=K??te.name,te.status="running",te.success=void 0,te.error=void 0,te.duration=void 0,k.parameters!==void 0&&(te.args=k.parameters),te.startedAt=te.startedAt??ye(k.startedAt),te.completedAt=void 0,te.durationMs=void 0,Y.toolCall=te,Y.streaming=!0,k.executionId&&(Y.agentMetadata={executionId:k.executionId,iteration:k.iteration}),y(Y)}else if(k.type==="tool_output_delta"){let F=k.toolCallId;if(D.has(F))continue;let K=ae(F),Y=K.toolCall??{id:F,status:"running"};Y.startedAt=Y.startedAt??Date.now();let te=k.delta;te&&(Y.chunks=Y.chunks??[],Y.chunks.push(String(te))),Y.status="running",K.toolCall=Y,K.streaming=!0,k.executionId&&(K.agentMetadata=K.agentMetadata??{executionId:k.executionId,iteration:ve}),y(K)}else if(k.type==="tool_complete"){let F=k.toolCallId;if(D.has(F)){D.delete(F);continue}let K=ae(F),Y=K.toolCall??{id:F,status:"running"};Y.status="complete",k.result!==void 0&&(Y.result=k.result),Y.name=k.toolName??Y.name,Y.success=k.success,Y.error=k.error,Y.completedAt=Date.now();let te=k.executionTime;if(typeof te=="number")Y.durationMs=te,Y.duration=te;else{let ge=Y.startedAt??Date.now();Y.durationMs=Math.max(0,(Y.completedAt??Date.now())-ge)}K.toolCall=Y,K.streaming=!1,k.executionId&&(K.agentMetadata=K.agentMetadata??{executionId:k.executionId,iteration:k.iteration??ve}),y(K)}else if(k.type==="await"&&k.toolName){let F=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,K=F??k.toolId??`local-${p()}`,Y=ae(K),te=k.toolName,ge=k.origin==="webmcp"&&!_r(te)?`webmcp:${te}`:te,Me=_r(ge),Ee=Y.toolCall??{id:K,status:"pending"};Ee.name=ge,Ee.args=k.parameters,Ee.status=Me?"running":"complete",Ee.chunks=Ee.chunks??[],Ee.startedAt=Ee.startedAt??ye(k.awaitedAt),Me?(Ee.completedAt=void 0,Ee.duration=void 0,Ee.durationMs=void 0):Ee.completedAt=Ee.completedAt??Ee.startedAt,Y.toolCall=Ee,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:k.executionId??Y.agentMetadata?.executionId,awaitingLocalTool:!0,...F?{webMcpToolCallId:F}:{}},y(Y)}else if(k.type==="text_start"){let F=typeof k.id=="string"?k.id:null,K=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if(F&&K){b.set(F,K);continue}let Y=C;Y&&(po==="flow"?(Ue(Y),Pe=Y):(Y.streaming=!1,y(Y)),C=null),T=typeof k.id=="string"?k.id:T,I=""}else if(k.type==="text_delta"){let F=typeof k.id=="string"?k.id:null,K=F?b.get(F):void 0;if(F&&K){let ge=typeof k.delta=="string"?k.delta:"",Me=(x.get(F)??"")+ge;if(x.set(F,Me),Me.trim()==="")continue;let Ee=Je(F,K);Ee.agentMetadata={...Ee.agentMetadata,executionId:k.executionId,parentToolId:K},q(Ee,Me,ge,void 0);continue}if(T=typeof k.id=="string"?k.id:T,po==="flow"){let ge=typeof k.delta=="string"?k.delta:"";if(I+=ge,I.trim()==="")continue;let Me=P();Me.agentMetadata={executionId:k.executionId,iteration:ve},q(Me,I,ge,void 0),A=Me;continue}let Y=typeof k.delta=="string"?k.delta:"";I+=Y;let te=P();te.agentMetadata={executionId:k.executionId,iteration:ve,turnId:Vn??void 0,agentName:wt?.agentName},q(te,I,Y,void 0),A=te}else if(k.type==="text_complete"){let F=typeof k.id=="string"?k.id:null;if(F&&b.has(F)){let Y=S.get(F);Y&&Ue(Y),b.delete(F),x.delete(F),S.delete(F);continue}let K=C;K&&(po==="flow"?(Ue(K),Pe=K):((K.content??"")===""&&typeof k.text=="string"&&(K.content=k.text),K.streaming=!1,y(K)),C=null),T=null,I=""}else if(k.type==="step_complete"){if(k.stepType==="tool")continue;if(k.success===!1){let F=k.error||"Step failed";o({type:"error",error:new Error(F)});let K=C;K&&K.streaming&&(K.streaming=!1,y(K)),o({type:"status",status:"idle"});continue}{let F=Pe;Pe=null;let K=k.stopReason,te=(k.result&&typeof k.result=="object"?k.result:null)?.response;if(F)K&&(F.stopReason=K),te!=null?yt(F,te):F.streaming!==!1&&(be.delete(F.id),pe.delete(F.id),F.streaming=!1,y(F));else{let ge=te!=null&&te!=="";if(ge||K){let Me=P();K&&(Me.stopReason=K),ge?Ue(Me,te):(Me.streaming=!1,y(Me))}}continue}}else if(k.type==="execution_start")po=k.kind==="flow"?"flow":"agent",dn=!0,po==="agent"&&(wt={executionId:k.executionId,agentId:k.agentId??"virtual",agentName:k.agentName??""});else if(k.type==="turn_start"){let F=typeof k.iteration=="number"?k.iteration:ve;if(F!==ve){if($n==="separate"&&F>1){let K=C;K&&(K.streaming=!1,y(K),C=null)}ve=F}Vn=typeof k.id=="string"?k.id:null,A=null}else if(k.type==="tool_input_delta"){let F=k.toolCallId;if(F){let K=N.get(F);K?.toolCall&&(K.toolCall.chunks=K.toolCall.chunks??[],K.toolCall.chunks.push(k.delta??""),y(K))}}else if(k.type==="tool_input_complete"){if(D.has(k.toolCallId))continue;let F=ae(k.toolCallId),K=F.toolCall;K.args=k.parameters,K.name=k.toolName??K.name,y(F)}else if(k.type==="turn_complete"){let F=k.stopReason,K=C??A;if(F&&K!==null){let Y=k.id;(!Y||K.agentMetadata?.turnId===Y)&&(K.stopReason=F,y(K))}Vn===k.id&&(Vn=null)}else if(k.type==="media_start"){let F=String(k.id);qe.set(F,{mediaType:typeof k.mediaType=="string"?k.mediaType:void 0,toolCallId:k.toolCallId,parts:[]})}else if(k.type==="media_delta"){let F=qe.get(String(k.id));F&&typeof k.delta=="string"&&F.parts.push(k.delta)}else if(k.type==="media_complete"){let F=String(k.id),K=qe.get(F);qe.delete(F);let Y=(typeof k.mediaType=="string"?k.mediaType:void 0)??K?.mediaType??"application/octet-stream",te=typeof k.data=="string"?k.data:void 0,ge=typeof k.url=="string"?k.url:K&&K.parts.length>0?K.parts.join(""):void 0,Me=null;if(te)Me={type:"media",data:te,mediaType:Y};else if(ge){let Ke=Y.toLowerCase();Me={type:Ke==="image"||Ke.startsWith("image/")?"image-url":"file-url",url:ge,mediaType:Y}}let Ee=k.toolCallId??K?.toolCallId,We=Me?[Me]:[],st=[];for(let Ke of We){if(!Ke||typeof Ke!="object")continue;let Ve=Ke,gt=typeof Ve.type=="string"?Ve.type:void 0,zt=typeof Ve.mediaType=="string"?Ve.mediaType.toLowerCase():"",It=null,ao="";if(gt==="media"){let wo=typeof Ve.data=="string"?Ve.data:void 0;if(!wo)continue;ao=zt.length>0?zt:"application/octet-stream",It=`data:${ao};base64,${wo}`}else if(gt==="image-url"){let wo=typeof Ve.url=="string"?Ve.url:void 0;if(!wo)continue;ao=zt,It=wo}else if(gt==="file-url"){let wo=typeof Ve.url=="string"?Ve.url:void 0;if(!wo)continue;ao=zt,It=wo}else continue;if(It)if(gt==="image-url"||ao.startsWith("image/"))st.push({type:"image",image:It,...ao.includes("/")?{mimeType:ao}:{}});else if(ao.startsWith("audio/"))st.push({type:"audio",audio:It,mimeType:ao});else if(ao.startsWith("video/"))st.push({type:"video",video:It,mimeType:ao});else{let wo=ao||"application/octet-stream";st.push({type:"file",data:It,mimeType:wo,filename:OE(wo)})}}if(st.length>0){let Ke=p(),Ve=Ee,zt={id:`agent-media-${typeof Ve=="string"&&Ve.length>0?`${Ve}-${Ke}`:String(Ke)}`,role:"assistant",content:"",contentParts:st,createdAt:new Date().toISOString(),streaming:!1,sequence:Ke,agentMetadata:{executionId:k.executionId,iteration:ve}};y(zt);let It=C;It&&(It.streaming=!1,y(It)),C=null,M.current=null}}else if(k.type==="execution_complete"){let F=C;F&&(k.kind==="flow"&&F.streaming!==!1?Ue(F):(F.streaming=!1,y(F)),C=null),T=null,I="",Pe=null,o({type:"status",status:"idle",terminal:!0})}else if(k.type==="execution_error"){let F=typeof k.error=="string"?k.error:k.error?.message??"Execution error";o({type:"error",error:new Error(F)})}else if(k.type!=="ping"){if(k.type==="approval_start"){let F=k.approvalId??`approval-${p()}`,K={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:F,status:"pending",agentId:wt?.agentId??"virtual",executionId:k.executionId??wt?.executionId??"",toolName:k.toolName??"",toolType:k.toolType,description:k.description??`Execute ${k.toolName??"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};y(K)}else if(k.type==="approval_complete"){let F=k.approvalId;if(F){let Y={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:F,status:k.decision??"approved",agentId:wt?.agentId??"virtual",executionId:k.executionId??wt?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};y(Y)}}else if(k.type==="artifact_start"||k.type==="artifact_delta"||k.type==="artifact_update"||k.type==="artifact_complete"){if(k.type==="artifact_start"){let F=k.artifactType,K=String(k.id),Y=typeof k.title=="string"?k.title:void 0,te=k.file,ge;if(te&&typeof te=="object"&&!Array.isArray(te)&&typeof te.path=="string"&&typeof te.mimeType=="string"&&(ge={path:te.path,mimeType:te.mimeType,...typeof te.language=="string"?{language:te.language}:{}}),o({type:"artifact_start",id:K,artifactType:F,title:Y,component:typeof k.component=="string"?k.component:void 0,...ge?{file:ge}:{}}),G.set(K,{markdown:"",title:Y,file:ge}),!ee.has(K)){ee.add(K);let Me=Dn(this.config.features?.artifacts,{artifactType:F,...ge?{file:ge}:{}}),Ee=typeof k.component=="string"?k.component:void 0,We={id:`artifact-ref-${K}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:Zi(Me,{artifactId:K,title:Y,artifactType:F,status:"streaming",...ge?{file:ge}:{},...Ee?{component:Ee}:{}})};W.set(K,We),y(We)}}else if(k.type==="artifact_delta"){let F=String(k.id),K=typeof k.delta=="string"?k.delta:String(k.delta??"");o({type:"artifact_delta",id:F,artDelta:K});let Y=G.get(F);Y&&(Y.markdown+=K)}else if(k.type==="artifact_update"){let F=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};o({type:"artifact_update",id:String(k.id),props:F,component:typeof k.component=="string"?k.component:void 0});let K=G.get(String(k.id));K&&(K.props={...K.props??{},...F})}else if(k.type==="artifact_complete"){let F=String(k.id);o({type:"artifact_complete",id:F});let K=W.get(F);if(K){K.streaming=!1;try{let Y=JSON.parse(K.rawContent??"{}");if(Y.props){Y.props.status="complete";let te=G.get(F);te?.markdown&&(Y.props.markdown=te.markdown),te?.file&&(Y.props.file=te.file),Y.component==="PersonaArtifactInline"&&te?.props&&Object.keys(te.props).length>0&&(Y.props.componentProps=te.props)}K.rawContent=JSON.stringify(Y)}catch{}G.delete(F),y(K),W.delete(F)}}}else if(k.type==="error"&&k.recoverable===!1&&k.error!=null&&k.error!==""){let F=typeof k.error=="string"?k.error:k.error?.message!=null?String(k.error.message):"Execution error";o({type:"error",error:new Error(F)});let K=C;K&&K.streaming&&(K.streaming=!1,y(K)),o({type:"status",status:"idle"})}}}so.length=0};;){let{done:z,value:k}=await a.read();if(z)break;d+=i.decode(k,{stream:!0});let F=d.split(`
|
|
8
8
|
|
|
9
9
|
`);d=F.pop()??"";for(let K of F){let Y=K.split(`
|
|
10
|
-
`),te="message",ge="",Me=null;for(let Ve of Y)Ve.startsWith("event:")?te=Ve.replace("event:","").trim():Ve.startsWith("data:")?ge+=Ve.replace("data:","").trim():Ve.startsWith("id:")&&(Me=Ve.slice(3).trim());let Ee=()=>{Me!==null&&Me!==""&&o({type:"cursor",id:Me})};if(!ge){Ee();continue}let We;try{We=JSON.parse(ge)}catch(Ve){o({type:"error",error:Ve instanceof Error?Ve:new Error("Failed to parse chat stream payload")});continue}let st=We!==null&&typeof We=="object"&&!Array.isArray(We)?We:null,Ke=te!=="message"?te:typeof st?.type=="string"?st.type:"message";if(this.onSSEEvent?.(Ke,We),this.parseSSEEvent){
|
|
11
|
-
`)){let n=/^ {0,3}(`+)/.exec(o);n&&n[1].length>t&&(t=n[1].length)}return t}function
|
|
10
|
+
`),te="message",ge="",Me=null;for(let Ve of Y)Ve.startsWith("event:")?te=Ve.replace("event:","").trim():Ve.startsWith("data:")?ge+=Ve.replace("data:","").trim():Ve.startsWith("id:")&&(Me=Ve.slice(3).trim());let Ee=()=>{Me!==null&&Me!==""&&o({type:"cursor",id:Me})};if(!ge){Ee();continue}let We;try{We=JSON.parse(ge)}catch(Ve){o({type:"error",error:Ve instanceof Error?Ve:new Error("Failed to parse chat stream payload")});continue}let st=We!==null&&typeof We=="object"&&!Array.isArray(We)?We:null,Ke=te!=="message"?te:typeof st?.type=="string"?st.type:"message";if(this.onSSEEvent?.(Ke,We),this.parseSSEEvent){M.current=C;let Ve=await this.handleCustomSSEEvent(We,o,M,y,p,E);if(M.current&&M.current!==C&&(C=M.current),Ve){Ee();continue}}st&&(so.push({...st,type:Ke}),Le()),Ee()}}Le()}};function NE(e){let t=0;for(let o of e.split(`
|
|
11
|
+
`)){let n=/^ {0,3}(`+)/.exec(o);n&&n[1].length>t&&(t=n[1].length)}return t}function kx(e,t){let o="`".repeat(Math.max(3,NE(t)+1));return`${o}${e}
|
|
12
12
|
${t}
|
|
13
|
-
${o}`}var
|
|
13
|
+
${o}`}var FE=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function UE(e){let t=e?.text?.trim()??"";return t?kx(FE(e),t):""}function Lx(e){let t=UE(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[an(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
14
14
|
|
|
15
|
-
`)}:{}}function Lc(e,t=140){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function
|
|
15
|
+
`)}:{}}function Lc(e,t=140){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function Ix(e,t){let o=e.findIndex(r=>r.id===t);if(o===-1||e[o].role!=="user")return null;let n=o+1;for(;n<e.length&&e[n].role!=="user";)n+=1;return{start:o,end:n}}function Zf(e,t){let o=e.findIndex(n=>n.id===t);if(o<=0)return null;for(let n=o-1;n>=0;n-=1)if(e[n].role==="user")return e[n].id;return null}function Rx(e){for(let t=e.length-1;t>=0;t-=1){let o=e[t];if(o.role==="user"||o.streaming)return null;if(!(o.role!=="assistant"||o.variant))return Zf(e,o.id)?o.id:null}return null}function em(e){return e.role!=="user"||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content=="string"&&e.content.length>0}var ln=class extends Error{constructor(t,o,n){super(o),this.name="HistoryProviderError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function Hx(e){return e instanceof ln}function ll(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(r=>r.name===o);if(n)return n}return e.find(o=>o.lang.startsWith("en"))??e[0]}var Hs=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,o){if(!e.isSupported()){o.onError?.(new Error("Web Speech API is unavailable"));return}let n=window.speechSynthesis;n.cancel();let r=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let i=a.find(d=>d.name===t.voice);i&&(r.voice=i)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):ll(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>o.onEnd?.(),r.onerror=i=>{let d=i.error;d==="canceled"||d==="interrupted"?o.onEnd?.():o.onError?.(new Error(d||"Speech synthesis failed"))},setTimeout(()=>{n.speak(r),o.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Oa=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,o){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,o)}async play(t,o){let n=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(n!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(o,{onStart:()=>{n===this.generation&&this.set(t,"playing")},onEnd:()=>{n===this.generation&&this.set(null,"idle")},onError:()=>{n===this.generation&&this.set(null,"idle")}})}catch{n===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,o){this.activeId=o==="idle"?null:t,this.state=o;for(let n of this.listeners)n(this.activeId,this.state)}};var dl=class{constructor(){this.cancelled=!1}start(t){this.turnId=t,this.cancelled=!1}cancel(){this.cancelled=!0}accepts(t){return!this.cancelled&&(!t||!this.turnId||t===this.turnId)}};var{setLoader:qE,load:VE}=mt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),Wx=qE,tm=VE;function om(e){if(!e)return"";let t=$E(e);return Bx(t!==null?t:e)}function $E(e){let t=e.trim(),o=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(o&&(t=o[1].trim()),!t.startsWith("{"))return null;try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{}return null}function Bx(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
16
16
|
`),t=t.replace(/\n{2,}/g,`
|
|
17
|
-
`),t.trim()}var
|
|
17
|
+
`),t.trim()}var nm=null,Ox=e=>{nm=e},rm=()=>nm?nm():import("./runtype-tts-entry");var{setLoader:jE,load:zE}=mt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Dx=jE,_x=zE;var KE=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function GE(e,t){return KE.some(o=>e[o]!==t[o])}var Nn=class extends Error{constructor(t,o){super(o),this.name="SessionHistoryError",this.code=t}};function sm(e,t){let o=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(o);let n="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return o.message?`${n}
|
|
18
18
|
|
|
19
|
-
_Details: ${o.message}_`:n}var sm=e=>({isError:!0,content:[{type:"text",text:e}]}),VE=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ox=e=>_r(e)||e===_n,Da=class e{constructor(t={},o,n={}){this.config=t;this.callbacks=o;this.historyInternals=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new dl;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Oa(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let o=t.message.toolCall,n=!!o?.name&&(_r(o.name)||o.name===_n&&jr(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&n&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(n),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Rs(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&em().catch(()=>{})}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let o=t.host??this.config.apiUrl,n=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!o||!n||!this.config.clientToken||nm().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return fv(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let o=Hs.isSupported()?new Hs({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let n=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,i=t.browserFallback!==!1;if(n&&r&&a)return nm().then(({RuntypeSpeechEngine:d,FallbackSpeechEngine:c})=>{let u=new d({host:n,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&o?new c(u,o,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});if(i&&o)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),o}return o}setupVoice(t){try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.cleanupVoice();let n=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=em().then(async a=>{await n,r===this.voiceSetupGeneration&&this.wireVoiceProvider(a.createVoiceProvider(o))}).catch(a=>{console.error("Failed to setup voice:",a)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(o){console.error("Failed to setup voice:",o)}}wireVoiceProvider(t){try{this.voiceProvider=t;let o=this.voiceSetupGeneration,n=()=>this.voiceProvider===t&&o===this.voiceSetupGeneration,a=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{n()&&i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c,u)=>{if(n())if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.voiceTurns.start(u?.turnId),this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(u?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(i=>{n()&&(this.voiceLevel=Number.isFinite(i)?Math.max(0,Math.min(1,i)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{n()&&this.config.voiceRecognition?.onMetrics?.(i)}),this.voiceProvider.onError(i=>{n()&&(console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(i=>{n()&&(this.voiceStatus=i,this.voiceActive=i==="listening",(i==="listening"||i==="idle"||i==="disconnected")&&this.settlePendingVoiceTurn(i!=="listening"),this.callbacks.onVoiceStatusChanged?.(i))}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){let t=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let o=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(o)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new dl,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(t){try{await t.disconnect()}catch(o){console.error("Failed to disconnect voice:",o)}}settlePendingVoiceTurn(t){let o=t?this.pendingVoiceUserMessageId:null,n=this.pendingVoiceAssistantMessageId;!o&&!n||(n&&this.voiceTurns.cancel(),t&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(r=>r.id!==o&&r.id!==n?[r]:r.id===n&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let o={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,o){return this.client.submitMessageFeedback(t,o)}async submitCSATFeedback(t,o){return this.client.submitCSATFeedback(t,o)}async submitNPSFeedback(t,o){return this.client.submitNPSFeedback(t,o)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let o=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:n=>{this.handleHistoryContinuityChanged(n),o?.(n)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new Nn("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let o=this.requireHistoryProvider(),n=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",a=n??(o.capabilities.scopes.includes(r)?r:o.capabilities.scopes[0]??r);if(!o.capabilities.scopes.includes(a))throw new ln("unsupported_scope","This history scope is not supported.");return{scope:a}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(t,o){this.callbacks.onHistoryNotice?.({code:t,message:o})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let o=this.projectionFinalizationPromise;o&&await o.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Nn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,o){let n=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(o?.scope);await this.awaitHistorySettled();let a=++this.historyOpenEpoch,i=await n.getPage(t,{context:r});if(a!==this.historyOpenEpoch)throw new Nn("superseded","A later selection won");let d=await n.prepareOpen(t,{context:r});if(a!==this.historyOpenEpoch)throw d.discard(),new Nn("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(d)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=d.conversationId||t,this.activeConversationRevision=d.conversationRevision||i.conversationRevision||null,this.historyNextMessageCursor=i.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.persistConversationMetadata(),this.hydrateMessages(i.messages),this.emitHistoryState(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,o,n){let r=this.requireHistoryProvider(),a=this.historyContext(n?.scope),i=o??this.historyNextMessageCursor;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let d=`${t} ${i}`,c=this.olderPageRequests.get(d);if(c)return c;let u=this.fetchOlderPage(r,t,i,a).finally(()=>{this.olderPageRequests.delete(d)});return this.olderPageRequests.set(d,u),u}async fetchOlderPage(t,o,n,r){let a=this.messages[0]?.createdAt,i=await t.getPage(o,{cursor:n,...a?{beforeCreatedAt:a}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==o)return{messages:[],nextMessageCursor:i.nextCursor};let d=il(this.messages,i.messages);this.messages=this.sortMessages(d.map(c=>this.ensureSequence(c))),this.historyNextMessageCursor=i.nextCursor;for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,a=await o.prepareStartNew({context:n});if(r!==this.historyOpenEpoch)throw a.discard(),new Nn("superseded","A later action won");await this.installFreshConversation(a)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,o){let n=this.requireHistoryProvider(),r=this.historyContext(o?.scope);await this.awaitHistorySettled(),await n.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,o,n){let r=this.requireHistoryProvider();if(!r.update)throw new Nn("history_unavailable","This history provider cannot update conversations");let a=this.historyContext(n?.scope);return await this.awaitHistorySettled(),r.update(t,o,{context:a})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await o.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:n});return await this.recoverFromDestroyedConversation(n),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new Nn("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(t)}async prepareReplacementConversation(t){let o=this.historyProvider;if(!o){this.historySendBlocked=!1,this.emitHistoryState();return}try{let n=await o.prepareStartNew({context:t});await this.installFreshConversation(n)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new Nn("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let o=this.client.getClientSession();o&&o.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(o)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(o=>this.handleExternalCredentialChange(o))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let o=this.messages.length>0;o||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),o&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let o=this.historyProvider,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!o||!n)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let a=this.runBootReconciliation(o,n,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===a&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=a,a}async runBootReconciliation(t,o,n){this.activeConversationId=o;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,a=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&a&&r===a){this.activeConversationRevision=r;return}let i=await t.getPage(o,{context:n}),d=new Set(i.messages.map(m=>m.id)),c=this.messages.some(m=>d.has(m.id)),u=i.messages[0]?.createdAt,p;if(!c)p=i.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,h=this.messages.filter(y=>d.has(y.id)||y.id===m?!0:u!==void 0&&y.createdAt<u);p=il(h,i.messages).map(y=>this.ensureSequence(y))}this.historyNextMessageCursor=i.nextCursor,this.activeConversationRevision=i.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of i.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let o of t){let n=al(o);n!==void 0&&this.acknowledgedProjections.set(o.id,n)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let o=[];for(let n of this.messages){if(n.role!=="assistant"||n.streaming)continue;let r=al(n);r!==void 0&&this.acknowledgedProjections.get(n.id)!==r&&o.push({id:n.id,displayContent:r})}o.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:o.map(n=>n.id)}),this.enqueueProjectionFinalization(t,o))}enqueueProjectionFinalization(t,o){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,o,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,o,n){if(this.activeConversationId!==t)return;let r=o.filter(a=>this.acknowledgedProjections.get(a.id)!==a.displayContent);if(r.length===0){this.clearFinalizedMarker(t,o);return}try{let{conversationRevision:a}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.acknowledgedProjections.set(i.id,i.displayContent);this.activeConversationId===t&&a&&(this.activeConversationRevision=a),this.clearFinalizedMarker(t,o)}catch(a){if(!n&&this.isTransientProjectionError(a)){await this.finalizeProjections(t,r,!0);return}if(a instanceof _e&&(a.code==="not_found"||a.code==="conversation_deleted")){this.clearFinalizedMarker(t,o);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof _e?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,o){let n=this.readPendingProjections();if(!n||n.conversationId!==t)return;let r=new Set(o.map(i=>i.id)),a=n.messageIds.filter(i=>!r.has(i));this.setPendingProjections(a.length?{conversationId:t,messageIds:a}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let o=[];for(let n of t.messageIds){let r=this.messages.find(a=>a.id===n);!r||typeof r.content!="string"||o.push({id:n,displayContent:r.content})}if(o.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,o),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof _e&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,o,n,r,a){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt},this.handleEvent);return}catch(i){if(!e.isConversationDeleted(i))throw i;let d=await this.recoverFromDeletedConversation(r);if(!d)throw i;this.recordDispatchedProjections([d]),await this.client.dispatch({messages:[d],signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let o=this.messages.find(r=>r.id===t);if(!o)return null;let n={...o};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let a=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(a)}else{this.client.clearClientSession();let a=await this.client.initSession();this.bindActivatedSession(a)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(n),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===n.id)??n}updateConfig(t){let o=this.config.features?.artifacts?.display,n={...this.config,...t},r=pv(this.config,n),a=qE(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&Wo(n.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(o)!==JSON.stringify(n.features?.artifacts?.display);if(!a){this.client.updateConfig(n),i&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let d=this.client.getSSEEventCallback();this.client=new Rs(this.config,this.historyInternals),i&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),d&&this.client.setSSEEventCallback(d)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:o,content:n,llmContent:r,contentParts:a,id:i,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:p,rawContent:m}=t,y={id:i??(o==="user"?ka():o==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:o,content:n,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let o=[];for(let n of t){let{role:r,content:a,llmContent:i,contentParts:d,id:c,createdAt:u,sequence:p,streaming:m=!1,voiceProcessing:h,rawContent:y}=n,M={id:c??(r==="user"?ka():r==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:m,...i!==void 0&&{llmContent:i},...d!==void 0&&{contentParts:d},...h!==void 0&&{voiceProcessing:h},...y!==void 0&&{rawContent:y}};o.push(M)}return this.messages=this.sortMessages([...this.messages,...o]),this.callbacks.onMessagesChanged([...this.messages]),o}injectComponentDirective(t){let{component:o,props:n={},text:r="",llmContent:a,id:i,createdAt:d,sequence:c}=t,u={text:r,component:o,props:n};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...a!==void 0&&{llmContent:a},...i!==void 0&&{id:i},...d!==void 0&&{createdAt:d},...c!==void 0&&{sequence:c}})}async applyMentionBundle(t,o,n){let r;try{r=await n()}catch{return}let a=r.blocks.join(`
|
|
19
|
+
_Details: ${o.message}_`:n}var am=e=>({isError:!0,content:[{type:"text",text:e}]}),XE=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Nx=e=>_r(e)||e===_n,Da=class e{constructor(t={},o,n={}){this.config=t;this.callbacks=o;this.historyInternals=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new dl;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Oa(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let o=t.message.toolCall,n=!!o?.name&&(_r(o.name)||o.name===_n&&jr(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&n&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(n),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Rs(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&tm().catch(()=>{})}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let o=t.host??this.config.apiUrl,n=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!o||!n||!this.config.clientToken||rm().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return mv(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let o=Hs.isSupported()?new Hs({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let n=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,i=t.browserFallback!==!1;if(n&&r&&a)return rm().then(({RuntypeSpeechEngine:d,FallbackSpeechEngine:c})=>{let u=new d({host:n,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&o?new c(u,o,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});if(i&&o)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),o}return o}setupVoice(t){try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.cleanupVoice();let n=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=tm().then(async a=>{await n,r===this.voiceSetupGeneration&&this.wireVoiceProvider(a.createVoiceProvider(o))}).catch(a=>{console.error("Failed to setup voice:",a)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(o){console.error("Failed to setup voice:",o)}}wireVoiceProvider(t){try{this.voiceProvider=t;let o=this.voiceSetupGeneration,n=()=>this.voiceProvider===t&&o===this.voiceSetupGeneration,a=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{n()&&i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c,u)=>{if(n())if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.voiceTurns.start(u?.turnId),this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(u?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(i=>{n()&&(this.voiceLevel=Number.isFinite(i)?Math.max(0,Math.min(1,i)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{n()&&this.config.voiceRecognition?.onMetrics?.(i)}),this.voiceProvider.onError(i=>{n()&&(console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(i=>{n()&&(this.voiceStatus=i,this.voiceActive=i==="listening",(i==="listening"||i==="idle"||i==="disconnected")&&this.settlePendingVoiceTurn(i!=="listening"),this.callbacks.onVoiceStatusChanged?.(i))}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){let t=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let o=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(o)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new dl,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(t){try{await t.disconnect()}catch(o){console.error("Failed to disconnect voice:",o)}}settlePendingVoiceTurn(t){let o=t?this.pendingVoiceUserMessageId:null,n=this.pendingVoiceAssistantMessageId;!o&&!n||(n&&this.voiceTurns.cancel(),t&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(r=>r.id!==o&&r.id!==n?[r]:r.id===n&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let o={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,o){return this.client.submitMessageFeedback(t,o)}async submitCSATFeedback(t,o){return this.client.submitCSATFeedback(t,o)}async submitNPSFeedback(t,o){return this.client.submitNPSFeedback(t,o)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let o=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:n=>{this.handleHistoryContinuityChanged(n),o?.(n)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new Nn("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let o=this.requireHistoryProvider(),n=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",a=n??(o.capabilities.scopes.includes(r)?r:o.capabilities.scopes[0]??r);if(!o.capabilities.scopes.includes(a))throw new ln("unsupported_scope","This history scope is not supported.");return{scope:a}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(t,o){this.callbacks.onHistoryNotice?.({code:t,message:o})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let o=this.projectionFinalizationPromise;o&&await o.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Nn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,o){let n=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(o?.scope);await this.awaitHistorySettled();let a=++this.historyOpenEpoch,i=await n.getPage(t,{context:r});if(a!==this.historyOpenEpoch)throw new Nn("superseded","A later selection won");let d=await n.prepareOpen(t,{context:r});if(a!==this.historyOpenEpoch)throw d.discard(),new Nn("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(d)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=d.conversationId||t,this.activeConversationRevision=d.conversationRevision||i.conversationRevision||null,this.historyNextMessageCursor=i.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.persistConversationMetadata(),this.hydrateMessages(i.messages),this.emitHistoryState(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,o,n){let r=this.requireHistoryProvider(),a=this.historyContext(n?.scope),i=o??this.historyNextMessageCursor;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let d=`${t} ${i}`,c=this.olderPageRequests.get(d);if(c)return c;let u=this.fetchOlderPage(r,t,i,a).finally(()=>{this.olderPageRequests.delete(d)});return this.olderPageRequests.set(d,u),u}async fetchOlderPage(t,o,n,r){let a=this.messages[0]?.createdAt,i=await t.getPage(o,{cursor:n,...a?{beforeCreatedAt:a}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==o)return{messages:[],nextMessageCursor:i.nextCursor};let d=il(this.messages,i.messages);this.messages=this.sortMessages(d.map(c=>this.ensureSequence(c))),this.historyNextMessageCursor=i.nextCursor;for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,a=await o.prepareStartNew({context:n});if(r!==this.historyOpenEpoch)throw a.discard(),new Nn("superseded","A later action won");await this.installFreshConversation(a)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,o){let n=this.requireHistoryProvider(),r=this.historyContext(o?.scope);await this.awaitHistorySettled(),await n.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,o,n){let r=this.requireHistoryProvider();if(!r.update)throw new Nn("history_unavailable","This history provider cannot update conversations");let a=this.historyContext(n?.scope);return await this.awaitHistorySettled(),r.update(t,o,{context:a})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await o.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:n});return await this.recoverFromDestroyedConversation(n),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new Nn("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(t)}async prepareReplacementConversation(t){let o=this.historyProvider;if(!o){this.historySendBlocked=!1,this.emitHistoryState();return}try{let n=await o.prepareStartNew({context:t});await this.installFreshConversation(n)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new Nn("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let o=this.client.getClientSession();o&&o.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(o)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(o=>this.handleExternalCredentialChange(o))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let o=this.messages.length>0;o||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),o&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let o=this.historyProvider,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!o||!n)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let a=this.runBootReconciliation(o,n,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===a&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=a,a}async runBootReconciliation(t,o,n){this.activeConversationId=o;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,a=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&a&&r===a){this.activeConversationRevision=r;return}let i=await t.getPage(o,{context:n}),d=new Set(i.messages.map(m=>m.id)),c=this.messages.some(m=>d.has(m.id)),u=i.messages[0]?.createdAt,p;if(!c)p=i.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,h=this.messages.filter(y=>d.has(y.id)||y.id===m?!0:u!==void 0&&y.createdAt<u);p=il(h,i.messages).map(y=>this.ensureSequence(y))}this.historyNextMessageCursor=i.nextCursor,this.activeConversationRevision=i.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of i.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let o of t){let n=al(o);n!==void 0&&this.acknowledgedProjections.set(o.id,n)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let o=[];for(let n of this.messages){if(n.role!=="assistant"||n.streaming)continue;let r=al(n);r!==void 0&&this.acknowledgedProjections.get(n.id)!==r&&o.push({id:n.id,displayContent:r})}o.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:o.map(n=>n.id)}),this.enqueueProjectionFinalization(t,o))}enqueueProjectionFinalization(t,o){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,o,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,o,n){if(this.activeConversationId!==t)return;let r=o.filter(a=>this.acknowledgedProjections.get(a.id)!==a.displayContent);if(r.length===0){this.clearFinalizedMarker(t,o);return}try{let{conversationRevision:a}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.acknowledgedProjections.set(i.id,i.displayContent);this.activeConversationId===t&&a&&(this.activeConversationRevision=a),this.clearFinalizedMarker(t,o)}catch(a){if(!n&&this.isTransientProjectionError(a)){await this.finalizeProjections(t,r,!0);return}if(a instanceof _e&&(a.code==="not_found"||a.code==="conversation_deleted")){this.clearFinalizedMarker(t,o);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof _e?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,o){let n=this.readPendingProjections();if(!n||n.conversationId!==t)return;let r=new Set(o.map(i=>i.id)),a=n.messageIds.filter(i=>!r.has(i));this.setPendingProjections(a.length?{conversationId:t,messageIds:a}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let o=[];for(let n of t.messageIds){let r=this.messages.find(a=>a.id===n);!r||typeof r.content!="string"||o.push({id:n,displayContent:r.content})}if(o.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,o),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof _e&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,o,n,r,a){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt},this.handleEvent);return}catch(i){if(!e.isConversationDeleted(i))throw i;let d=await this.recoverFromDeletedConversation(r);if(!d)throw i;this.recordDispatchedProjections([d]),await this.client.dispatch({messages:[d],signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let o=this.messages.find(r=>r.id===t);if(!o)return null;let n={...o};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let a=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(a)}else{this.client.clearClientSession();let a=await this.client.initSession();this.bindActivatedSession(a)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(n),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===n.id)??n}updateConfig(t){let o=this.config.features?.artifacts?.display,n={...this.config,...t},r=fv(this.config,n),a=GE(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&Wo(n.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(o)!==JSON.stringify(n.features?.artifacts?.display);if(!a){this.client.updateConfig(n),i&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let d=this.client.getSSEEventCallback();this.client=new Rs(this.config,this.historyInternals),i&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),d&&this.client.setSSEEventCallback(d)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:o,content:n,llmContent:r,contentParts:a,id:i,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:p,rawContent:m}=t,y={id:i??(o==="user"?ka():o==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:o,content:n,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let o=[];for(let n of t){let{role:r,content:a,llmContent:i,contentParts:d,id:c,createdAt:u,sequence:p,streaming:m=!1,voiceProcessing:h,rawContent:y}=n,A={id:c??(r==="user"?ka():r==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:m,...i!==void 0&&{llmContent:i},...d!==void 0&&{contentParts:d},...h!==void 0&&{voiceProcessing:h},...y!==void 0&&{rawContent:y}};o.push(A)}return this.messages=this.sortMessages([...this.messages,...o]),this.callbacks.onMessagesChanged([...this.messages]),o}injectComponentDirective(t){let{component:o,props:n={},text:r="",llmContent:a,id:i,createdAt:d,sequence:c}=t,u={text:r,component:o,props:n};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...a!==void 0&&{llmContent:a},...i!==void 0&&{id:i},...d!==void 0&&{createdAt:d},...c!==void 0&&{sequence:c}})}async applyMentionBundle(t,o,n){let r;try{r=await n()}catch{return}let a=r.blocks.join(`
|
|
20
20
|
|
|
21
21
|
`),i=[a,o].filter(Boolean).join(`
|
|
22
22
|
|
|
23
|
-
`),d=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(d){let u=[];a&&u.push(an(a)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(c){let u=[];i&&u.push(an(i)),u.push(...r.contentParts),t.contentParts=u}else a&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,o){let n=t.trim(),r=!!o?.replayFields&&(o.replayFields.llmContent!==void 0||o.replayFields.rawContent!==void 0||(o.replayFields.contextMentions?.length??0)>0);if(!n&&(!o?.contentParts||o.contentParts.length===0)&&(!o?.mentions||o.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let a=ka(),i=Fr();this.activeAssistantMessageId=null;let d=o?.contentParts&&Ba(o.contentParts)?Wa:"",c={id:a,role:"user",content:n||d,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:o?.viaVoice||!1,...o?.contentParts&&o.contentParts.length>0&&{contentParts:o.contentParts},...o?.mentions&&o.mentions.refs.length>0&&{contextMentions:o.mentions.refs},...o?.contentSegments&&o.contentSegments.length>0&&{contentSegments:o.contentSegments},...o?.composerOptions&&{composerOptions:o.composerOptions},...o?.replayFields??{}};this.appendMessage(c),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,o?.mentions){let m=this.messages.find(h=>h.id===a)??c;if(await this.applyMentionBundle(m,n,o.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(o?.quote&&!o.replayFields){let m=this.messages.find(y=>y.id===a)??c,h=Ex({quote:o.quote,text:m.llmContent??m.content,contentParts:m.contentParts});h.contentParts&&(m.contentParts=h.contentParts),h.llmContent!==void 0&&(m.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(m.quote={...o.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=[...this.messages];try{await this.dispatchWithDeletedRecovery(p,u,i,a,{composerOptions:o?.composerOptions,interrupt:o?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let h=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!h){let y=rm(m,this.config.errorMessage);if(y){let x={id:i,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(x)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,o){let n=Px(this.messages,t);if(!n)return!1;let r=this.messages[n.start],a=o.replacement,i=a?a.text:r.content,d=a?a.contentParts:r.contentParts;if(!(!!i?.trim()||(d?.length??0)>0||!a&&(r.llmContent?.trim()?.length??0)>0))return!1;let u=a?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},p=a?this.toComposerOptionsPayload(a.options):r.composerOptions,m=a?a.contentSegments:r.contentSegments,h=a?a.options?.quote:void 0,y=a?a.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(i??"",{...d?.length?{contentParts:[...d]}:{},...m?.length?{contentSegments:[...m]}:{},...p?{composerOptions:p}:{},...h?{quote:h}:{},...u&&Object.keys(u).length>0?{replayFields:u}:{},viaVoice:y===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=Fr();this.activeAssistantMessageId=null,this.setStreaming(!0);let o=new AbortController;this.abortController=o;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:o.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let i=rm(r,this.config.errorMessage);if(i){let d={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(d)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,o){if(this.streaming&&!o?.allowReentry)return;o?.allowReentry||this.abortController?.abort(),o?.preserveAssistantId&&o.assistantMessageId&&(this.activeAssistantMessageId=o.assistantMessageId);let n=o?.preserveAssistantId?o.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==n&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,o?.assistantMessageId,o?.seedContent)}catch(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(o=>this.requestWebMcpApproval(o))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let o={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},n=`approval-${o.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o}),new Promise(r=>{this.webMcpApprovalResolvers.set(n,r)})}resolveWebMcpApproval(t,o){let n=this.webMcpApprovalResolvers.get(t);if(!n)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:o,resolvedAt:Date.now()}}),n(o==="approved")}async resolveApproval(t,o,n){let r=`approval-${t.id}`,a={...t,status:o,resolvedAt:Date.now()},i=this.messages.find(p=>p.id===r),d={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(d),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,u=c&&typeof c=="object"?c.onDecision:void 0;try{let p;if(u?p=await u({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},o,n):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},o),p){let m=null;if(p instanceof Response){if(!p.ok){let h=await p.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m,{allowReentry:!0}):(o==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:o.answers,askUserQuestionIndex:o.currentIndex}})}markAskUserQuestionResolved(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...o?{askUserQuestionAnswers:o}:{}}})}async resolveAskUserQuestion(t,o){if(this.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof o=="string"?void 0:o;if(i===void 0&&typeof o=="string"){let p=t.toolCall?.args,m=Array.isArray(p?.questions)?p.questions:[];if(m.length===1){let h=typeof m[0]?.question=="string"?m[0].question:"";h&&(i={[h]:o})}}this.markAskUserQuestionResolved(t,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=t.toolCall.id,c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===0){let p=typeof o=="string"?o:Object.entries(o).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${d}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=i??{};u.forEach((m,h)=>{let y=typeof m?.question=="string"?m.question:"";if(!y)return;let x=p[y],M=Array.isArray(x)?x.join(", "):typeof x=="string"?x:"";this.appendMessage({id:`ask-user-q-${d}-${h}`,role:"assistant",content:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${d}-${h}`,role:"user",content:M||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[a]:o},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}enqueueWebMcpAwait(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.id;if(!o||!n){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(o);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(o,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let o of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(o)})}flushWebMcpAwaitBatch(t){let o=this.webMcpAwaitBatches.get(t);if(!o)return;this.webMcpAwaitBatches.delete(t);let{snapshots:n}=o;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(t,n)}resolveWebMcpToolStartedAt(t){let n=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of n)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==_n?!1:(this.messages.find(n=>n.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let o=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:o,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),o}markWebMcpToolComplete(t,o,n,r=Date.now(),a){this.messages.some(i=>i.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:o,startedAt:n,completedAt:r,duration:void 0,durationMs:Math.max(0,r-n)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,o){let n=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let a=async c=>{let u=c.toolCall?.name,p=c.toolCall?.id;if(!u||!p)return null;let m=`${t}:${p}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(m),n.push(m);let h=this.markWebMcpToolRunning(c),y=c.agentMetadata?.webMcpToolCallId??u;if(u===_n)return{dedupeKey:m,resumeKey:y,output:ex(),toolMessage:c,startedAt:h,completedAt:Date.now()};let x=this.client.executeWebMcpToolCall(u,c.toolCall?.args,r.signal),M;if(!x)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await x}catch(S){let k=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));return k||this.callbacks.onError?.(S instanceof Error?S:new Error(String(S))),this.markWebMcpToolComplete(c,sm(k?"Aborted by cancel()":VE(S)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(c,sm("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:y,output:M,toolMessage:c,startedAt:h,completedAt:Date.now()}},i;if(this.config.webmcp?.execution==="sequential"){i=[];for(let c of o)i.push(await a(c))}else i=await Promise.all(o.map(a));let d=[];try{if(d=i.filter(p=>p!==null),d.length===0)return;let c={};for(let p of d)c[p.resumeKey]=p.output;let u=await this.client.resumeFlow(t,c,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!u.ok){let p=await u.json().catch(()=>null);throw new Error(p?.error??`Resume failed: ${u.status}`)}for(let p of d)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt,p.toolMessage.toolCall?.name===_n?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let p of d)this.markWebMcpToolComplete(p.toolMessage,sm("Aborted by cancel()"),p.startedAt)}finally{for(let c of n)this.webMcpInflightKeys.delete(c);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.name,r=t.toolCall?.id;if(!o){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!n)return;if(!r){let i=`${o}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i))return;this.webMcpInflightKeys.add(i);try{await this.resumeWithToolOutput(o,n,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(i)}catch(d){this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}finally{this.webMcpInflightKeys.delete(i)}return}let a=`${o}:${r}`;if(!(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(o,[t])}async resumeWithToolOutput(t,o,n,r){let a=await this.client.resumeFlow(t,{[o]:n},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!a.ok){let i=await a.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${a.status}`)}r?.onHttpOk?.(),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let o=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=t.artifactType==="markdown"?{id:o,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:o,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(o,n),this.selectedArtifactId=o,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(n),n}injectArtifactRefBlock(t){let o=`artifact-ref-${t.id}`,n=Dn(this.config.features?.artifacts,t),r=Zi(n,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(i=>i.id===o);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:o,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let o of this.artifacts.values()){let n=this.messages.find(i=>i.id===`artifact-ref-${o.id}`);if(!n)continue;let r=Dn(this.config.features?.artifacts,o),a=Zi(r,{artifactId:o.id,title:o.title,artifactType:o.artifactType,status:o.status,...o.file?{file:o.file}:{},...o.presentation?{presentation:o.presentation}:{},...o.component?{component:o.component}:{},...o.props?{componentProps:o.props}:{},...o.markdown!==void 0?{markdown:o.markdown}:{}});n.rawContent!==a&&(n.rawContent=a,n.streaming=o.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);o?.artifactType==="markdown"&&(o.markdown=(o.markdown??"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);o?.artifactType==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>({...o,streaming:!1,sequence:o.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,o=null){this.artifacts.clear();for(let n of t)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=o,this.emitArtifactsState()}trackCursor(t){let o=this.agentExecution?.executionId;if(!o||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let n=this.resumable===null;this.resumable={executionId:o,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(n)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Bx().then(({createReconnectController:t})=>{let o=t(this.buildReconnectHost());return this.reconnectController=o,o}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:o=>t.setStatus(o),setStreaming:o=>t.setStreaming(o),setReconnecting:o=>{t.reconnecting=o},setAbortController:o=>{t.abortController=o},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(o,n,r)=>t.connectStream(o,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:o=>t.appendMessage(o),nextSequence:()=>t.nextSequence(),emitReconnect:o=>t.callbacks.onReconnect?.(o),buildErrorContent:o=>rm(new Error(o),t.config.errorMessage),onError:o=>t.callbacks.onError?.(o)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let o=this.reopenTrailingAssistant();o||(o=Fr(),this.appendMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=o,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:o,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let o=this.messages[t];if(o.role==="assistant"&&!o.variant)return o.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),o.id;if(o.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let o=this.config.onExecutionState;if(o){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),o(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let o=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),o&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let n=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=tm(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ll(t)}toggleReadAloud(t){let o=this.messages.find(a=>a.id===t);if(!o||o.role!=="assistant")return;let n=tm(o.content||"");if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let o=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let o=this.ensureSequence(t),n=this.messages.findIndex(r=>r.id===o.id);if(n===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,a)=>{if(a!==n)return r;let i={...r,...o};if(r.agentMetadata?.askUserQuestionAnswered===!0&&o.agentMetadata&&(i.agentMetadata={...o.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&o.agentMetadata&&(i.agentMetadata={...i.agentMetadata??o.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&o.approval&&r.approval.id===o.approval.id){let p=r.approval,m=o.approval;i.approval={...p,...m,executionId:m.executionId||p.executionId,toolName:m.toolName||p.toolName,description:m.description||p.description,toolType:m.toolType??p.toolType,reason:m.reason??p.reason,parameters:m.parameters??p.parameters}}let d=o.toolCall?.name,c=o.agentMetadata?.executionId,u=o.toolCall?.id;if(d&&Ox(d)&&c&&u&&o.agentMetadata?.awaitingLocalTool===!0){let p=`${c}:${u}`,m=this.webMcpInflightKeys.has(p),h=this.webMcpResolvedKeys.has(p),y=r.toolCall?.name,x=r.agentMetadata?.executionId===c&&r.toolCall?.id===u&&y!==void 0&&Ox(y)&&r.toolCall?.status==="complete";(m||h||x)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((o,n)=>{let r=new Date(o.createdAt).getTime(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let i=o.sequence??0,d=n.sequence??0;return i!==d?i-d:o.id.localeCompare(n.id)})}};var _a=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var am=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var im=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var cl=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var lm=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var dm=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var cm=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var um=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Na=[["path",{d:"M20 6 9 17l-5-5"}]];var ul=[["path",{d:"m6 9 6 6 6-6"}]];var pm=[["path",{d:"m15 18-6-6 6-6"}]];var fm=[["path",{d:"m9 18 6-6-6-6"}]];var Ws=[["path",{d:"m18 15-6-6-6 6"}]];var mm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var gm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var Ic=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Fa=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var hm=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Rc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Hc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var ym=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var bm=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var pl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var fl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Bs=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var ml=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var vm=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var xm=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Wc=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Cm=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Sm=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var wm=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var gl=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var Am=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Mm=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Tm=[["path",{d:"M5 12h14"}]];var Bc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]];var Em=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Pm=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var km=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Lm=[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]];var Im=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Rm=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Hm=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Wm=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Bm=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Oc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Om=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Dm=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var _m=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Nm=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Fm=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Um=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var qm=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Vm=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var hl=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Ut=(e,t=24,o="currentColor",n=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(n)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let i=a[0],d=a[1];if(!d)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(d).forEach(([u,p])=>{u!=="stroke"&&c.setAttribute(u,String(p))}),r.appendChild(c)}),r};var{setLoader:$E,load:jE}=mt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),Dx=$E,Dc=jE;var zE={activity:_a,"arrow-down":am,"arrow-up":dm,"arrow-up-right":lm,bot:um,"chevron-down":ul,"chevron-up":Ws,"chevron-right":fm,"chevron-left":pm,check:Na,clipboard:gm,"clipboard-copy":mm,"code-xml":Ic,copy:Fa,file:ml,"file-code":pl,"file-spreadsheet":fl,"file-text":Bs,"image-plus":xm,loader:Cm,"loader-circle":Wc,mic:Am,paperclip:Em,quote:Lm,"refresh-cw":Im,search:Rm,send:Hm,"shield-alert":Wm,"shield-check":Bm,"shield-x":Oc,square:Om,"thumbs-down":_m,"thumbs-up":Nm,upload:qm,"volume-2":Vm,x:hl,"at-sign":cm,"arrow-left":im,"arrow-right":cl,"external-link":ym,ellipsis:Hc,"ellipsis-vertical":Rc,menu:wm,"panel-left":Bc,plus:km,minus:Tm,pencil:Pm,trash:Um,"trash-2":Fm,download:hm,maximize:Sm,minimize:Mm,"message-square":gl,star:Dm,eye:bm,history:vm},KE=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],yl=new Map(Object.entries(zE)),Ua=new Set,_c=!1,Nc=new Set,_x=e=>{let t=[...Nc];e&&Nc.clear();for(let o of t)try{o()}catch{}},Nx=e=>_c?()=>{}:(Nc.add(e),()=>{Nc.delete(e)}),Fx=()=>{let e=0;for(let t of[...Ua]){let o=yl.get(t.name);if(!o)continue;Ua.delete(t),e++;let n=Ut(o,t.size,t.color,t.strokeWidth);if(n)for(t.el.removeAttribute("data-persona-icon-pending");n.firstChild;)t.el.appendChild(n.firstChild)}return e},Ux=e=>{for(let[t,o]of Object.entries(e))yl.set(t,o);Fx()>0&&!_c&&_x(!1)};var $m=!1,GE=()=>{Dc().then(e=>{if(!_c){for(let[t,o]of Object.entries(e.EXTRA_LUCIDE_ICONS))yl.has(t)||yl.set(t,o);_c=!0,Fx(),_x(!0)}}).catch(e=>{$m=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},XE=(e,t,o)=>{let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n},le=(e,t=24,o="currentColor",n=2)=>{let r=yl.get(e);if(r)return Ut(r,t,o,n);if(KE.includes(e)){$m&&($m=!1);let a=XE(t,o,n);if(Ua.size>=500){let i=Ua.values().next().value;i&&Ua.delete(i)}return Ua.add({el:a,name:e,size:t,color:o,strokeWidth:n}),GE(),a}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null};var QE={add:e=>px(e)},YE=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Fc={allowedTypes:mr,maxFileSize:10*1024*1024,maxFiles:4};function JE(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ZE(e){return e==="application/pdf"?Bs:e.startsWith("text/")?Bs:e.includes("word")?Bs:e.includes("excel")||e.includes("spreadsheet")?fl:e==="application/json"?pl:ml}var Os=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??Fc.allowedTypes,maxFileSize:t.maxFileSize??Fc.maxFileSize,maxFiles:t.maxFiles??Fc.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:QE}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let o of this.attachments)this.renderPreview(o)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Fc.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.destroyed)return;let o=[];for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let r=fx(n,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,i);continue}let a={id:JE(),file:n,previewUrl:Pc(n)?URL.createObjectURL(n):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(a),this.renderPreview(a),o.push(a)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(o.map(n=>this.runAdd(n)))}async runAdd(t){let o=new AbortController;this.pendingAdds.set(t.id,o);let n=()=>this.destroyed||o.signal.aborted||this.pendingAdds.get(t.id)!==o||!this.attachments.includes(t);try{let r=await this.adapter().add(t.file,{signal:o.signal,onProgress:a=>{n()||t.status!=="uploading"||(t.progress=YE(a),this.updatePreview(t),this.notify())}});if(n())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(n())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(t.id)===o&&this.pendingAdds.delete(t.id)}this.updatePreview(t),this.notify()}retryAttachment(t){let o=this.attachments.find(n=>n.id===t);!o||o.status!=="error"||this.destroyed||(o.status=this.hasCustomAdapter()?"uploading":"processing",o.progress=this.hasCustomAdapter()?0:void 0,o.error=void 0,this.updatePreview(o),this.notify(),this.runAdd(o))}abortAdd(t){let o=this.pendingAdds.get(t);o&&(this.pendingAdds.delete(t),o.abort())}removeAttachment(t){let o=this.attachments.findIndex(a=>a.id===t);if(o===-1)return;let n=this.attachments[o];this.abortAdd(t),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(o,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),n.status==="ready"&&n.contentPart&&this.releasePart(n.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(t){let o=this.config.adapter?.remove;if(o)try{let n=o(t,{signal:new AbortController().signal});n&&typeof n.catch=="function"&&n.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(n){console.error("[AttachmentManager] adapter.remove failed:",n)}}clearAttachments(){for(let t of this.attachments)this.abortAdd(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let t of this.pendingAdds.values())t.abort();this.pendingAdds.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let o=Pc(t.file),n=R("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",t.id),n.style.width="48px",n.style.height="48px",o&&t.previewUrl){let p=R("img");p.src=t.previewUrl,p.alt=t.file.name,p.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",p.style.width="48px",p.style.height="48px",p.style.objectFit="cover",p.style.borderRadius="8px",n.appendChild(p)}else{let p=R("div");p.style.width="48px",p.style.height="48px",p.style.borderRadius="8px",p.style.backgroundColor="var(--persona-container, #f3f4f6)",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.display="flex",p.style.flexDirection="column",p.style.alignItems="center",p.style.justifyContent="center",p.style.gap="2px",p.style.overflow="hidden";let m=ZE(t.file.type),h=Ut(m,20,"var(--persona-muted, #6b7280)",1.5);h&&p.appendChild(h);let y=R("span");y.textContent=mx(t.file.type,t.file.name),y.style.fontSize="8px",y.style.fontWeight="600",y.style.color="var(--persona-muted, #6b7280)",y.style.textTransform="uppercase",y.style.lineHeight="1",p.appendChild(y),n.appendChild(p)}let r=Q("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),a=R("div","persona-attachment-progress");a.appendChild(R("div","persona-attachment-progress__bar"));let i=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),d=le("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);d?i.appendChild(d):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(a,i),n.appendChild(r);let c=R("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let u=Ut(hl,10,"var(--persona-text-inverse, #ffffff)",2);u?c.appendChild(u):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),n.appendChild(c),this.previewsContainer.appendChild(n),this.applyPreviewState(n,t)}updatePreview(t){let o=this.previewsContainer?.querySelector(`[data-attachment-id="${t.id}"]`);o&&this.applyPreviewState(o,t)}applyPreviewState(t,o){t.dataset.status=o.status;let n=o.status!=="ready"&&o.status!=="error";t.setAttribute("aria-busy",n?"true":"false"),t.title=o.status==="error"?`${o.file.name}: ${o.error??"Upload failed"}`:o.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let a=o.progress;r.style.width=typeof a=="number"?`${Math.round(a*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,o){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:o,adapter:t?.adapter})}};var qx=(e,t)=>e.length===t.length&&e.every((o,n)=>o===t[n]),e0=(e,t)=>e.length===t.length&&e.every((o,n)=>{let r=t[n];return o.id===r.id&&o.name===r.name&&o.mimeType===r.mimeType&&o.size===r.size&&o.status===r.status&&o.progress===r.progress&&o.error===r.error});function Vx(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,o=null,n=!1,r=!1,a=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let p=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:p,inputDisabled:e.inputDisabled,sendDisabled:p!=="idle"||e.sendDisabled||e.inputDisabled})},d=()=>(o||(o=i()),o),c=()=>{if(n=!1,r||t.size===0)return;let p=d();for(let m of[...t])try{m(p)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},u=()=>{o=null,!(r||n)&&(n=!0,queueMicrotask(c))};return{getState:d,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,u())},setAttachments:p=>{e0(e.attachments,p)||(e.attachments=[...p],u())},setMentionRefs:p=>{qx(e.mentionRefs,p)||(e.mentionRefs=[...p],u())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,u())},setActiveModeIds:p=>{qx(e.activeModeIds,p)||(e.activeModeIds=[...p],u())},setQuote:p=>{let m=e.quote;m?.text===p?.text&&m?.messageId===p?.messageId&&m?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,u())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,u())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,u())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,u())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,u())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,u())},flush:()=>{n&&c()},destroy:()=>{r=!0,n=!1,t.clear()}}}var Oo=(e,...t)=>{for(let o of t){let n=e.querySelector(o);if(n)return n}return null},$x=(e,t)=>{let o=R("div",e);return o.setAttribute(t,""),o.setAttribute("data-persona-composer-synthesized",""),o.style.display="contents",o};function jx(e,t={}){let o=Oo(e,"[data-persona-composer-form]"),n=Oo(e,"[data-persona-composer-input]");if(!o||!n){let k=`[Persona] composer surface is missing required element(s): ${[!o&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(o||n))throw new Error(k);return typeof console<"u"&&console.warn(k),null}let r={header:Oo(e,"[data-persona-composer-header]"),body:Oo(e,"[data-persona-composer-body]"),actionsStart:Oo(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Oo(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Oo(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Oo(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Oo(e,"[data-persona-composer-status]")},a=new Set,i=r.header;i||(a.add("header"),i=$x("persona-widget-composer__header","data-persona-composer-header"),o.parentNode?o.parentNode.insertBefore(i,o):e.appendChild(i));let d=r.body??n.parentElement??o,c=(S,k,P,H,b)=>{if(k)return k;a.add(S);let w=$x(P,H);return b.appendChild(w),w},u=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",o),p=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",o),m=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),h=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),y=[],x=(S,k)=>S.target===k.target&&S.type===k.type&&S.handler===k.handler,M=Oo(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:o,input:n,header:i,body:d,actionsStart:u,actionsEnd:p,suggestions:m,status:h,attachmentInput:M,attachmentPreviews:Oo(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Oo(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Oo(e,"[data-persona-composer-submit]")??void 0,micButton:Oo(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:r,addListener:(S,k,P,H)=>{S.addEventListener(k,P,H),y.push({target:S,type:k,handler:P,options:H})},removeListener:(S,k,P,H)=>{S.removeEventListener(k,P,H),y=y.filter(b=>!x(b,{target:S,type:k,handler:P}))},destroy:()=>{for(let S of y)S.target.removeEventListener(S.type,S.handler,S.options);y=[]}}}var qt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},ro=1e5,qa=ro+1;var t0=8,o0=8,jm=10,zx=200,Kx=300,Gx=0,qc=e=>Math.max(0,e);function Xx(e){e.delayMs!==void 0&&(zx=qc(e.delayMs)),e.skipDelayMs!==void 0&&(Kx=qc(e.skipDelayMs))}var n0=()=>Date.now()<Gx,r0=e=>{Gx=e>0?Date.now()+e:0},Uc=new WeakMap,Km="data-persona-tooltip-suppressed",s0=e=>typeof e.closest=="function"&&e.closest(`[${Km}]`)!==null;function Qx(e){Uc.get(e)?.hide()}var Yx=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,a0=e=>{let t=e.getRootNode?.();return Yx(t)?t:e.ownerDocument.body},zm=(e,t,o)=>Math.min(Math.max(e,t),Math.max(t,o)),i0=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function Jt(e){Uc.get(e.anchor)?.destroy();let{anchor:t,trigger:o=t,text:n,hint:r,enabled:a=!0,gap:i=t0,viewportPadding:d=o0}=e,c=()=>t.ownerDocument,u=()=>c().defaultView??window,p=null,m=null,h=null,y=null,x,M=!1,S=!1,k=!1,P=()=>(typeof n=="function"?n():n).trim(),H=()=>(typeof r=="function"?r():r??"").trim(),b=()=>qc(e.delayMs??zx),w=()=>qc(e.skipDelayMs??Kx),C=()=>{x!==void 0&&(u().clearTimeout(x),x=void 0)},L=()=>{C();let ye=p!==null;y?.(),y=null,p?.remove(),p=null,m=null,h=null,ye&&r0(w())},N=()=>{if(!p)return;let ye=c(),Re=u(),be=t.getBoundingClientRect(),pe=p.getBoundingClientRect(),yt=ye.documentElement.clientWidth||Re.innerWidth,Pe=ye.documentElement.clientHeight||Re.innerHeight,q=yt-d-pe.width,Ue=be.left+be.width/2-pe.width/2,Je=zm(Ue,d,q),so=be.top-d,Le=Pe-d-be.bottom,qe=pe.height+i,ve=so>=qe||so>=Le?"top":"bottom",po=ve==="top"?be.top-i-pe.height:be.bottom+i,dn=Pe-d-pe.height,Vn=zm(po,d,dn),wt=be.left+be.width/2,$n=Math.max(jm,pe.width-jm),z=zm(wt-Je,jm,$n);p.dataset.placement=ve,p.style.left=`${Je}px`,p.style.top=`${Vn}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${z}px`)},X=()=>{if(k||!a||p||!t.isConnected||s0(t))return;let ye=P(),Re=a0(t);if(!ye||!Re)return;let be=c(),pe=u();p=be.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(qa);let yt=pe.getComputedStyle?.(t);if(yt){for(let qe of i0){let ve=yt.getPropertyValue(qe).trim();ve&&p.style.setProperty(qe,ve)}yt.fontFamily&&(p.style.fontFamily=yt.fontFamily)}m=be.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ye,p.appendChild(m);let Pe=H();Pe&&(h=be.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=Pe,p.appendChild(h));let q=be.createElement("span");q.className="persona-control-tooltip__arrow",p.appendChild(q),Re.appendChild(p),N(),p.dataset.state="open";let Ue=()=>{if(!t.isConnected){L();return}m&&(m.textContent=P()),h&&(h.textContent=H()),N()};pe.addEventListener("scroll",Ue,!0),pe.addEventListener("resize",Ue);let Je=t.getRootNode(),so=Yx(Je)?Je:be.documentElement,Le=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||L()});Le?.observe(so,{childList:!0,subtree:!0}),y=()=>{pe.removeEventListener("scroll",Ue,!0),pe.removeEventListener("resize",Ue),Le?.disconnect()}},V=ye=>{if(!(k||p)){if(C(),ye||b()<=0||n0()){X();return}x=u().setTimeout(()=>{x=void 0,X()},b())}},T=()=>{M||S?V(S):L()},O=()=>{let ye=u();(!ye.matchMedia||!ye.matchMedia("(hover: none)").matches)&&(M=!0,T())},D=()=>{M=!1,T()},W=()=>{try{S=t.matches(":focus-visible")}catch{S=!0}T()},ee=()=>{S=!1,T()},G=()=>{M=!1,S=!1,L()},ue=ye=>{ye.key==="Escape"&&G()};o.addEventListener("mouseenter",O),o.addEventListener("mouseleave",D),t.addEventListener("focus",W),t.addEventListener("blur",ee),t.addEventListener("keydown",ue),t.addEventListener("click",G);let ae={get isOpen(){return p!==null},show:X,hide:L,reposition:N,destroy:()=>{k||(k=!0,L(),o.removeEventListener("mouseenter",O),o.removeEventListener("mouseleave",D),t.removeEventListener("focus",W),t.removeEventListener("blur",ee),t.removeEventListener("keydown",ue),t.removeEventListener("click",G),Uc.delete(t))}};return Uc.set(t,ae),ae}var Jx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Va(e,t){if(!e)return t;if(!t)return e;let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];Jx(a)&&Jx(r)?o[n]=Va(a,r):o[n]=r}return o}var Ko="min(440px, calc(100vw - 24px))",Vc="440px",Gm="How can I help...",l0={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Ko,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:l0,copy:{inputPlaceholder:Gm,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Zx(e,t){if(!(!e&&!t))return e?t?Va(e,t):e:t}function $a(e){return e?{...rt,...e,theme:Zx(rt.theme,e.theme),darkTheme:Zx(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...rt.tooltip,...e.tooltip},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,o=e.features?.artifacts,n=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,a=rt.features?.scrollBehavior,i=e.features?.scrollBehavior,d=rt.features?.streamAnimation,c=e.features?.streamAnimation,u=rt.features?.askUserQuestion,p=e.features?.askUserQuestion,m=rt.features?.history,h=e.features?.history,y=t===void 0&&o===void 0?void 0:{...t,...o,layout:{...t?.layout,...o?.layout}},x=n===void 0&&r===void 0?void 0:{...n,...r},M=a===void 0&&i===void 0?void 0:{...a,...i},S=d===void 0&&c===void 0?void 0:{...d,...c},k=u===void 0&&p===void 0?void 0:{...u,...p,styles:{...u?.styles,...p?.styles}},P=m===void 0&&h===void 0?void 0:{...m,...h,copy:{...m?.copy,...h?.copy}};return{...rt.features,...e.features,...x!==void 0?{scrollToBottom:x}:{},...M!==void 0?{scrollBehavior:M}:{},...y!==void 0?{artifacts:y}:{},...S!==void 0?{streamAnimation:S}:{},...k!==void 0?{askUserQuestion:k}:{},...P!==void 0?{history:P}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}function Xm(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let o=t.getComputedStyle(e).lineHeight;if(!o||!o.trim().endsWith("px"))return 20;let n=parseFloat(o);return Number.isFinite(n)&&n>0?n:20}function $c(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function eC(e,t){e.style.maxHeight=`${t*Xm(e)}px`,e.style.overflowY="auto"}function xl(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function tC(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function oC(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let o=e.metaKey===!0||e.ctrlKey===!0,n=t.submitKey??"enter";return n==="none"?!1:n==="mod-enter"?o:o||!tC(t)}function d0(e){return(e.submitKey??"enter")!=="enter"||tC(e)?"enter":"send"}function jc(e,t){e.setAttribute("enterkeyhint",d0(t))}function zc(e,t){let o=t?.autocomplete;e.setAttribute("autocomplete",typeof o=="string"&&o?o:"off");let n=(r,a)=>{a===void 0?e.removeAttribute(r):e.setAttribute(r,a)};n("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),n("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),n("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),n("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Qm(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var Go="persona-composer-control",xn="persona-composer-control--glyph",Jm=40,bo=24,Kc=(e,t,o)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let r=n.getComputedStyle(e);for(let a of o){let i=r.getPropertyValue(a).trim();i?t.style.setProperty(a,i):t.style.removeProperty(a)}},Gc=(e,t)=>{let o=R("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=e?.copy?.inputPlaceholder??Gm,o.dir="auto",jc(o,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:xl(o)}),zc(o,e?.composer?.inputAttributes),o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=$c(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${n*20}px`;o.style.maxHeight=r,o.style.overflowY="auto";let a=()=>{let d=o.style.maxHeight;if(d!==r){let u=parseFloat(d);if(Number.isFinite(u)&&u>0)return u}let c=n*Xm(o);return r=`${c}px`,o.style.maxHeight=r,c},i=()=>{o.addEventListener("input",()=>{o.style.height="auto";let d=Math.min(o.scrollHeight,a());o.style.height=`${d}px`})};return o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"}),{textarea:o,attachAutoResize:i}},u0="[data-persona-glyph-stack]",Zm=(e,t,o="send")=>{let n=Q("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":o,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},Xc=e=>{let t=e?.sendButton??{},o=t.useIcon??!1,n=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",i=t.tooltipText??"Send message",d=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",u=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,m=t.size,h=parseFloat(m??"")||Jm,y=t.backgroundColor,x=t.textColor,M=R("div","persona-send-button-wrapper"),S=Q("button",{className:yo("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?`persona-flex persona-items-center persona-justify-center ${Go}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",o&&!y&&"persona-bg-persona-primary",!o&&!x&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:o?m:void 0,height:o?m:void 0,minWidth:o?m:void 0,minHeight:o?m:void 0,fontSize:o?"18px":void 0,lineHeight:o?"1":void 0,color:o?x||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":x||void 0,backgroundColor:o&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:o?"0":t.paddingX||void 0,paddingRight:o?"0":t.paddingX||void 0,paddingTop:o?"0":t.paddingY||void 0,paddingBottom:o?"0":t.paddingY||void 0}}),k=null,P=null,H=null;if(o){let C=parseFloat(t.iconSize??"")||Math.round(h*.5),L=t.iconStrokeWidth??2,N=x?.trim()||"currentColor";r&&(k=le(r,C,N,L)),P=le(a,C,N,L),k&&P?(H=Zm(k,P),S.appendChild(H)):k?S.appendChild(k):(S.textContent=n,P=null)}else S.textContent=c;S.setAttribute("aria-label",i),M.appendChild(S),Jt({anchor:S,trigger:M,text:()=>S.getAttribute("aria-label")??"",enabled:p});let b="send";return{button:S,wrapper:M,setMode:C=>{if(C===b)return;b=C;let L=C==="stop"?d:i;S.setAttribute("aria-label",L),S.setAttribute("data-persona-send-mode",C),o?(S.querySelector(u0)??H)?.setAttribute("data-mode",C):S.textContent=C==="stop"?u:c},glyphStack:H}},ja=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let n=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",a=t.provider?.type==="custom";if(!(n||r||a))return null;let d=t.iconName??"mic",c=t.iconSize,u=parseFloat(c??"")||bo,p=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,h=R("div","persona-send-button-wrapper"),y=Q("button",{className:yo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Go,!c&&xn),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),M=le(d,u,m||"currentColor",1.5);M?y.appendChild(M):y.textContent="\u{1F3A4}",h.appendChild(y);let S=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return Jt({anchor:y,trigger:h,text:()=>y.getAttribute("aria-label")??S,enabled:k}),{button:y,wrapper:h}},Qc=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let o=R("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=R("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??mr).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",a=R("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Go} ${xn}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),d=le(r,bo,"currentColor",1.5);d?i.appendChild(d):i.textContent="\u{1F4CE}",i.addEventListener("click",u=>{u.preventDefault(),n.click()}),a.appendChild(i);let c=t.buttonTooltipText??"Attach file";return Jt({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:a,input:n,previewsContainer:o}},Yc=e=>{let t=e?.statusIndicator??{},o=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",n=R("div",`persona-mt-2 ${o} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let r=t.visible??!0;n.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let i=R("a");i.href=t.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=a,i.style.color="inherit",i.style.textDecoration="none",n.appendChild(i)}else n.textContent=a;return n},Jc=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function p0(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Zc(e){let{anchor:t,content:o,placement:n="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:i,verticalOffset:d,zIndex:c=2147483e3,onOpen:u,onDismiss:p}=e,m=e.container??p0(t),h=!1,y=null,x=()=>{if(!h)return;let k=t.getBoundingClientRect();o.style.position="fixed",a&&(o.style.minWidth=`${k.width}px`),i&&(o.style.maxWidth=`${k.width}px`);let P=o.getBoundingClientRect(),H=d?.()??null,b=H!=null?k.top+H:k.top,w=n==="top-start"||n==="top-end"?b-r-P.height:k.bottom+r,L=n==="bottom-end"||n==="top-end"?k.right-P.width:k.left,N=i?.()??null;if(N!=null){let X=Math.max(k.left,k.right-P.width);L=Math.min(Math.max(k.left+N,k.left),X)}o.style.top=`${w}px`,o.style.left=`${L}px`},M=()=>{h&&(h=!1,y&&(y(),y=null),o.remove())},S=()=>{if(h)return;h=!0,c!=null&&(o.style.zIndex=String(c)),m.appendChild(o),x();let k=(t.ownerDocument??document).defaultView??window,P=t.ownerDocument??document,H=()=>{if(!t.isConnected){M(),p?.("anchor-removed");return}x()},b=C=>{let L=typeof C.composedPath=="function"?C.composedPath():[];L.includes(o)||L.includes(t)||(M(),p?.("outside"))},w=k.setTimeout(()=>{P.addEventListener("pointerdown",b,!0)},0);k.addEventListener("scroll",H,!0),k.addEventListener("resize",H),y=()=>{k.clearTimeout(w),P.removeEventListener("pointerdown",b,!0),k.removeEventListener("scroll",H,!0),k.removeEventListener("resize",H)},u?.()};return{get isOpen(){return h},open:S,close:M,toggle:()=>h?M():S(),reposition:x,destroy:M}}var f0='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',m0=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],eg="data-persona-menu-focus",g0=new Set(["ArrowDown","ArrowUp","Home","End"]);function nC(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(f0)??e}var h0=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function rC(e){let t=e.label,o=!1,n=R("div","persona-send-button-wrapper"),r=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Go} ${xn}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(r);let a=Q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let W=e.getButtonSize?.()??"";r.style.width=W,r.style.height=W,r.style.minWidth=W,r.style.minHeight=W,r.style.lineHeight="1",r.replaceChildren();let ee=le("plus",bo,"currentColor",1.5);ee?r.appendChild(ee):r.textContent="+"},d=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),a.setAttribute("aria-label",t)};d(),i();let c=[],u=-1,p=!1,m=()=>{let ee=a.getRootNode().activeElement;return ee instanceof HTMLElement?ee:null},h=()=>{let W=m();for(let ee of c){let G=!!W&&nC(ee)===W;ee.toggleAttribute(eg,G&&p)}},y=()=>c.filter(W=>W.isConnected||a.contains(W)).map(nC).filter(W=>!h0(W)),x=(W,ee)=>{W.forEach((G,ue)=>{G.setAttribute("tabindex",ue===ee?"0":"-1")})},M=W=>{let ee=y();if(ee.length===0)return;let G=(W%ee.length+ee.length)%ee.length;u=G,x(ee,G),ee[G].focus(),h()},S=()=>n.ownerDocument??document,k=null,P=null,H=null,b=()=>{k&&(S().removeEventListener("focusin",k,!0),k=null)},w=()=>{P&&(a.removeEventListener("focusin",P),P=null),H&&(a.removeEventListener("pointerdown",H,!0),H=null)},C=null,L=()=>(C||(C=Zc({anchor:r,content:a,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),b()}})),C),N=()=>C?.isOpen===!0,X=(W=!1)=>{if(N()){C?.close(),r.setAttribute("aria-expanded","false"),b(),w(),u=-1,p=!1;for(let ee of c)ee.removeAttribute(eg);W&&r.focus()}},V=(W=0,ee=!1)=>{if(o||N())return;p=ee,Kc(r,a,m0),L().open(),r.setAttribute("aria-expanded","true");let G=y();x(G,-1),M(W<0?G.length-1:W),k=ue=>{let ae=typeof ue.composedPath=="function"?ue.composedPath():[];ae.includes(a)||ae.includes(n)||X()},S().addEventListener("focusin",k,!0),P=()=>h(),a.addEventListener("focusin",P),H=()=>{p=!1},a.addEventListener("pointerdown",H,!0)},T=W=>{W.preventDefault(),W.stopPropagation(),N()?X(!0):V(0)},O=W=>{if(W.key==="ArrowDown"||W.key==="Enter"||W.key===" "){W.preventDefault(),p=!0,N()?M(0):V(0,!0);return}W.key==="ArrowUp"&&(W.preventDefault(),p=!0,N()?M(-1):V(-1,!0))},D=W=>{switch(g0.has(W.key)&&(p=!0),W.key){case"ArrowDown":W.preventDefault(),M(u+1);return;case"ArrowUp":W.preventDefault(),M(u-1);return;case"Home":W.preventDefault(),M(0);return;case"End":W.preventDefault(),M(y().length-1);return;case"Escape":W.preventDefault(),W.stopPropagation(),X(!0);return;case"Tab":X(!0);return;default:}};return r.addEventListener("click",T),r.addEventListener("keydown",O),a.addEventListener("keydown",D),{trigger:n,triggerButton:r,panel:a,setItems:W=>{for(let G of c)W.includes(G)||G.removeAttribute(eg);if(c=[...W],!N())return;let ee=y();x(ee,Math.min(u,ee.length-1)),h()},isOpen:N,open:()=>V(0),close:X,setLabel:W=>{W!==t&&(t=W,d())},applyButtonSize:i,destroy:()=>{o=!0,b(),w(),r.removeEventListener("click",T),r.removeEventListener("keydown",O),a.removeEventListener("keydown",D),C?.destroy(),C=null,n.remove(),a.remove(),c=[]}}}var Fn={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},sC="data-persona-composer-action",tg="data-persona-composer-disable-when-streaming",y0="core:overflow",b0=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function v0(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let o=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(o))return o;let n=R("div");n.style.position="absolute",n.style.visibility="hidden",n.style.pointerEvents="none",n.style.height="0",n.style.width=e,t.appendChild(n);let r=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(o)?o:null}function og(e){let t=e.clientWidth;if(!t)return 0;let o=e.ownerDocument?.defaultView;if(!o?.getComputedStyle)return t;let n=o.getComputedStyle(e),r=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-r)}var aC=(e,t)=>{!e||typeof console>"u"||console.warn(t)},x0=(e,t)=>t.includes(":")?t:`${e}:${t}`;function C0(e){let{debug:t}=e,o=[],n=new Map,r=0,a=d=>{let c=n.get(d.id);if(c){aC(t,`[Persona] composer action "${d.id}" is already contributed by ${iC(c)}; the ${iC(d)} copy is ignored.`);return}n.set(d.id,d),o.push(d)};for(let d of e.builtIns)a({id:d.id,placement:d.placement,presentation:"bar",order:d.order,sequence:r++,source:"core",builtIn:d});let i=(d,c,u)=>{let p=u?x0(u,d.id):d.id,m=d.order??Fn.custom;d.placement==="end"&&m>=Fn.send&&(aC(t,`[Persona] composer action "${p}" ordered at ${m} would render after send; clamped to ${Fn.send-1}.`),m=Fn.send-1),a({id:p,placement:d.placement,presentation:d.presentation??"bar",order:m,sequence:r++,source:c,pluginId:u,action:d})};for(let d of e.configActions??[])i(d,"config");for(let d of e.plugins){if(!d.contributeComposerActions)continue;let c;try{c=d.contributeComposerActions(e.contributionContext)}catch(u){typeof console<"u"&&console.error(`[Persona] plugin "${d.id}" contributeComposerActions failed:`,u);continue}for(let u of c??[])i(u,"plugin",d.id)}return o.sort((d,c)=>d.order===c.order?d.sequence-c.sequence:d.order-c.order)}var iC=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",lC=(e,t,o)=>e===void 0?o:typeof e=="function"?e(t)===!0:e===!0,S0=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function w0(e,t){if(!e||e==="always")return!0;let o=S0(t);return e==="when-text"?o:!o}var zr=e=>e.kind==="custom",ng=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,A0=e=>{let t=ng(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},M0='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function T0(e){let t="",o=n=>{if(n.nodeType===Node.TEXT_NODE){t+=n.nodeValue??"";return}if(n.nodeType!==Node.ELEMENT_NODE)return;let r=n;typeof r.matches=="function"&&r.matches(M0)||n.childNodes.forEach(o)};return o(e),t.trim()}var E0=e=>T0(e).length===0;function dC(e){let t=new Map,o=[],n=!1,r=()=>e.getButtonSize?.(),a=(T,O)=>{let D=T.button;if(!D)return;D.setAttribute("role","menuitem"),D.setAttribute("tabindex","-1"),D.className="persona-composer-overflow-menu__item";for(let G of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])D.style[G]="";D.style.lineHeight="1",O.tooltipText?D.setAttribute("title",O.tooltipText):D.removeAttribute("title"),D.replaceChildren();let W=R("span","persona-composer-overflow-menu__icon");if(O.iconName){let G=le(O.iconName,16,"currentColor",1.5);G&&W.appendChild(G)}let ee=R("span","persona-composer-overflow-menu__label");ee.textContent=O.shortLabel??O.label,D.append(W,ee)},i=(T,O)=>{let D=T.button;if(!D)return;if(D.setAttribute("aria-label",O.label),O.pressed===void 0?D.removeAttribute("aria-pressed"):D.setAttribute("aria-pressed",O.pressed?"true":"false"),D.toggleAttribute(tg,O.disableWhenStreaming===!0),T.mode==="menu"){T.tooltip?.destroy(),T.tooltip=void 0,a(T,O);return}D.removeAttribute("role"),D.removeAttribute("tabindex"),D.removeAttribute("title");let W=r(),ee=!!O.shortLabel;if(D.className=yo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Go,xn,ee&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),D.style.width=W&&!ee?W:"",D.style.height=W??"",D.style.minWidth=W&&!ee?W:"",D.style.minHeight=W??"",D.style.fontSize=ee?"":"18px",D.style.lineHeight="1",D.style.color=O.iconColor??"",D.style.backgroundColor=O.backgroundColor??"",D.replaceChildren(),O.iconName){let G=le(O.iconName,bo,"currentColor",1.5);G&&D.appendChild(G)}if(ee){let G=R("span","persona-composer-action-button__label");G.textContent=O.shortLabel,D.appendChild(G)}else D.firstChild||(D.textContent=O.label);T.tooltip?.destroy(),T.tooltip=Jt({anchor:D,trigger:T.element,text:()=>O.tooltipText??O.label,enabled:!!O.tooltipText})},d=(T,O)=>{let D=T.action,W=Q("button",{attrs:{type:"button"}}),ee=W;if(O==="bar"){let ae=R("div","persona-send-button-wrapper");ae.appendChild(W),ee=ae}ee.setAttribute(sC,T.id);let G={resolved:T,element:ee,button:W,owned:!0,managed:!0,busy:!1,visible:!0,mode:O},ue=ae=>{if(ae.preventDefault(),ae.stopPropagation(),G.busy||W.disabled)return;let ye=G.resolved.action;G.mode==="menu"&&y?.close(!0);let Re;try{Re=ye.onSelect(e.actionContext,ae)}catch(be){e.reportError(be,{actionId:G.resolved.id});return}!Re||typeof Re.then!="function"||(G.busy=!0,W.setAttribute("aria-busy","true"),Re.catch(be=>{e.reportError(be,{actionId:G.resolved.id})}).finally(()=>{G.busy=!1,W.removeAttribute("aria-busy")}))};return W.addEventListener("click",ue),G.detach=()=>W.removeEventListener("click",ue),i(G,D),G},c=T=>{let O=T.action,D;try{D=O.render({...e.actionContext,id:T.id,action:O})}catch(W){return e.reportError(W,{actionId:T.id}),null}return D?.element?(D.element.setAttribute(sC,T.id),D.element.toggleAttribute(tg,O.disableWhenStreaming===!0),{resolved:T,element:D.element,owned:!0,managed:!0,destroy:D.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(T,O)=>{if(T.builtIn){let W=T.builtIn.element;return W?{resolved:T,element:W,owned:!1,managed:T.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let D=T.action;return D?zr(D)?c(T):d(T,O):null},p=T=>{if(T.detach?.(),T.tooltip?.destroy(),T.detachMenuSlot?.(),T.detachMenuSlot=void 0,T.menuLabel?.remove(),T.menuLabel=void 0,T.menuSlot?.remove(),T.menuSlot=void 0,T.owned){try{T.destroy?.()}catch(O){e.reportError(O,{actionId:T.resolved.id})}T.element.remove()}},m=(T,O)=>{for(let D=0;D<O.length;D++){let W=O[D];if(!W.managed)continue;let ee=null;for(let G=D+1;G<O.length;G++){let ue=O[G];if(!ue.managed&&ue.element.parentElement===T){ee=ue.element;break}}ee?(W.element.parentElement!==T||W.element.nextSibling!==ee)&&T.insertBefore(W.element,ee):T.lastChild!==W.element&&T.appendChild(W.element)}},h=(T,O)=>{if(T.button){T.button.disabled=O;return}if(!T.owned)return;let D=T.element;D.toggleAttribute("data-disabled",O),D.setAttribute("aria-disabled",O?"true":"false");let W=D instanceof HTMLButtonElement||D instanceof HTMLSelectElement||D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement?D:D.querySelector("button, select, input, textarea");W&&(W.disabled=O)},y=null,x=null,M=null,S=0,k=()=>{let T=e.getOverflow?.();return T?.enabled===!0?T:void 0},P=()=>(y?y.setLabel(e.getOverflowLabel?.()??"More actions"):y=rC({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),y),H=T=>{x!==T&&(M?.disconnect(),x=T,S=og(T),!(typeof ResizeObserver>"u")&&(M=new ResizeObserver(O=>{let W=O[O.length-1]?.contentRect?.width??og(T);W!==S&&(S=W,X())}),M.observe(T)))},b=(T,O)=>{let D=v0(T.collapseAutoActionsBelow,O);if(D===null)return!1;let W=S||og(O);return W>0&&W<D},w=(T,O,D)=>{if(!O)return"bar";if(T.resolved.builtIn){let ee=b0(T.resolved.id);return ee&&O.includeBuiltIns?.includes(ee)?"menu":"bar"}let W=T.resolved.presentation;return W==="overflow"||W==="auto"&&D?"menu":"bar"},C=T=>{let O=T.menuSlot;if(!O)return;if(!E0(T.element)){T.menuLabel?.remove(),T.menuLabel=void 0;return}let D=A0(T.element);if(!D){T.menuLabel?.remove(),T.menuLabel=void 0;return}T.menuLabel||(T.menuLabel=R("span","persona-composer-overflow-menu__label")),T.menuLabel.textContent!==D&&(T.menuLabel.textContent=D),T.menuLabel.parentElement!==O&&O.appendChild(T.menuLabel)},L=(T,O)=>{if(T.mode===O)return T;let D=T.resolved.action;if(D&&!zr(D)){p(T),t.delete(T.resolved.id);let W=d(T.resolved,O);return t.set(T.resolved.id,W),W}if(O==="menu"){let W=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Km]:""}});W.appendChild(T.element),Qx(ng(T.element)),T.menuSlot=W;let ee=G=>{let ue=ng(T.element);if(ue.disabled)return;let ae=G.target===ue||ue.contains(G.target);y?.close(!0),ae||ue.click()};W.addEventListener("click",ee,!0),T.detachMenuSlot=()=>W.removeEventListener("click",ee,!0),T.managed=!0,C(T)}else T.detachMenuSlot?.(),T.detachMenuSlot=void 0,T.menuLabel?.remove(),T.menuLabel=void 0,T.menuSlot?.remove(),T.menuSlot=void 0;return T.mode=O,T},N=(T,O)=>{let D=O.map(W=>W.menuSlot??W.element);for(D.forEach((W,ee)=>{let G=T.children[ee];G!==W&&(G?T.insertBefore(W,G):T.appendChild(W))});T.children.length>D.length;)T.lastElementChild?.remove()},X=()=>{if(n)return;let T=e.getBindings();if(!T)return;let O=e.getState(),D=O.phase==="streaming",W=k();W&&H(T.footer);let ee=W?b(W,T.footer):!1,G={start:[],end:[]},ue=[];for(let ae of o){let ye=t.get(ae.id);if(!ye)continue;let Re=ae.action,be=Re?lC(Re.visible,O,!0)&&w0(Re.visibility,O):!0;if(ye.visible!==be&&(ye.visible=be,!be&&ye.managed&&(ye.menuSlot??ye.element).remove()),!!be){if(ye=L(ye,w(ye,W,ee)),Re){let pe=lC(Re.disabled,O,!1)||Re.disableWhenStreaming===!0&&D;h(ye,pe),!zr(Re)&&Re.pressed!==void 0&&ye.button?.setAttribute("aria-pressed",Re.pressed?"true":"false")}ye.mode==="menu"?(C(ye),ue.push(ye)):G[ae.placement].push(ye)}}if(ue.length>0){let ae=P();N(ae.panel,ue),ae.setItems(ue.map(pe=>pe.menuSlot??pe.element)),ae.applyButtonSize();let ye=Number.isFinite(W?.order)?W?.order:Fn.overflow,Re=G.start.findIndex(pe=>pe.resolved.order>ye),be={resolved:{id:y0,placement:"start",presentation:"bar",order:ye,sequence:-1,source:"core"},element:ae.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};G.start.splice(Re<0?G.start.length:Re,0,be)}else y&&(y.close(),y.trigger.remove(),y.setItems([]));m(T.actionsStart,G.start),m(T.actionsEnd,G.end)};return{resolve:()=>{if(n)return;let T=C0(e.collect()),O=new Set(T.map(D=>D.id));for(let[D,W]of t)O.has(D)||(p(W),t.delete(D));for(let D of T){let W=t.get(D.id);if(!W){let ae=u(D,"bar");ae&&t.set(D.id,ae);continue}let ee=W.resolved.action,G=D.action;if(!!ee!=!!G||ee&&G&&zr(ee)!==zr(G)||ee&&G&&zr(ee)&&zr(G)&&ee.render!==G.render){p(W),t.delete(D.id);let ae=u(D,W.mode);ae&&t.set(D.id,ae);continue}W.resolved=D,D.builtIn?(W.managed=D.builtIn.managed===!0||W.mode==="menu",D.builtIn.element&&W.mode==="bar"&&(W.element=D.builtIn.element)):G&&!zr(G)?i(W,G):G&&W.element.toggleAttribute(tg,G.disableWhenStreaming===!0)}o=T,X()},sync:X,getResolved:()=>o,getOverflowMenu:()=>y,destroy:()=>{if(!n){n=!0,M?.disconnect(),M=null,x=null;for(let T of t.values())p(T);t.clear(),y?.destroy(),y=null,o=[]}}}}var P0="core:model",k0=700,cC=16,L0=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],uC=()=>{let e=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function pC(e){let t=e.label??"Model",o=e.presentation??"native",n=null,r=c=>{let u=e.getSelectedModelId();return c.find(p=>p.id===u)??c[0]},a=()=>{let c=Q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),u="",p=()=>{let M=e.getModels(),S=M.map(k=>`${k.id}:${k.label}`).join("|");S!==u&&(u=S,c.replaceChildren(...M.map(k=>{let P=Q("option",{attrs:{value:k.id}});return P.textContent=k.label,P}))),c.value=r(M)?.id??""};p(),n=p;let m=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",m);let h=M=>M.stopPropagation();c.addEventListener("click",h);let{wrapper:y,chevron:x}=uC();return y.append(c,x),{element:y,destroy:()=>{n===p&&(n=null),c.removeEventListener("change",m),c.removeEventListener("click",h)}}},i=()=>{let c=Q("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),u=R("span","persona-composer-model-picker-label"),p=R("span","persona-composer-model-picker-suffix");c.append(u,p);let m=Q("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),h=new Map,y="",x=null,M=()=>x?.isOpen===!0,S=(O=!1)=>{M()&&(x?.close(),c.setAttribute("aria-expanded","false"),O&&c.focus())},k=O=>{let D=[...h.values()];if(D.length===0)return;let W=(O%D.length+D.length)%D.length;D[W].focus()},P=O=>{if(M())return;x||(x=Zc({anchor:c,content:m,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Kc(c,m,L0),x.open(),c.setAttribute("aria-expanded","true");let W=[...h.keys()].indexOf(r(e.getModels())?.id??"");k(O??(W>=0?W:0))},H=O=>{S(!0),e.onSelect(O)},b=O=>{O.preventDefault(),O.stopPropagation();let D=O.currentTarget.getAttribute("data-persona-model-option");D&&H(D)},w=O=>{let D=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":O.id}});if(O.icon){let ae=le(O.icon,cC,"currentColor",1.5);if(ae){let ye=R("span","persona-composer-model-option-icon");ye.appendChild(ae),D.appendChild(ye)}}let W=R("span","persona-composer-model-option-body"),ee=R("span","persona-composer-model-option-label");if(ee.textContent=O.label,W.appendChild(ee),O.description){let ae=R("span","persona-composer-model-option-description");ae.textContent=O.description,W.appendChild(ae)}D.appendChild(W);let G=R("span","persona-composer-model-option-check");G.setAttribute("aria-hidden","true");let ue=le("check",cC,"currentColor",2);return ue&&G.appendChild(ue),D.appendChild(G),D.addEventListener("click",b),D},C=()=>{let O=e.getModels(),D=O.map(G=>`${G.id}:${G.label}:${G.icon??""}:${G.description??""}`).join("|");if(D!==y){y=D;for(let G of h.values())G.removeEventListener("click",b);h.clear(),m.replaceChildren(...O.map(G=>{let ue=w(G);return h.set(G.id,ue),ue}))}let W=r(O);for(let[G,ue]of h)ue.setAttribute("aria-selected",String(G===W?.id));u.textContent=W?.label??"";let ee=e.getSuffix?.()??"";p.textContent=ee,c.setAttribute("aria-label",[t,[W?.label,ee].filter(Boolean).join(" ")].filter(Boolean).join(": "))};C(),n=C;let L=O=>{O.preventDefault(),O.stopPropagation(),M()?S(!0):P()},N=O=>{if(O.key==="ArrowDown"){O.preventDefault(),M()?k(0):P(0);return}O.key==="ArrowUp"&&(O.preventDefault(),M()?k(-1):P(-1))},X=O=>{let D=[...h.values()],W=D.indexOf(O.target?.closest?.(".persona-composer-model-option"));switch(O.key){case"ArrowDown":O.preventDefault(),k(W+1);return;case"ArrowUp":O.preventDefault(),k(W-1);return;case"Home":O.preventDefault(),k(0);return;case"End":O.preventDefault(),k(D.length-1);return;case"Escape":O.preventDefault(),O.stopPropagation(),S(!0);return;case"Tab":S(!0);return;default:}};c.addEventListener("click",L),c.addEventListener("keydown",N),m.addEventListener("keydown",X);let{wrapper:V,chevron:T}=uC();return V.append(c,T),{element:V,destroy:()=>{n===C&&(n=null),c.removeEventListener("click",L),c.removeEventListener("keydown",N),m.removeEventListener("keydown",X);for(let O of h.values())O.removeEventListener("click",b);h.clear(),x?.destroy(),x=null,m.remove()}}};return{action:{id:P0,kind:"custom",placement:"end",order:k0,presentation:o==="popover"?"bar":"auto",label:t,render:()=>o==="popover"?i():a()},repaint:()=>n?.()}}var rg="[data-persona-composer-chip-row]";function eu(e){e.style.display=e.childElementCount>0?"flex":"none"}function sg(e){let t=e.querySelector(rg);if(t)return t;let o=Q("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});o.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(o,n):e.appendChild(o),o}var I0=":scope > [data-persona-composer-mode]";function fC(e){let t=e.row,o="",n=!1,r=new Set(e.initialIds??[]),a=u=>{let p=Q("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let x=R("span","persona-mention-chip-icon"),M=le(u.iconName,12,"currentColor",1.5);M&&x.appendChild(M),p.appendChild(x)}let m=R("span","persona-mention-chip-label");m.textContent=u.shortLabel??u.label,p.appendChild(m);let h=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),y=le("x",12,"currentColor",2);return y?h.appendChild(y):h.textContent="\xD7",h.addEventListener("click",x=>{x.preventDefault(),x.stopPropagation(),e.onRemove(u.id)}),p.appendChild(h),p},i=()=>Array.from(t.querySelectorAll(I0)),d=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let p=()=>{u.remove(),eu(t)},m=t.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(u).animationName:"";if(!h||h==="none"){p();return}u.addEventListener("animationend",p,{once:!0}),u.addEventListener("animationcancel",p,{once:!0})},c=()=>{for(let u of i())u.remove()};return{element:t,render:(u,p)=>{if(n)return;let m=p.filter(M=>u.includes(M.id)),h=m.map(M=>`${M.id}:${M.shortLabel??M.label}`).join("|");if(h===o)return;o=h;let y=new Map;for(let M of i()){let S=M.getAttribute("data-persona-composer-mode");S&&m.some(P=>P.id===S)&&!M.hasAttribute("data-persona-chip-exit")?y.set(S,M):M.hasAttribute("data-persona-chip-exit")||d(M)}let x=t.firstChild;for(let M of m){let S=y.get(M.id);S||(S=a(M),r.has(M.id)||(S.setAttribute("data-persona-chip-enter",""),S.addEventListener("animationend",()=>S?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(M.id),S!==x&&t.insertBefore(S,x),x=S.nextSibling}eu(t)},destroy:()=>{n=!0,c(),eu(t)}}}var mC=e=>`core:mode:${e}`;var ag=e=>Math.min(300+e,499),gC=e=>`core:mode-group:${e}`;function tu(e,t){return e?t?.find(o=>o.id===e)?.presentation==="segmented":!1}function R0(e,t){return e?t?.find(o=>o.id===e)?.chipVisibility==="hidden":!1}function hC(e,t){return e?.length?e.filter(o=>!tu(o.groupId,t)&&!R0(o.groupId,t)):[]}var H0=(e,t)=>e.groupId?t?.find(o=>o.id===e.groupId)?.selection??null:null;function yC(e,t,o,n){let r=o.find(d=>d.id===t);if(!r)return[...e];let a=e.includes(t),i=new Set(e);if(a)i.delete(t);else{if(H0(r,n)==="single"){let d=o.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!d.includes(c)))}i.add(t)}return o.filter(d=>i.has(d.id)).map(d=>d.id)}function ou(e,t){return t?.length?t.filter(o=>e.includes(o.id)).map(o=>o.id):[]}function bC(e,t){return t?.length?t.filter(o=>e.includes(o.id)&&(o.persistence??"sticky")!=="once").map(o=>o.id):[]}function vC(e,t){if(!(!t?.length||e.length===0))return t.find(o=>e.includes(o.id)&&o.placeholder)?.placeholder}var W0=16;function xC(e){let t=null;return{action:{id:gC(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let n=Q("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,a="",i=u=>{u.preventDefault(),u.stopPropagation();let m=u.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},d=u=>{let p=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let h=le(u.iconName,W0,"currentColor",1.5);h&&p.appendChild(h)}let m=R("span","persona-composer-segmented-label");return m.textContent=u.shortLabel??u.label,p.appendChild(m),p.addEventListener("click",i),p},c=()=>{let u=e.getGroup();u?.label?(n.setAttribute("role","group"),n.setAttribute("aria-label",u.label)):(n.removeAttribute("role"),n.removeAttribute("aria-label"));let p=e.getModes(),m=p.map(y=>`${y.id}:${y.shortLabel??y.label}:${y.iconName??""}`).join("|");if(m!==a){a=m;for(let x of r.values())x.removeEventListener("click",i);r.clear();let y=p.map(x=>{let M=d(x);return r.set(x.id,M),M});n.replaceChildren(...y)}let h=e.getActiveIds();for(let[y,x]of r)x.setAttribute("aria-pressed",String(h.includes(y)))};return c(),t=c,{element:n,destroy:()=>{t===c&&(t=null);for(let u of r.values())u.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}function CC(e){let t=Q("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let o="",n=!1,r=a=>{let i=R("span","persona-composer-quote-bar"),d=R("div","persona-composer-quote-content");if(a.sourceLabel){let m=R("div","persona-composer-quote-source");m.textContent=a.sourceLabel,d.appendChild(m)}let c=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Lc(a.text),d.appendChild(c);let u=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=le("x",12,"currentColor",2);p?u.appendChild(p):u.textContent="\xD7",u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,d,u)};return{element:t,render:a=>{if(n)return;let i=a?`${a.sourceLabel??""}\0${a.text}`:"";if(i!==o){if(o=i,!a){t.replaceChildren(),t.style.display="none";return}r(a),t.style.display="flex"}},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function SC(e){let t=Q("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let o,n=!1,r=(i,d,c,u)=>{let p=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":d,[c]:""}}),m=le(i,12,"currentColor",2);return m?p.appendChild(m):p.textContent=d,p.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),u()}),p},a=i=>{let d=Lc(i.text??"",90);if(d)return d;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(p=>p.label).join(", "):"Queued message"};return{element:t,render:i=>{if(n||i===o)return;if(o=i,!i){t.replaceChildren(),t.style.display="none";return}let d=R("span","persona-composer-pending-badge");d.textContent=e.label??"Sends next";let c=Q("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=a(i),t.replaceChildren(d,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function wC(e){let t=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),o=Q("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});o.value=e.initialText;let n=()=>{o.style.height="auto",o.style.height=`${o.scrollHeight}px`};o.addEventListener("input",n);let r=R("div","persona-message-edit-actions"),a=(d,c,u,p)=>{let m=Q("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[u]:""},text:d});return m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),m},i=()=>{let d=o.value.trim();d&&e.onSave(d)};return r.append(a(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),a(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),o.addEventListener("keydown",d=>{if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),e.onCancel();return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),i())}),t.append(o,r),{element:t,getValue:()=>o.value,focus:()=>{o.focus();let d=o.value.length;o.setSelectionRange(d,d),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}function AC(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function MC(e,t){if(!e||typeof e.text!="string")return;let o=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(c=>o.has(c.sourceId)),r=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>a.has(c)),d=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:n}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...d?{selectedModelId:d}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function TC(e){let t=e.delay??500,o=null,n=!1,r=()=>{o!==null&&(clearTimeout(o),o=null)};return{schedule:()=>{n||(r(),o=setTimeout(()=>{o=null,e.write()},t))},flush:()=>{n||o===null||(r(),e.write())},cancel:r,destroy:()=>{n=!0,r()}}}function EC(e){return e.wrapped||e.text.includes(`
|
|
24
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function
|
|
25
|
-
`:n===""||
|
|
26
|
-
`||i==="\uFFFC"||!r&&
|
|
27
|
-
`).some(L=>L.startsWith(
|
|
28
|
-
`)[0]).startsWith(w.trigger):!1),a=(b,w)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${b}`,{detail:w}))}catch{}},i=!e.chipRow,d=e.chipRow??Q("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),c=null,u=null,p=e.textarea,m=null,h=null,y=null,x=null,M=()=>{if(c)return Promise.resolve(c);if(u)return u;let b=lg().then(w=>(w.setMentionIconRenderer(le),c=w.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:H,emit:a}),c)).catch(w=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",w),u===b&&(u=null),null));return u=b,b},S=()=>{UC().then(b=>{let w=b.mountInlineComposer({textarea:e.textarea,renderToken:L=>Cl(L,{render:t.renderMentionToken}),onMentionRemoved:L=>c?.untrackMention(L)});m=w.input,h=w.destroy;let C=p;C.replaceWith(w.element),p=w.element,x={next:w.element,prev:C},y?.(w.element,C),c?c.rebindComposer(w.input):u&&u.then(L=>L?.rebindComposer(w.input))}).catch(b=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",b)})};t.display==="inline"&&S();let k=[],P=new Map;for(let b of o){if(!b.showButton)continue;let w=_C({config:{...t,buttonIconName:b.buttonIconName,buttonTooltipText:b.buttonTooltipText},onOpen:()=>{M().then(C=>C?.openMenu(b.trigger))}});k.push(w),P.set(b.trigger,w.button)}let H=(b,w,C)=>{let L=P.get(w);L&&(L.setAttribute("aria-expanded",b?"true":"false"),b?L.setAttribute("aria-controls",C):L.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(b=>b.wrapper),contextRow:d,handleInput:b=>{if(c){c.handleInput();return}if(!OC(b))return;let w=p,C=w.selectionStart??0;BC(w.value,C,o)&&M().then(L=>L?.handleInput())},handleKeydown:b=>{if(c?.isMenuOpen())return c.handleKeydown(b);if(b.key==="Backspace"&&c?.hasMentions()&&!x){let w=p,C=w.selectionStart===0&&w.selectionEnd===0;if((w.value.length===0||C)&&c.removeLastChip())return b.preventDefault(),!0}return!1},isMenuOpen:()=>c?.isMenuOpen()??!1,hasMentions:()=>c?.hasMentions()??!1,getMentionRefs:()=>c?.getMentionRefs()??[],collectForSubmit:()=>c?.collectForSubmit()??null,takeInlineCommand:async b=>r(b)?(c??await M())?.dispatchInlineCommand(b)??null:null,clear:()=>c?.clear(),prefetch:()=>{lg().catch(()=>{})},onComposerSwap:b=>{y=b,x&&b(x.next,x.prev)},destroy:()=>{c?.destroy(),h?.();for(let b of k)b.wrapper.remove();i&&d.remove()}}}var nu="16px",ru="transparent",q0=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),cg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:q0,typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},ug={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},pg={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Ko,maxWidth:Vc,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:nu,canvasBackground:ru},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function vo(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let o=t.split("."),n=e;for(let r of o){if(n==null)return;n=n[r]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?vo(e,n):n}function su(e){let t={};function o(n,r){for(let[a,i]of Object.entries(n)){let d=`${r}.${a}`;if(typeof i=="string"){let c=vo(e,i);c!==void 0&&(t[d]={path:d,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&o(i,d)}}return o(e.palette,"palette"),o(e.semantic,"semantic"),o(e.components,"components"),t}function fg(e){let t=[],o=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||o.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||o.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:o}}function $C(e,t){let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?o[n]=$C(a,r):o[n]=r}return o}function V0(e,t){return t?$C(e,t):e}function Sl(e,t={}){let o={palette:cg,semantic:ug,components:pg},n={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:V0(o.components,e?.components)};if(t.validate!==!1){let r=fg(n);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)n=r.transform(n);return n}var dg=e=>e.trim()==="0"?"0px":e,VC="--persona-",$0=e=>{if(!e)return;let t=e.trim().toLowerCase(),o;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?o=[0,1,2].map(d=>parseInt(i[d]+i[d],16)):(i.length===6||i.length===8)&&(o=[0,2,4].map(d=>parseInt(i.slice(d,d+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let d=i[1].split(/[,/\s]+/).filter(Boolean);d.length>=3&&(o=d.slice(0,3).map(c=>{let u=c.endsWith("%"),p=parseFloat(u?c.slice(0,-1):c);return u?p/100*255:p}))}}if(!o||o.some(i=>!Number.isFinite(i)))return;let[n,r,a]=o.map(i=>{let d=Math.max(0,Math.min(255,i))/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)});return .2126*n+.7152*r+.0722*a},j0=.179,Zt=(e,t)=>{for(let[o,...n]of t){let r;for(let a of n)if(r=a.charCodeAt(0)===61?a.slice(1):e[VC+a],r!==void 0)break;r!==void 0&&(e[VC+o]=r)}};function au(e){let t=su(e),o={};for(let[q,Ue]of Object.entries(t)){let Je=q.replace(/\./g,"-");o[`--persona-${Je}`]=Ue.value}Zt(o,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let n=o["--persona-components-launcher-foreground"];o["--persona-launcher-fg-muted"]=n&&n!==o["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:o["--persona-muted"],Zt(o,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),Zt(o,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),o["--persona-panel-border"]=o["--persona-components-panel-border"]??`1px solid ${o["--persona-border"]}`,Zt(o,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),o["--persona-panel-inset"]=o["--persona-components-panel-inset"]??nu,o["--persona-panel-canvas-bg"]=o["--persona-components-panel-canvasBackground"]??ru,Zt(o,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),Zt(o,[["header-bg","components-header-background","surface"]]);let r=o["--persona-header-bg"],a=o["--persona-components-header-foreground"],i=a?`color-mix(in srgb, ${a} 72%, ${r})`:void 0;o["--persona-header-border"]=o["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${r})`:void 0)??o["--persona-divider"],Zt(o,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),o["--persona-header-title-fg"]=o["--persona-components-header-title-color"]??o["--persona-components-header-titleForeground"]??a??o["--persona-primary"],o["--persona-header-subtitle-fg"]=o["--persona-components-header-subtitle-color"]??o["--persona-components-header-subtitleForeground"]??i??o["--persona-text-muted"],o["--persona-header-action-icon-fg"]=o["--persona-components-header-actionIconForeground"]??i??o["--persona-muted"],Zt(o,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let d=e.components?.header;d?.shadow&&(o["--persona-header-shadow"]=d.shadow),d?.borderBottom&&(o["--persona-header-border-bottom"]=d.borderBottom),d?.minHeight&&(o["--persona-header-min-height"]=d.minHeight);let c=o["--persona-components-history-railHeader-background"];c&&(o["--persona-history-rail-header-bg"]=c);let u=o["--persona-components-history-railHeader-border"];u&&(o["--persona-history-rail-header-border"]=u);let p=o["--persona-components-history-railHeader-minHeight"];p&&(o["--persona-history-rail-header-min-height"]=p);for(let[q,Ue]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Je=o[`--persona-components-history-overlay-${q}`];Je&&(o[`--persona-history-overlay-${Ue}`]=Je)}for(let[q,Ue]of[["background","bg"],["borderRadius","radius"]]){let Je=o[`--persona-components-history-menu-${q}`];Je&&(o[`--persona-history-menu-${Ue}`]=Je)}let m=e.components?.history?.motion;if(m){let q=so=>{if(so===void 0)return;let Le=String(so).trim();return/^\d+(\.\d+)?$/.test(Le)?`${Le}ms`:Le},Ue=q(m.enterDurationMs);Ue!==void 0&&(o["--persona-history-enter-ms"]=Ue);let Je=q(m.exitDurationMs);Je!==void 0&&(o["--persona-history-exit-ms"]=Je),m.enterEasing&&(o["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(o["--persona-history-exit-easing"]=m.exitEasing)}let h=o["--persona-components-history-dangerForeground"];h&&(o["--persona-history-danger-fg"]=h),o["--persona-danger"]=o["--persona-components-history-confirm-dangerBackground"]??o["--persona-palette-colors-error-700"]??"#b42318",o["--persona-danger-fg"]=o["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let q of["scrim","shadow"]){let Ue=o[`--persona-components-history-confirm-${q}`];Ue&&(o[`--persona-history-confirm-${q}`]=Ue)}for(let[q,Ue]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Je=o[`--persona-components-tooltip-${q}`];Je&&(o[`--persona-tooltip-${Ue}`]=Je)}e.components?.tooltip?.arrow===!1&&(o["--persona-tooltip-arrow-display"]="none");for(let[q,Ue]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Je=o[`--persona-components-messageActions-${q}`];Je&&(o[`--persona-message-action-${Ue}`]=Je)}Zt(o,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let y=o["--persona-components-introCard-background"],x=o["--persona-components-introCard-shadow"],M=(!y||y==="transparent"||y==="none")&&(!x||x==="none"),S=o["--persona-components-introCard-padding"]??"1.5rem";o["--persona-intro-card-padding"]=M&&S==="1.5rem"?"1.5rem 0":S,Zt(o,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),Zt(o,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let k=o["--persona-components-markdown-heading-h1-fontSize"];k&&(o["--persona-md-h1-size"]=k);let P=o["--persona-components-markdown-heading-h1-fontWeight"];P&&(o["--persona-md-h1-weight"]=P);let H=o["--persona-components-markdown-heading-h2-fontSize"];H&&(o["--persona-md-h2-size"]=H);let b=o["--persona-components-markdown-heading-h2-fontWeight"];b&&(o["--persona-md-h2-weight"]=b);let w=o["--persona-components-markdown-prose-fontFamily"];w&&w!=="inherit"&&(o["--persona-md-prose-font-family"]=w),Zt(o,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),Zt(o,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Zt(o,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Zt(o,[["md-hr-color","components-markdown-hr-color","divider"]]),Zt(o,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]),o["--cw-container"]=o["--persona-components-collapsibleWidget-container"]??o["--persona-surface"],o["--cw-surface"]=o["--persona-components-collapsibleWidget-surface"]??o["--persona-surface"],o["--cw-border"]=o["--persona-components-collapsibleWidget-border"]??o["--persona-border"],Zt(o,[["message-border","components-message-border","border"]]),Zt(o,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let C=e.components,L=C?.iconButton;L&&(L.background&&(o["--persona-icon-btn-bg"]=L.background),L.border&&(o["--persona-icon-btn-border"]=L.border),L.color&&(o["--persona-icon-btn-color"]=L.color),L.padding&&(o["--persona-icon-btn-padding"]=L.padding),L.borderRadius&&(o["--persona-icon-btn-radius"]=L.borderRadius),L.hoverBackground&&(o["--persona-icon-btn-hover-bg"]=L.hoverBackground),L.hoverColor&&(o["--persona-icon-btn-hover-color"]=L.hoverColor),L.activeBackground&&(o["--persona-icon-btn-active-bg"]=L.activeBackground),L.activeBorder&&(o["--persona-icon-btn-active-border"]=L.activeBorder));let N=C?.labelButton;N&&(N.background&&(o["--persona-label-btn-bg"]=N.background),N.border&&(o["--persona-label-btn-border"]=N.border),N.color&&(o["--persona-label-btn-color"]=N.color),N.padding&&(o["--persona-label-btn-padding"]=N.padding),N.borderRadius&&(o["--persona-label-btn-radius"]=N.borderRadius),N.hoverBackground&&(o["--persona-label-btn-hover-bg"]=N.hoverBackground),N.fontSize&&(o["--persona-label-btn-font-size"]=N.fontSize),N.gap&&(o["--persona-label-btn-gap"]=N.gap));let X=C?.toggleGroup;X&&(X.gap&&(o["--persona-toggle-group-gap"]=X.gap),X.borderRadius&&(o["--persona-toggle-group-radius"]=X.borderRadius));let V=C?.artifact;if(V?.toolbar){let q=V.toolbar;q.iconHoverColor&&(o["--persona-artifact-toolbar-icon-hover-color"]=q.iconHoverColor),q.iconHoverBackground&&(o["--persona-artifact-toolbar-icon-hover-bg"]=q.iconHoverBackground),q.iconPadding&&(o["--persona-artifact-toolbar-icon-padding"]=q.iconPadding),q.iconBorderRadius&&(o["--persona-artifact-toolbar-icon-radius"]=q.iconBorderRadius),q.iconBorder&&(o["--persona-artifact-toolbar-icon-border"]=q.iconBorder),q.toggleGroupGap&&(o["--persona-artifact-toolbar-toggle-group-gap"]=dg(q.toggleGroupGap)),q.toggleBorderRadius&&(o["--persona-artifact-toolbar-toggle-radius"]=q.toggleBorderRadius),q.toggleGroupPadding&&(o["--persona-artifact-toolbar-toggle-group-padding"]=dg(q.toggleGroupPadding)),q.toggleGroupBorder&&(o["--persona-artifact-toolbar-toggle-group-border"]=q.toggleGroupBorder),q.toggleGroupBorderRadius&&(o["--persona-artifact-toolbar-toggle-group-radius"]=q.toggleGroupBorderRadius),q.toggleGroupBackground&&(o["--persona-artifact-toolbar-toggle-group-bg"]=vo(e,q.toggleGroupBackground)??q.toggleGroupBackground),q.copyBackground&&(o["--persona-artifact-toolbar-copy-bg"]=q.copyBackground),q.copyBorder&&(o["--persona-artifact-toolbar-copy-border"]=q.copyBorder),q.copyColor&&(o["--persona-artifact-toolbar-copy-color"]=q.copyColor),q.copyBorderRadius&&(o["--persona-artifact-toolbar-copy-radius"]=dg(q.copyBorderRadius)),q.copyPadding&&(o["--persona-artifact-toolbar-copy-padding"]=q.copyPadding),q.copyMenuBackground&&(o["--persona-artifact-toolbar-copy-menu-bg"]=q.copyMenuBackground,o["--persona-dropdown-bg"]=o["--persona-dropdown-bg"]??q.copyMenuBackground),q.copyMenuBorder&&(o["--persona-artifact-toolbar-copy-menu-border"]=q.copyMenuBorder,o["--persona-dropdown-border"]=o["--persona-dropdown-border"]??q.copyMenuBorder),q.copyMenuShadow&&(o["--persona-artifact-toolbar-copy-menu-shadow"]=q.copyMenuShadow,o["--persona-dropdown-shadow"]=o["--persona-dropdown-shadow"]??q.copyMenuShadow),q.copyMenuBorderRadius&&(o["--persona-artifact-toolbar-copy-menu-radius"]=q.copyMenuBorderRadius,o["--persona-dropdown-radius"]=o["--persona-dropdown-radius"]??q.copyMenuBorderRadius),q.copyMenuItemHoverBackground&&(o["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=q.copyMenuItemHoverBackground,o["--persona-dropdown-item-hover-bg"]=o["--persona-dropdown-item-hover-bg"]??q.copyMenuItemHoverBackground),q.iconBackground&&(o["--persona-artifact-toolbar-icon-bg"]=q.iconBackground),q.toolbarBorder&&(o["--persona-artifact-toolbar-border"]=q.toolbarBorder)}if(V?.tab){let q=V.tab;q.background&&(o["--persona-artifact-tab-bg"]=q.background),q.activeBackground&&(o["--persona-artifact-tab-active-bg"]=q.activeBackground),q.activeBorder&&(o["--persona-artifact-tab-active-border"]=q.activeBorder),q.borderRadius&&(o["--persona-artifact-tab-radius"]=q.borderRadius),q.textColor&&(o["--persona-artifact-tab-color"]=q.textColor),q.hoverBackground&&(o["--persona-artifact-tab-hover-bg"]=q.hoverBackground),q.listBackground&&(o["--persona-artifact-tab-list-bg"]=q.listBackground),q.listBorderColor&&(o["--persona-artifact-tab-list-border-color"]=q.listBorderColor),q.listPadding&&(o["--persona-artifact-tab-list-padding"]=q.listPadding)}if(V?.pane){let q=V.pane;if(q.toolbarBackground){let Ue=vo(e,q.toolbarBackground)??q.toolbarBackground;o["--persona-artifact-toolbar-bg"]=Ue}}if(V?.card){let q=V.card;q.background&&(o["--persona-artifact-card-bg"]=q.background),q.border&&(o["--persona-artifact-card-border"]=q.border),q.borderRadius&&(o["--persona-artifact-card-radius"]=q.borderRadius),q.hoverBackground&&(o["--persona-artifact-card-hover-bg"]=q.hoverBackground),q.hoverBorderColor&&(o["--persona-artifact-card-hover-border"]=q.hoverBorderColor)}if(V?.inline){let q=V.inline;q.background&&(o["--persona-artifact-inline-bg"]=vo(e,q.background)??q.background),q.border&&(o["--persona-artifact-inline-border"]=q.border),q.borderRadius&&(o["--persona-artifact-inline-radius"]=q.borderRadius),q.chromeBackground&&(o["--persona-artifact-inline-chrome-bg"]=vo(e,q.chromeBackground)??q.chromeBackground),q.chromeBorder&&(o["--persona-artifact-inline-chrome-border"]=vo(e,q.chromeBorder)??q.chromeBorder),q.titleColor&&(o["--persona-artifact-inline-title-color"]=vo(e,q.titleColor)??q.titleColor),q.mutedColor&&(o["--persona-artifact-inline-muted-color"]=vo(e,q.mutedColor)??q.mutedColor),q.frameHeight&&(o["--persona-artifact-inline-frame-height"]=q.frameHeight)}let T=C?.code;T&&(T.keywordColor&&(o["--persona-code-keyword-color"]=T.keywordColor),T.stringColor&&(o["--persona-code-string-color"]=T.stringColor),T.commentColor&&(o["--persona-code-comment-color"]=T.commentColor),T.numberColor&&(o["--persona-code-number-color"]=T.numberColor),T.tagColor&&(o["--persona-code-tag-color"]=T.tagColor),T.attrColor&&(o["--persona-code-attr-color"]=T.attrColor),T.propertyColor&&(o["--persona-code-property-color"]=T.propertyColor),T.lineNumberColor&&(o["--persona-code-line-number-color"]=T.lineNumberColor),T.gutterBorderColor&&(o["--persona-code-gutter-border-color"]=T.gutterBorderColor),T.background&&(o["--persona-code-bg"]=vo(e,T.background)??T.background));let O=o["--persona-surface"],D=o["--persona-container"],W=o["--persona-palette-colors-gray-100"]??"#f3f4f6",ee=o["--persona-palette-colors-gray-200"]??"#e5e7eb",G=o["--persona-palette-colors-gray-300"]??"#d1d5db",ue=!D||D===O,ae=$0(O??o["--persona-background"]),ye=ue&&ae!==void 0&&ae<j0,Re=ye?"rgba(255, 255, 255, 0.08)":W,be=ye?"rgba(255, 255, 255, 0.12)":ee,pe=ye?"rgba(255, 255, 255, 0.16)":G,yt=ue?Re:D,Pe=ue?be:D;return o["--persona-icon-btn-hover-bg"]=o["--persona-icon-btn-hover-bg"]??yt,o["--persona-icon-btn-active-bg"]=o["--persona-icon-btn-active-bg"]??Pe,ue&&(o["--persona-icon-btn-active-border"]=o["--persona-icon-btn-active-border"]??pe),o["--persona-label-btn-hover-bg"]=o["--persona-label-btn-hover-bg"]??yt,o["--persona-artifact-tab-hover-bg"]=o["--persona-artifact-tab-hover-bg"]??yt,o["--persona-artifact-card-hover-bg"]=o["--persona-artifact-card-hover-bg"]??yt,o}var jC={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var z0={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},K0={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},zC=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},wl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",G0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":wl()},iu=e=>G0(e),X0=e=>Sl(e),Q0=e=>{let t=Va(K0,e??{})??{};return Sl({...t,palette:{...t.palette,colors:{...z0.colors,...t.palette?.colors}}},{validate:!1})},Kr=e=>{let t=iu(e),o=zC(e?.theme),n=zC(e?.darkTheme);return t==="dark"?Q0(Va(o??{},n??{})):X0(o)},Y0=e=>au(e),Ds=(e,t)=>{let o=Kr(t),n=Y0(o);for(let[r,a]of Object.entries(n))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",iu(t))},za=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let o=new MutationObserver(()=>{e(wl())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>o.disconnect())}if(typeof window<"u"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(wl());o.addEventListener?(o.addEventListener("change",n),t.push(()=>o.removeEventListener("change",n))):o.addListener&&(o.addListener(n),t.push(()=>o.removeListener(n)))}return()=>{t.forEach(o=>o())}};var Gr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var lu="24px",mg=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Al=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let o=Number(t[1])/100;return o>0&&o<1?o:null},KC=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var GC=null;var gg=()=>{if(GC!==null)return GC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},J0="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",du=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},cu=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),o=t.pop(),n={key:o,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")n.mod=!0;else if(r==="shift")n.shift=!0;else if(r==="alt"||r==="option")n.alt=!0;else return du("unknown modifier in",e),null;return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(o)||!/^([^+\s]|[a-z]{2,12})$/.test(o)?(du("unsupported",e),null):(o==="space"&&(n.key=" "),n)},Z0=e=>J0.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),XC=(e,t)=>{let o=cu(e);if(!o)return"";let n=gg(),r=Z0(o.key);if(!t&&n)return`${o.alt?"\u2325":""}${o.shift?"\u21E7":""}\u2318${r}`;let a=[t?n?"Meta":"Control":"Ctrl"];return o.alt&&a.push("Alt"),o.shift&&a.push("Shift"),a.push(r),a.join("+")},uu=e=>XC(e,!1),Ml=e=>XC(e,!0),eP=(e,t)=>t.key?.toLowerCase()===e.key&&(gg()?t.metaKey:t.ctrlKey)===e.mod&&!(gg()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,tP=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},QC=e=>{let t=new Map,o=e?.ownerDocument??(typeof document<"u"?document:null),n=(a,i)=>{if((a.scope??"widget")==="page")return!0;if(!e)return!1;let d=i.composedPath?.();return d?.length?d.includes(e):e.contains(i.target)},r=a=>{if(a.isComposing||!t.size)return;let i=a.composedPath?.()[0]??a.target;for(let d of t.values())if(eP(d.parsed,a)&&d.when?.()!==!1&&n(d,a)&&!(!d.allowInInput&&tP(i))){a.preventDefault();try{d.run(a)}catch(c){du(`${d.id} threw on`,d.combo),console.warn(c)}return}};return o?.addEventListener("keydown",r),{register(a){let i=cu(a.combo);if(!i)return()=>{};let d=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(d);return c?(du(`${c.id} already owns`,a.combo),()=>{}):(t.set(d,{...a,parsed:i}),a.element?.setAttribute("aria-keyshortcuts",Ml(a.combo)),()=>{t.get(d)?.id===a.id&&t.delete(d),a.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),o?.removeEventListener("keydown",r)}}};var YC=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:h=>h.getAttribute("im-preserve")==="true",shouldReAppend:h=>h.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function o(h,y,x={}){h=p(h);let M=m(y),S=u(h,M,x),k=r(S,()=>d(S,h,M,P=>P.morphStyle==="innerHTML"?(a(P,h,M),Array.from(h.childNodes)):n(P,h,M)));return S.pantry.remove(),k}function n(h,y,x){let M=m(y);return a(h,M,x,y,y.nextSibling),Array.from(M.childNodes)}function r(h,y){if(!h.config.restoreFocus)return y();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return y();let{id:M,selectionStart:S,selectionEnd:k}=x,P=y();return M&&M!==document.activeElement?.getAttribute("id")&&(x=h.target.querySelector(`[id="${M}"]`),x?.focus()),x&&!x.selectionEnd&&k&&x.setSelectionRange(S,k),P}let a=(function(){function h(b,w,C,L=null,N=null){w instanceof HTMLTemplateElement&&C instanceof HTMLTemplateElement&&(w=w.content,C=C.content),L||(L=w.firstChild);for(let X of C.childNodes){if(L&&L!=N){let T=x(b,X,L,N);if(T){T!==L&&S(b,L,T),i(T,X,b),L=T.nextSibling;continue}}if(X instanceof Element){let T=X.getAttribute("id");if(b.persistentIds.has(T)){let O=k(w,T,L,b);i(O,X,b),L=O.nextSibling;continue}}let V=y(w,X,L,b);V&&(L=V.nextSibling)}for(;L&&L!=N;){let X=L;L=L.nextSibling,M(b,X)}}function y(b,w,C,L){if(L.callbacks.beforeNodeAdded(w)===!1)return null;if(L.idMap.has(w)){let N=document.createElement(w.tagName);return b.insertBefore(N,C),i(N,w,L),L.callbacks.afterNodeAdded(N),N}else{let N=document.importNode(w,!0);return b.insertBefore(N,C),L.callbacks.afterNodeAdded(N),N}}let x=(function(){function b(L,N,X,V){let T=null,O=N.nextSibling,D=0,W=X;for(;W&&W!=V;){if(C(W,N)){if(w(L,W,N))return W;T===null&&(L.idMap.has(W)||(T=W))}if(T===null&&O&&C(W,O)&&(D++,O=O.nextSibling,D>=2&&(T=void 0)),L.activeElementAndParents.includes(W))break;W=W.nextSibling}return T||null}function w(L,N,X){let V=L.idMap.get(N),T=L.idMap.get(X);if(!T||!V)return!1;for(let O of V)if(T.has(O))return!0;return!1}function C(L,N){let X=L,V=N;return X.nodeType===V.nodeType&&X.tagName===V.tagName&&(!X.getAttribute?.("id")||X.getAttribute?.("id")===V.getAttribute?.("id"))}return b})();function M(b,w){if(b.idMap.has(w))H(b.pantry,w,null);else{if(b.callbacks.beforeNodeRemoved(w)===!1)return;w.parentNode?.removeChild(w),b.callbacks.afterNodeRemoved(w)}}function S(b,w,C){let L=w;for(;L&&L!==C;){let N=L;L=L.nextSibling,M(b,N)}return L}function k(b,w,C,L){let N=L.target.getAttribute?.("id")===w&&L.target||L.target.querySelector(`[id="${w}"]`)||L.pantry.querySelector(`[id="${w}"]`);return P(N,L),H(b,N,C),N}function P(b,w){let C=b.getAttribute("id");for(;b=b.parentNode;){let L=w.idMap.get(b);L&&(L.delete(C),L.size||w.idMap.delete(b))}}function H(b,w,C){if(b.moveBefore)try{b.moveBefore(w,C)}catch{b.insertBefore(w,C)}else b.insertBefore(w,C)}return h})(),i=(function(){function h(P,H,b){return b.ignoreActive&&P===document.activeElement?null:(b.callbacks.beforeNodeMorphed(P,H)===!1||(P instanceof HTMLHeadElement&&b.head.ignore||(P instanceof HTMLHeadElement&&b.head.style!=="morph"?c(P,H,b):(y(P,H,b),k(P,b)||a(b,P,H))),b.callbacks.afterNodeMorphed(P,H)),P)}function y(P,H,b){let w=H.nodeType;if(w===1){let C=P,L=H,N=C.attributes,X=L.attributes;for(let V of X)S(V.name,C,"update",b)||C.getAttribute(V.name)!==V.value&&C.setAttribute(V.name,V.value);for(let V=N.length-1;0<=V;V--){let T=N[V];if(T&&!L.hasAttribute(T.name)){if(S(T.name,C,"remove",b))continue;C.removeAttribute(T.name)}}k(C,b)||x(C,L,b)}(w===8||w===3)&&P.nodeValue!==H.nodeValue&&(P.nodeValue=H.nodeValue)}function x(P,H,b){if(P instanceof HTMLInputElement&&H instanceof HTMLInputElement&&H.type!=="file"){let w=H.value,C=P.value;M(P,H,"checked",b),M(P,H,"disabled",b),H.hasAttribute("value")?C!==w&&(S("value",P,"update",b)||(P.setAttribute("value",w),P.value=w)):S("value",P,"remove",b)||(P.value="",P.removeAttribute("value"))}else if(P instanceof HTMLOptionElement&&H instanceof HTMLOptionElement)M(P,H,"selected",b);else if(P instanceof HTMLTextAreaElement&&H instanceof HTMLTextAreaElement){let w=H.value,C=P.value;if(S("value",P,"update",b))return;w!==C&&(P.value=w),P.firstChild&&P.firstChild.nodeValue!==w&&(P.firstChild.nodeValue=w)}}function M(P,H,b,w){let C=H[b],L=P[b];if(C!==L){let N=S(b,P,"update",w);N||(P[b]=H[b]),C?N||P.setAttribute(b,""):S(b,P,"remove",w)||P.removeAttribute(b)}}function S(P,H,b,w){return P==="value"&&w.ignoreActiveValue&&H===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(P,H,b)===!1}function k(P,H){return!!H.ignoreActiveValue&&P===document.activeElement&&P!==document.body}return h})();function d(h,y,x,M){if(h.head.block){let S=y.querySelector("head"),k=x.querySelector("head");if(S&&k){let P=c(S,k,h);return Promise.all(P).then(()=>{let H=Object.assign(h,{head:{block:!1,ignore:!0}});return M(H)})}}return M(h)}function c(h,y,x){let M=[],S=[],k=[],P=[],H=new Map;for(let w of y.children)H.set(w.outerHTML,w);for(let w of h.children){let C=H.has(w.outerHTML),L=x.head.shouldReAppend(w),N=x.head.shouldPreserve(w);C||N?L?S.push(w):(H.delete(w.outerHTML),k.push(w)):x.head.style==="append"?L&&(S.push(w),P.push(w)):x.head.shouldRemove(w)!==!1&&S.push(w)}P.push(...H.values());let b=[];for(let w of P){let C=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(C)!==!1){if("href"in C&&C.href||"src"in C&&C.src){let L,N=new Promise(function(X){L=X});C.addEventListener("load",function(){L()}),b.push(N)}h.appendChild(C),x.callbacks.afterNodeAdded(C),M.push(C)}}for(let w of S)x.callbacks.beforeNodeRemoved(w)!==!1&&(h.removeChild(w),x.callbacks.afterNodeRemoved(w));return x.head.afterHeadMorphed(h,{added:M,kept:k,removed:S}),b}let u=(function(){function h(b,w,C){let{persistentIds:L,idMap:N}=P(b,w),X=y(C),V=X.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(V))throw`Do not understand how to morph style ${V}`;return{target:b,newContent:w,config:X,morphStyle:V,ignoreActive:X.ignoreActive,ignoreActiveValue:X.ignoreActiveValue,restoreFocus:X.restoreFocus,idMap:N,persistentIds:L,pantry:x(),activeElementAndParents:M(b),callbacks:X.callbacks,head:X.head}}function y(b){let w=Object.assign({},t);return Object.assign(w,b),w.callbacks=Object.assign({},t.callbacks,b.callbacks),w.head=Object.assign({},t.head,b.head),w}function x(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function M(b){let w=[],C=document.activeElement;if(C?.tagName!=="BODY"&&b.contains(C))for(;C&&(w.push(C),C!==b);)C=C.parentElement;return w}function S(b){let w=Array.from(b.querySelectorAll("[id]"));return b.getAttribute?.("id")&&w.push(b),w}function k(b,w,C,L){for(let N of L){let X=N.getAttribute("id");if(w.has(X)){let V=N;for(;V;){let T=b.get(V);if(T==null&&(T=new Set,b.set(V,T)),T.add(X),V===C)break;V=V.parentElement}}}}function P(b,w){let C=S(b),L=S(w),N=H(C,L),X=new Map;k(X,N,b,C);let V=w.__idiomorphRoot||w;return k(X,N,V,L),{persistentIds:N,idMap:X}}function H(b,w){let C=new Set,L=new Map;for(let{id:X,tagName:V}of b)L.has(X)?C.add(X):L.set(X,V);let N=new Set;for(let{id:X,tagName:V}of w)N.has(X)?C.add(X):L.get(X)===V&&N.add(X);for(let X of C)N.delete(X);return N}return h})(),{normalizeElement:p,normalizeParent:m}=(function(){let h=new WeakSet;function y(k){return k instanceof Document?k.documentElement:k}function x(k){if(k==null)return document.createElement("div");if(typeof k=="string")return x(S(k));if(h.has(k))return k;if(k instanceof Node){if(k.parentNode)return new M(k);{let P=document.createElement("div");return P.append(k),P}}else{let P=document.createElement("div");for(let H of[...k])P.append(H);return P}}class M{constructor(P){this.originalNode=P,this.realParentNode=P.parentNode,this.previousSibling=P.previousSibling,this.nextSibling=P.nextSibling}get childNodes(){let P=[],H=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;H&&H!=this.nextSibling;)P.push(H),H=H.nextSibling;return P}querySelectorAll(P){return this.childNodes.reduce((H,b)=>{if(b instanceof Element){b.matches(P)&&H.push(b);let w=b.querySelectorAll(P);for(let C=0;C<w.length;C++)H.push(w[C])}return H},[])}insertBefore(P,H){return this.realParentNode.insertBefore(P,H)}moveBefore(P,H){return this.realParentNode.moveBefore(P,H)}get __idiomorphRoot(){return this.originalNode}}function S(k){let P=new DOMParser,H=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(H.match(/<\/html>/)||H.match(/<\/head>/)||H.match(/<\/body>/)){let b=P.parseFromString(k,"text/html");if(H.match(/<\/html>/))return h.add(b),b;{let w=b.firstChild;return w&&h.add(w),w}}else{let w=P.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return h.add(w),w}}return{normalizeElement:y,normalizeParent:x}})();return{morph:o,defaults:t}})();var pu=(e,t,o={})=>{let{preserveTypingAnimation:n=!0}=o;YC.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&n){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let i=r.textContent??"",d=a.textContent??"";if(i!==d)return}return!1}}}}})};var JC=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var hg={index:-1,draft:""};function ZC(e){let{direction:t,history:o,currentValue:n,atStart:r,state:a}=e,i=a.index!==-1;if(o.length===0)return{handled:!1,state:a};if(t==="up"){if(!i&&!r)return{handled:!1,state:a};if(!i){let d=o.length-1;return{handled:!0,value:o[d],state:{index:d,draft:n}}}if(a.index>0){let d=a.index-1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,state:a}}if(!i)return{handled:!1,state:a};if(a.index<o.length-1){let d=a.index+1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function eS(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function tS(){return new Map}function oS(e,t,o){let n=e.get(t);return n&&n.fingerprint===o?n.wrapper:null}function nS(e,t,o,n){e.set(t,{fingerprint:o,wrapper:n})}function rS(e,t){for(let o of e.keys())t.has(o)||e.delete(o)}function sS(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function aS(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Un(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function _s(e,t){return Un(e)-e.scrollTop<=t}function iS(e){let{following:t,currentScrollTop:o,lastScrollTop:n,nearBottom:r,userScrollThreshold:a,isAutoScrolling:i=!1,pauseOnUpwardScroll:d=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:u=!1}=e,p=o-n;return i||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:o}:!t&&r&&(!u||p>0)?{action:"resume",delta:p,nextLastScrollTop:o}:t&&d&&p<0?{action:"pause",delta:p,nextLastScrollTop:o}:t&&c&&!r?{action:"pause",delta:p,nextLastScrollTop:o}:{action:"none",delta:p,nextLastScrollTop:o}}function lS(e){let{following:t,deltaY:o,nearBottom:n=!1,resumeWhenNearBottom:r=!1}=e;return t&&o<0?"pause":!t&&r&&o>0&&n?"resume":"none"}function dS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function yg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),o=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:o}}function cS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Tl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},oP=["pre","code","a","script","style"],fu=e=>({type:e?.type??Tl.type,placeholder:e?.placeholder??Tl.placeholder,speed:e?.speed??Tl.speed,duration:e?.duration??Tl.duration,buffer:e?.buffer??Tl.buffer}),pS=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],El=new Map;for(let e of pS)El.set(e.name,e);var fS=["wipe","glyph-cycle"],Ka=e=>{El.set(e.name,e)},xg=e=>{pS.some(t=>t.name===e)||El.delete(e)},Cg=()=>Array.from(El.keys()),Pl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:El.get(e)??null,mu=(e,t,o,n,r)=>{if(!r)return e;if(o?.bufferContent)return o.bufferContent(e,n);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
|
|
29
|
-
`);return a<0?"":e.slice(0,a)}return e},nP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${o}-${n}`,r.style.setProperty("--char-index",String(n)),r.textContent=t,r},rP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${o}-${n}`,r.style.setProperty("--word-index",String(n)),r.textContent=t,r},bg=/\s/,sP=(e,t)=>{let o=e.parentNode;for(;o;){if(o.nodeType===1){let n=o;if(t.has(n.tagName.toLowerCase()))return!0}o=o.parentNode}return!1},aP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=0;for(;d<a.length;)if(bg.test(a[d])){let c=d;for(;c<a.length&&bg.test(a[c]);)c+=1;i.appendChild(n.createTextNode(a.slice(d,c))),d=c}else{let c=n.createElement("span");c.className="persona-stream-word-group";let u=d;for(;u<a.length&&!bg.test(a[u]);)c.appendChild(nP(n,a[u],t,o.value)),o.value+=1,u+=1;i.appendChild(c),d=u}r.replaceChild(i,e)},iP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=a.split(/(\s+)/);for(let c of d)c&&(/^\s+$/.test(c)?i.appendChild(n.createTextNode(c)):(i.appendChild(rP(n,c,t,o.value)),o.value+=1));r.replaceChild(i,e)},kl=(e,t,o,n)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((n?.skipTags??oP).map(m=>m.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),d=[],c=i.nextNode();for(;c;)sP(c,a)||d.push(c),c=i.nextNode();let u={value:n?.startIndex??0},p=t==="char"?aP:iP;for(let m of d)p(m,o,u);return r.innerHTML},gu=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ll=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let o=e.createElement("div");return o.className="persona-stream-skeleton-line",t.appendChild(o),t},uS=new WeakMap,lP=(e,t)=>{if(!e.styles)return;let o=uS.get(t);if(o||(o=new Set,uS.set(t,o)),o.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;o.delete(e.name)}o.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},vg=new WeakMap,dP=(e,t)=>{if(!e.onAttach)return;let o=vg.get(t);if(o||(o=new Map,vg.set(t,o)),o.has(e.name))return;let n=e.onAttach(t);o.set(e.name,n)},mS=e=>{let t=vg.get(e);if(t){for(let o of t.values())typeof o=="function"&&o();t.clear()}},Il=(e,t)=>{lP(e,t),dP(e,t)};var{setLoader:cP,load:uP}=mt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),gS=cP,hS=uP;function Sg(e,t=ro){let o=e.style.position,n=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),i=a.position==="static"||a.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=o),e.style.zIndex=n,e.style.isolation=r}}var Rl=0,Xr=null;function wg(e=document){if(Rl++,Rl===1){let o=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Xr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:r},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${r}px`,o.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Rl=Math.max(0,Rl-1),Rl===0&&Xr)){let o=e.body,n=e.defaultView??window;o.style.overflow=Xr.originalOverflow,o.style.position=Xr.originalPosition,o.style.top=Xr.originalTop,o.style.width=Xr.originalWidth,n.scrollTo(0,Xr.scrollY),Xr=null}}}var Hl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ct=e=>(e?.launcher?.mountMode??"floating")==="docked",Qr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Do=e=>{let t=e?.launcher?.dock;return{side:t?.side??Hl.side,width:t?.width??Hl.width,animate:t?.animate??Hl.animate,reveal:t?.reveal??Hl.reveal,maxHeight:t?.maxHeight??Hl.maxHeight}};var Ag=e=>e==="followUp"?"follow-up":e,Mg=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let o=e.label.trim();if(!o)return null;let n=e.prompt?.trim()||o;return{id:e.id?.trim()||n||`suggestion-${t}`,label:o,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},pP=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},yS=new WeakSet,fP=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,mP=e=>{fP()||e.forEach((t,o)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:o*60,easing:"ease-out",fill:"backwards"})})},Tg=e=>{var H,b,w;let{item:t,index:o,surface:n,source:r,variant:a,streaming:i,config:d,plugins:c,chipsConfig:u,session:p,getTextarea:m,eventTarget:h,submitPrompt:y}=e,x=n==="followUp",M=t.behavior,S=()=>{if(p.isStreaming())return;let C={suggestion:{...t},surface:n,source:r,behavior:M},L=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:C,bubbles:!0,composed:!0,cancelable:!0}));if(x&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!L)return;for(let X of c)if(X.onSuggestionSelect?.({suggestion:{...t},surface:n,source:r,variant:a,config:d})===!1)return;let N=m();if(M==="fill"){N.value=t.prompt,N.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),N.focus();return}if(y){y(t.prompt);return}N.value="",p.sendMessage(t.prompt)},k=()=>{let C=R("button",`persona-suggestion persona-suggestion--${a}`);if(C.type="button",C.disabled=i,C.dataset.suggestionId=t.id,C.dataset.emphasis=t.emphasis,C.dataset.behavior=M,a==="chip"&&(u?.fontFamily&&(C.style.fontFamily=pP(u.fontFamily)),u?.fontWeight&&(C.style.fontWeight=u.fontWeight),u?.paddingX&&(C.style.paddingLeft=u.paddingX,C.style.paddingRight=u.paddingX),u?.paddingY&&(C.style.paddingTop=u.paddingY,C.style.paddingBottom=u.paddingY)),t.icon){let N=le(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);N&&(N.classList.add("persona-suggestion__icon"),t.iconColor&&(N.style.color=t.iconColor),C.appendChild(N))}let L=R("span","persona-suggestion__copy");if(L.appendChild(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&a!=="chip"&&L.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),C.appendChild(L),a!=="chip"){let N=Ut(cl,16,"currentColor",1.8);N&&(N.classList.add("persona-suggestion__arrow"),C.appendChild(N))}return C.addEventListener("click",S),C},P=null;for(let C of c)if(C.renderSuggestion&&(P=C.renderSuggestion({suggestion:{...t},index:o,surface:n,source:r,variant:a,streaming:i,config:d,defaultRenderer:k,select:S}),P))break;return P??(P=k()),(H=P.dataset).suggestionId||(H.suggestionId=t.id),(b=P.dataset).behavior||(b.behavior=M),(w=P.dataset).emphasis||(w.emphasis=t.emphasis),P instanceof HTMLButtonElement||P.setAttribute("aria-disabled",i?"true":"false"),P},Wl=e=>{let t=[],o=[],n=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){a();return}let m=getComputedStyle(e).direction==="rtl",h=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),y=4,x=h<=y,M=h>=p-y,S=m?!M:!x,k=m?!x:!M;e.toggleAttribute("data-scroll-left",S),e.toggleAttribute("data-scroll-right",k)},d=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",d,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(d):null;return c?.observe(e),{buttons:t,elements:o,destroy:()=>{e.removeEventListener("scroll",d),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,m,h,y,x,M)=>{e.replaceChildren(),t.length=0,o.length=0;let S=M?.source??"config",k=M?.surface??(S==="config"?"starter":"followUp"),P=k==="followUp",H=M?.variant??"chip",b=M?.behavior??"send",w=M?.overflow??"wrap",C=M?.config??{},L=M?.plugins??[],N=typeof M?.maxItems=="number"?Math.max(0,Math.floor(M.maxItems)):void 0,X=P?"followUps":"starters";!yS.has(C)&&C.debug===!0&&H!=="chip"&&C.suggestions?.[X]?.overflow!==void 0&&(yS.add(C),console.info(`[persona] suggestions.${X}.overflow applies to the "chip" variant only; the "${H}" variant manages its own stacking.`));let V=G=>G.map(Mg).filter(ue=>ue!==null).map(ue=>({...ue,behavior:ue.behavior??b})),T=V(p??[]);L.forEach(G=>{G.transformSuggestions&&(T=V(G.transformSuggestions({suggestions:T.map(ue=>({...ue})),surface:k,source:S,config:C})))});let O=N===void 0?T:T.slice(0,N);if(!O.length){e.hidden=!0,n=null,a();return}if(!P&&(y??m.getMessages()).some(ue=>ue.role==="user")){e.hidden=!0,n=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Ag(k),e.dataset.variant=H,e.dataset.overflow=w;let D=document.createDocumentFragment(),W=m.isStreaming();O.forEach((G,ue)=>{let ae=Tg({item:G,index:ue,surface:k,source:S,variant:H,streaming:W,config:C,plugins:L,chipsConfig:x,session:m,getTextarea:()=>h,eventTarget:e,submitPrompt:M?.submitPrompt});D.appendChild(ae),o.push(ae),[...ae instanceof HTMLButtonElement?[ae]:[],...Array.from(ae.querySelectorAll("button"))].forEach(Re=>{t.includes(Re)||(Re.disabled=W,t.push(Re))})}),e.appendChild(D),i(),d();let ee=JSON.stringify({normalized:O,surface:k,variant:H,source:S});ee!==n&&(n=ee,mP(o),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:O.map(G=>({...G})),surface:k,source:S,variant:H},bubbles:!0,composed:!0})),P&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:O.map(G=>G.prompt)},bubbles:!0,composed:!0})))}}};var Xo={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var gP="persona-header-control",hP="persona-header-control--glyph",yP="persona-header-control--sparse",bP=20,vP={x:[1.4,1.05]},bS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",xP="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",hu=(e,t,o={})=>{let{iconSize:n,iconText:r}=o,[a,i]=vP[t]??[1,1.5],d=!n;e.classList.toggle(hP,d),e.classList.toggle(yP,d&&a!==1);let c=parseFloat(n??"")||bP,u=le(t,`${Math.round(c*a)}px`,"currentColor",i);u?(u.style.display="block",d||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(u)):r&&(e.textContent=r)},Ns=e=>{let{ariaLabel:t,tooltip:o=!0,tooltipHint:n,iconName:r,iconText:a,wrapperClassName:i=bS,size:d,iconSize:c,color:u,backgroundColor:p,borderWidth:m,borderColor:h,borderRadius:y,paddingX:x,paddingY:M,hidden:S,extraClassName:k,attrs:P}=e,H=R("div",i),b=!!(m||h),w=Q("button",{className:yo(gP,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!b&&"persona-border-none",!y&&"persona-rounded-full",k),attrs:{type:"button","aria-label":t,...P},style:{width:d,height:d,minWidth:d,minHeight:d,display:S?"none":void 0,color:u||xo.actionIconColor,backgroundColor:p,border:b?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:y,paddingLeft:x,paddingRight:x,paddingTop:M,paddingBottom:M}});return r?hu(w,r,{iconSize:c,iconText:a}):a&&(w.textContent=a),H.appendChild(w),Jt({anchor:w,trigger:H,text:()=>w.getAttribute("aria-label")??t,hint:n,enabled:o}),{button:w,wrapper:H}},Ga=(e,t={})=>{let{showClose:o=!0,wrapperClassName:n=bS,buttonSize:r,iconSize:a}=t,i=e?.launcher??{},d=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:u,wrapper:p}=Ns({ariaLabel:d,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:n,size:r??i.closeButtonSize,iconSize:a,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!o});return{button:u,wrapper:p}},Xa=(e,t={})=>{let{wrapperClassName:o=xP,buttonSize:n,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},d=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:u,wrapper:p}=Ns({ariaLabel:d,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:o,size:n??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:u,wrapper:p}};var xo={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},Eg={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},CP={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},gr=e=>{let{config:t,showClose:o=!0}=e,n=Q("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:xo.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},a=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",d=r.headerIconHidden??!1,c=r.headerIconName,u=Q("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!d)if(c){let w=parseFloat(a)||24,C=le(c,w*.6,"currentColor",1);C?u.replaceChildren(C):u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let w=R("img");w.src=t.launcher.iconUrl,w.alt="",w.className="persona-rounded-xl persona-object-cover",w.style.height=a,w.style.width=a,u.replaceChildren(w)}else u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=R("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Q("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:xo.titleColor,...Eg}}),h=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:xo.subtitleColor,...CP}});p.append(m,h),d?n.append(p):n.append(u,p);let y=r.clearChat??{},x=y.enabled??!0,M=y.placement??"inline",S=null,k=null;if(x){let C=Xa(t,{wrapperClassName:M==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=C.button,k=C.wrapper,M==="top-right"&&(k.style.right="48px"),M==="inline"&&n.appendChild(k)}let P=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&M==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:H,wrapper:b}=Ga(t,{showClose:o,wrapperClassName:P});return i!=="top-right"&&n.appendChild(b),{header:n,iconHolder:u,headerTitle:m,headerSubtitle:h,closeButton:H,closeButtonWrapper:b,clearChatButton:S,clearChatButtonWrapper:k}},Fs=(e,t,o)=>{let n=o?.launcher??{},r=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Us(e){let{items:t,onSelect:o,anchor:n,position:r="bottom-left",portal:a,onOpenChange:i}=e,d=R("div","persona-dropdown-menu persona-hidden");d.setAttribute("role","menu"),d.setAttribute("data-persona-theme-zone","dropdown"),a?(d.style.position="fixed",d.style.zIndex=String(qa)):(d.style.position="absolute",d.style.top="100%",d.style.marginTop="4px",r==="bottom-right"?d.style.right="0":d.style.left="0");for(let x of t){if(x.dividerBefore){let k=document.createElement("hr");d.appendChild(k)}let M=document.createElement("button");if(M.type="button",M.setAttribute("role","menuitem"),M.setAttribute("data-dropdown-item-id",x.id),x.destructive&&M.setAttribute("data-destructive",""),x.icon){let k=le(x.icon,16,"currentColor",1.5);k&&M.appendChild(k)}let S=document.createElement("span");S.textContent=x.label,M.appendChild(S),M.addEventListener("click",k=>{k.stopPropagation(),m(),o(x.id)}),d.appendChild(M)}let c=null;function u(){if(!a)return;let x=n.getBoundingClientRect();d.style.top=`${x.bottom+4}px`,r==="bottom-right"?(d.style.right=`${window.innerWidth-x.right}px`,d.style.left="auto"):(d.style.left=`${x.left}px`,d.style.right="auto")}function p(){let x=d.classList.contains("persona-hidden");u(),d.classList.remove("persona-hidden"),x&&i?.(!0),requestAnimationFrame(()=>{let M=S=>{!d.contains(S.target)&&!n.contains(S.target)&&m()};document.addEventListener("click",M,!0),c=()=>document.removeEventListener("click",M,!0)})}function m(){let x=!d.classList.contains("persona-hidden");d.classList.add("persona-hidden"),c?.(),c=null,x&&i?.(!1)}function h(){d.classList.contains("persona-hidden")?p():m()}function y(){m(),d.remove()}return a&&a.appendChild(d),{element:d,show:p,hide:m,toggle:h,destroy:y}}function qs(e){let{icon:t,label:o,size:n,strokeWidth:r,className:a,chromeless:i,onClick:d,aria:c}=e,u=R("button",yo(!i&&"persona-icon-btn",a));u.type="button",u.setAttribute("aria-label",o),u.title=o;let p=le(t,n??16,"currentColor",r??2);if(p&&u.appendChild(p),d&&u.addEventListener("click",d),c)for(let[m,h]of Object.entries(c))u.setAttribute(m,h);return u}function Pg(e){let{icon:t,label:o,variant:n="default",size:r="sm",iconSize:a,className:i,onClick:d,aria:c}=e,u="persona-label-btn";n!=="default"&&(u+=" persona-label-btn--"+n),u+=" persona-label-btn--"+r,i&&(u+=" "+i);let p=R("button",u);if(p.type="button",p.setAttribute("aria-label",o),t){let h=le(t,a??14,"currentColor",2);h&&p.appendChild(h)}let m=R("span");if(m.textContent=o,p.appendChild(m),d&&p.addEventListener("click",d),c)for(let[h,y]of Object.entries(c))p.setAttribute(h,y);return p}function vS(e){let{items:t,selectedId:o,onSelect:n,className:r}=e,a=R("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let i=o,d=[];function c(){for(let p of d)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let m;p.icon?m=qs({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,c(),n(p.id)}}):(m=R("button","persona-icon-btn"+(p.className?" "+p.className:"")),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{i=p.id,c(),n(p.id)})),m.setAttribute("aria-pressed",p.id===i?"true":"false"),d.push({id:p.id,btn:m}),a.appendChild(m)}function u(p){i=p,c()}return{element:a,setSelected:u}}function xS(e){let{label:t,icon:o,iconSize:n,iconOnly:r,menuItems:a,onSelect:i,onPrimary:d,position:c="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:m,className:h,primaryClassName:y,chevronClassName:x}=e,M=R("div","persona-split-btn"+(h?" "+h:"")),S={label:t,className:"persona-split-btn-primary"+(y?" "+y:""),onClick:d},k=r&&o?qs({...S,icon:o,size:n??14}):Pg({...S,icon:o,iconSize:n??14}),P=qs({icon:"chevron-down",label:p,size:m??14,className:"persona-split-btn-chevron"+(x?" "+x:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});M.append(k,P);let H=null,b=()=>{if(H)return H;let w=(typeof u=="function"?u():u)??void 0;return H=Us({items:a,onSelect:i,anchor:M,position:c,portal:w,onOpenChange:C=>{P.setAttribute("aria-expanded",C?"true":"false")}}),w||M.appendChild(H.element),H};return M.isConnected?b():requestAnimationFrame(()=>{H||b()}),P.addEventListener("click",w=>{w.stopPropagation(),b().toggle()}),{element:M,primaryButton:k,chevronButton:P,openMenu:()=>b().show(),closeMenu:()=>H?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{H?.destroy(),M.remove()}}}function yu(e){let{label:t,icon:o="chevron-down",menuItems:n,onSelect:r,position:a="bottom-left",portal:i,className:d,hover:c}=e,u=R("div","persona-combo-btn"+(d?" "+d:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",t);let p=R("span","persona-combo-btn-label");p.textContent=t,u.appendChild(p);let m=le(o,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",u.appendChild(m)),c&&(u.style.borderRadius=c.borderRadius??"10px",u.style.padding=c.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=c.background??"",u.style.borderColor=c.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let h=Us({items:n,onSelect:x=>{u.setAttribute("aria-expanded","false"),r(x)},anchor:u,position:a,portal:i});i||u.appendChild(h.element);let y=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",x=>{if(x.stopPropagation(),y())return;let M=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",M?"false":"true"),h.toggle()}),u.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),u.click())}),{element:u,setLabel:x=>{p.textContent=x,u.setAttribute("aria-label",x)},open:()=>{u.setAttribute("aria-expanded","true"),h.show()},close:()=>{u.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let x=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",x?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),u.remove()}}}var kg=e=>{let t=gr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),o=e.layoutHeaderConfig?.onTitleClick;if(o){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>o()),n.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),o())}))}return t};function SP(e,t,o){if(t?.length)for(let n of t){let{button:r,wrapper:a}=Ns({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?uu(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",n.id),n.shortcut){let i=Ml(n.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(n.menuItems?.length){let i=Us({items:n.menuItems,onSelect:d=>o?.(d),anchor:a,position:"bottom-right"});a.appendChild(i.element),r.addEventListener("click",d=>{d.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>o?.(n.id));e.appendChild(a)}}var Lg=e=>{let{config:t,showClose:o=!0,onClose:n,layoutHeaderConfig:r,onHeaderAction:a}=e,i=t?.launcher??{},d=R("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");d.setAttribute("data-persona-theme-zone","header"),d.style.minHeight=xo.minHeight,d.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",d.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",d.style.boxShadow="var(--persona-header-shadow, none)",d.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,u,p;if(c){let b=yu({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:w=>{let C=N=>{N===!1&&b.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:w}}))},L=c.onSelect(w);L instanceof Promise?L.then(C,()=>{}):C(L)},hover:c.hover,className:""});u=b.element,u.style.color=xo.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=R("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=R("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=xo.titleColor,Object.assign(p.style,Eg),p.textContent=i.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let w=r.onTitleClick;u.addEventListener("click",C=>{C.target.closest("button")||w()}),u.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),w())})}let b=r?.titleRowHover;b&&(u.style.borderRadius=b.borderRadius??"10px",u.style.padding=b.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=b.background??"",u.style.borderColor=b.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}d.appendChild(u);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:y}=Ga(t,{showClose:o,wrapperClassName:m});n&&h.addEventListener("click",n);let x=R("div","persona-flex persona-items-center persona-gap-1");c||SP(x,r?.trailingActions,r?.onAction??a);let M=i.clearChat??{},S=null,k=null;if(M.enabled??!0){let b=M.placement??"inline",w=Xa(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});S=w.button,k=w.wrapper,b==="top-right"?k.style.right="48px":x.appendChild(k)}x.appendChild(y),d.appendChild(x);let P=R("div");P.style.display="none";let H=R("span");return H.style.display="none",{header:d,iconHolder:P,headerTitle:p,headerSubtitle:H,closeButton:h,closeButtonWrapper:y,clearChatButton:S,clearChatButtonWrapper:k}},bu={default:kg,minimal:Lg},Ig=e=>bu[e]??bu.default,Qa=(e,t,o)=>{if(t?.render){let i=t.render({config:e,onClose:o?.onClose,onClearChat:o?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),d=R("div");d.style.display="none";let c=R("span"),u=R("span"),p=R("button");p.style.display="none";let m=R("div");return m.style.display="none",{header:i,iconHolder:d,headerTitle:c,headerSubtitle:u,closeButton:p,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let n=t?.layout??"default",a=Ig(n)({config:e,showClose:t?.showCloseButton??o?.showClose??!0,onClose:o?.onClose,onClearChat:o?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Vs=e=>{let{config:t}=e,o=Q("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),n=Jc(),r=Q("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:i}=Gc(t);i();let d=Xc(t),c=ja(t),u=Qc(t),p=Yc(t),m=Q("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),u&&(u.previewsContainer.style.gap="8px",m.append(u.previewsContainer),r.append(u.input)),r.append(a);let h=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),x=Q("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return u&&y.append(u.wrapper),c&&x.append(c.wrapper),x.append(d.wrapper),h.append(y,x),r.append(h),r.addEventListener("click",M=>{M.target!==d.button&&M.target!==d.wrapper&&M.target!==c?.button&&M.target!==c?.wrapper&&M.target!==u?.button&&M.target!==u?.wrapper&&a.focus()}),o.append(n,r,p),{footer:o,suggestions:n,composerForm:r,header:m,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:h,leftActions:y,rightActions:x,setSendButtonMode:d.setMode}};var CS=()=>{let e=Q("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=R("span","persona-pill-peek__icon"),o=Ut(gl,16,"currentColor",1.5);o&&t.appendChild(o);let n=R("span","persona-pill-peek__text"),r=R("span","persona-pill-peek__caret"),a=Ut(Ws,16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,n,r),{root:e,textNode:n}},vu=e=>{let{config:t}=e,o=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=Jc(),r=Yc(t);r.style.display="none";let{textarea:a,attachAutoResize:i}=Gc(t,{defaultMaxLines:5});i();let d=Xc(t),c=ja(t),u=Qc(t);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&m.append(u.wrapper);let h=Q("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&h.append(c.wrapper),h.append(d.wrapper),p.addEventListener("click",M=>{M.target!==d.button&&M.target!==d.wrapper&&M.target!==c?.button&&M.target!==c?.wrapper&&M.target!==u?.button&&M.target!==u?.wrapper&&a.focus()}),u&&p.append(u.input),p.append(m,a,h);let y=Q("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(y),u&&y.append(u.previewsContainer),o.append(n,p,r);let x=p;return{footer:o,suggestions:n,composerForm:p,header:y,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:x,leftActions:m,rightActions:h,setSendButtonMode:d.setMode}};var wP=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},AP=(e,t)=>{if(!e)return null;let o=wP(e);if(o===null)return null;let n=t?.[e],r=n!==void 0?n:o;return r||null},MP=(e,t)=>{let o=R("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return o.setAttribute("data-stop-reason",e),o.setAttribute("role","note"),o.style.opacity="0.75",o.textContent=t,o},TP=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Hg=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Wg=320,TS=320,EP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),PP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),kP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),LP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),IP=e=>{if(!e||e.length===0)return null;let t=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let o of e){let n=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:o.label}}),r=R("span","persona-mention-chip-icon"),a=le(o.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),n.appendChild(r),n.appendChild(Q("span",{className:"persona-mention-chip-label",text:o.label})),t.appendChild(n)}return t},RP=(e,t)=>{let o=document.createDocumentFragment();for(let n of e){if(n.kind==="text"){o.appendChild(document.createTextNode(n.text));continue}o.appendChild(Cl(n.ref,{readonly:!0,render:t}))}return o},SS="\uE000",wS="\uE001",HP=(e,t,o,n)=>{let r=Math.random().toString(36).slice(2,8),a=h=>`${SS}${r}:${h}${wS}`,i=t.map((h,y)=>h.kind==="text"?h.text:a(y)).join(""),d=o(i);if(!t.every((h,y)=>h.kind==="text"||d.includes(a(y)))){e.replaceChildren(RP(t,n));return}e.innerHTML=d;let u=new RegExp(`${SS}${r}:(\\d+)${wS}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let h=p.nextNode();h;h=p.nextNode())m.push(h);for(let h of m){let y=h;for(let x=u.exec(y.data);x;x=u.exec(y.data)){let M=t[Number(x[1])],S=y.splitText(x.index);S.data=S.data.slice(x[0].length),M?.kind==="mention"&&S.parentNode?.insertBefore(Cl(M.ref,{readonly:!0,render:n}),S),y=S}}},WP=(e,t,o)=>{if(e.length===0)return null;try{let n=R("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let r=0,a=!1,i=()=>{a||(a=!0,n.remove(),o?.())};return e.forEach((d,c)=>{let u=R("img");u.alt=d.alt?.trim()||`Attached image ${c+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${Wg}px`,u.style.maxHeight=`${TS}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&i())}),u.addEventListener("load",()=>{p=!0}),TP(d.image)?(u.src=d.image,n.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(i(),null):n}catch{return o?.(),null}},BP=e=>{if(e.length===0)return null;try{let t=R("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let o=0;return e.forEach(n=>{if(!Hg(n.audio))return;let r=R("audio");r.controls=!0,r.preload="metadata",r.src=n.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Wg}px`,t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},OP=e=>{if(e.length===0)return null;try{let t=R("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let o=0;return e.forEach(n=>{if(!Hg(n.video))return;let r=R("video");r.controls=!0,r.preload="metadata",r.src=n.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Wg}px`,r.style.maxHeight=`${TS}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},DP=e=>{if(e.length===0)return null;try{let t=R("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let o=0;return e.forEach(n=>{if(!Hg(n.data))return;let r=R("a");r.href=n.data,r.download=n.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=n.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},$s=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(o),e.appendChild(n),e.appendChild(r),e},Bg=(e,t,o)=>{let n={config:o??{},streaming:!0,location:e,defaultRenderer:$s};if(t){let r=t(n);if(r!==null)return r}return $s()},_P=(e,t)=>{let o=R("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=t==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let r=R("img");r.src=n,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",o.appendChild(r)}else o.textContent=n,o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else o.textContent=t==="user"?"U":"A",o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return o},AS=(e,t,o="div")=>{let n=R(o,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Bl=(e,t="bubble")=>{let o=["persona-message-bubble"];switch(t){case"flat":e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):o.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":o.push("persona-text-sm","persona-leading-relaxed"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:o.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return o},MS={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},NP=(e,t,o="bubble",n)=>{if(!n)return;let r=t==="user"?"user":"assistant",a=MS[o??"bubble"]??MS.bubble;n.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},xu="custom:",FP=e=>`${xu}${e}`,ES=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(o=>(o.roles??["assistant"]).includes(t)),Og=(e,t,o,n)=>{let r=t.showCopy??!0,a=t.showUpvote??!0,i=t.showDownvote??!0,d=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&n?.canRegenerate===!0,u=(t.showEdit??!1)&&n?.canEdit===!0,p=(t.showQuote??!1)&&n?.canQuote!==!1,m=ES(t,e.role);if(!r&&!a&&!i&&!d&&!c&&!u&&!p&&m.length===0){let H=R("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let h=t.visibility??"hover",y=t.align??"right",x=t.layout??"pill-inside",M={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[y],S={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[x],k=R("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${M} ${S} ${h==="hover"?"persona-message-actions-hover":""}`);k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id);let P=(H,b,w)=>{let C=qs({icon:H,label:b,size:14,className:"persona-message-action-btn",chromeless:!0});return C.setAttribute("data-action",w),C};r&&k.appendChild(P("copy","Copy message","copy")),d&&k.appendChild(P("volume-2","Read aloud","read-aloud")),a&&k.appendChild(P("thumbs-up","Upvote","upvote")),i&&k.appendChild(P("thumbs-down","Downvote","downvote")),c&&k.appendChild(P("refresh-cw","Regenerate response","regenerate")),u&&k.appendChild(P("pencil","Edit message","edit")),p&&k.appendChild(P("quote","Quote message","quote"));for(let H of m)k.appendChild(P(H.iconName??"ellipsis",H.label,FP(H.id)));return k},Ya=(e,t,o,n,r,a)=>{let i=o??{},d=i.layout??"bubble",c=i.avatar,u=i.timestamp,p=c?.show??!1,m=u?.show??!1,h=c?.position??"left",y=u?.position??"below",x=Bl(e.role,d),M=R("div",x.join(" "));M.id=`bubble-${e.id}`,M.setAttribute("data-message-id",e.id),M.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let S=a?.widgetConfig?.theme?.components?.message;NP(M,e.role,d,e.role==="user"?S?.user:S?.assistant),d==="flat"?(M.style.backgroundColor="transparent",M.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(M.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",M.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(M.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",M.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=EP(e),P=e.content?.trim()??"",b=k.length>0&&P===Wa,w=fu(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,L=e.role==="assistant"&&w.type!=="none"?Pl(w.type,C):null,N=e.role==="assistant"&&L?.isAnimating?.(e)===!0,X=e.role==="assistant"&&L!==null&&(!!e.streaming||N);X&&L?.bubbleClass&&M.classList.add(L.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),e.streaming&&V.classList.add("persona-content-streaming"),X&&L&&(L.containerClass&&V.classList.add(L.containerClass),V.style.setProperty("--persona-stream-step",`${w.speed}ms`),V.style.setProperty("--persona-stream-duration",`${w.duration}ms`));let T=X?mu(e.content??"",w.buffer,L,e,!!e.streaming):e.content??"",O=()=>{let Pe=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent});return X&&L?.wrap==="char"?kl(Pe,"char",e.id,{skipTags:L.skipTags}):X&&L?.wrap==="word"?kl(Pe,"word",e.id,{skipTags:L.skipTags}):Pe},D=null;if(b?(D=document.createElement("div"),D.innerHTML=O(),D.style.display="none",V.appendChild(D)):e.contentSegments?.length?HP(V,e.contentSegments,Pe=>t({text:Pe,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=O(),X&&L?.useCaret&&!b&&P){let Pe=gu(),q=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ue=q[q.length-1];if(Ue?.parentNode)Ue.parentNode.insertBefore(Pe,Ue.nextSibling);else{let Je=V.lastElementChild;Je?Je.appendChild(Pe):V.appendChild(Pe)}}if(m&&y==="inline"&&e.createdAt){let Pe=AS(e,u,"span");Pe.classList.add("persona-timestamp-inline");let q=V.lastElementChild;q?q.appendChild(Pe):V.appendChild(Pe)}if(k.length>0){let Pe=WP(k,!b&&!!P,()=>{b&&D&&(D.style.display="")});Pe?M.appendChild(Pe):b&&D&&(D.style.display="")}let W=PP(e);if(W.length>0){let Pe=BP(W);Pe&&M.appendChild(Pe)}let ee=kP(e);if(ee.length>0){let Pe=OP(ee);Pe&&M.appendChild(Pe)}let G=LP(e);if(G.length>0){let Pe=DP(G);Pe&&M.appendChild(Pe)}let ue=e.contentSegments?.length?null:IP(e.contextMentions);if(ue&&M.appendChild(ue),M.appendChild(V),m&&y==="below"&&e.createdAt){let Pe=AS(e,u);Pe.classList.add("persona-mt-1"),M.appendChild(Pe)}let ae=e.role==="assistant"?AP(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Pe=!!(T&&T.trim()),q=w.placeholder==="skeleton",Ue=q&&w.buffer==="line"&&Pe;if(Pe)Ue&&M.appendChild(Ll());else if(q)M.appendChild(Ll());else{let Je=Bg("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Je&&M.appendChild(Je)}}ae&&e.stopReason&&!e.streaming&&(P||(V.style.display="none"),M.appendChild(MP(e.stopReason,ae)));let ye=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&n?.enabled!==!1,Re=a?.actionEligibility,be=e.role==="user"&&!e.streaming&&n?.enabled!==!1&&(n?.showEdit===!0&&Re?.canEdit===!0||n?.showQuote===!0&&Re?.canQuote===!0||ES(n,"user").length>0);if((ye||be)&&n){let Pe=Og(e,be?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,r,Re);M.appendChild(Pe)}if(!p||e.role==="system")return M;let pe=R("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),yt=_P(c,e.role);return h==="right"||h==="left"&&e.role==="user"?pe.append(M,yt):pe.append(yt,M),pe},PS=(e,t,o,n,r,a)=>{let i=o??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ya(e,t,o,n,r,a)};var UP=40,qP=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let o=null;try{o=t()}catch(n){console.warn("[persona] welcome.icon renderer threw",n)}if(!o){e.hidden=!0;return}e.appendChild(o),e.hidden=!1;return}if(t.type==="lucide"){let o=le(t.name,UP);if(!o){e.hidden=!0;return}e.appendChild(o)}else t.type==="image"?e.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Q("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},kS=(e,t,o={})=>{let n=Q("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let r=R("p","persona-welcome-kicker");r.hidden=!0;let a=R("h2","persona-welcome-title"),i=R("p","persona-welcome-subtitle"),d=Q("div",{className:"persona-welcome-head-text"},r,a),c=Q("div",{className:"persona-welcome-title-row"},n,d);return{host:Q("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:o.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,i,t),iconHolder:n,kicker:r,title:a,subtitle:i,starterSuggestions:t}},Ja=(e,t,o)=>{t.hidden=!o,t.style.display=o?"":"none",e.classList.toggle("persona-gap-6",o),e.classList.toggle("persona-gap-3",!o)},Su=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",qP(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},VP="data-persona-welcome-plugin",LS="data-persona-welcome-overlay",Cu="persona-welcome-overlay-active",Dg=new WeakMap,_g=(e,t,o)=>{o.setAttribute(VP,""),t.appendChild(o),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(LS,""),e.classList.contains(Cu)||(Dg.set(e,e.scrollTop),e.classList.add(Cu),e.scrollTop=0)},Ng=(e,t,o)=>{o&&o!==t&&o.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(LS),e.classList.contains(Cu)&&(e.classList.remove(Cu),e.scrollTop=Dg.get(e)??e.scrollTop,Dg.delete(e))},IS=()=>{let e=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},wu=(e,t,o)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let n=o?.layout?.messages?.layout??"bubble",r=Q("div",{className:Bl("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:n==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Q("div",{className:"persona-flex"},r)),e.hidden=!1},RS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,HS=(e,t)=>{if(RS()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let o=e.getBoundingClientRect(),n=e.parentElement,r=0,a=0,i=0;if(n){let x=getComputedStyle(n);r=parseFloat(x.rowGap)||0;let M=e.previousElementSibling,S=e.nextElementSibling,P=n.getBoundingClientRect().top+(parseFloat(x.borderTopWidth)||0)+(parseFloat(x.paddingTop)||0)-n.scrollTop;a=Math.max(0,M?o.top-M.getBoundingClientRect().bottom-r:o.top-P),i=Math.max(0,S?S.getBoundingClientRect().top-o.bottom-r:0)}let d=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),u=parseFloat(c.paddingTop)||0,p=parseFloat(c.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${o.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${a}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,y=()=>{h||(h=!0,e.style.overflow=d,t(m))};return m.finished.then(y).catch(y),m},WS=(e,t,o)=>{if(t<=1||RS()||typeof e.animate!="function"||!e.isConnected)return null;let n=o==="drop"?-t:t;return e.animate([{transform:`translateY(${n}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var $P="Hello \u{1F44B}",jP="I can answer questions and help you get things done here.",BS=new WeakSet,Co=(e,t)=>!!e&&e[t]!==void 0,zP=(e,t)=>{!e||e.debug!==!0||!t.length||BS.has(e)||(BS.add(e),t.forEach(o=>console.warn(`[persona] ${o}`)))},Cn=e=>{let t=e?.welcome,o=e?.copy,n=Co(t,"variant")?t.variant:o?.showWelcomeCard===!1?"none":"card",r=n==="hero"?"on-first-message":Co(t,"dismiss")?t.dismiss:"never",a=[];Co(t,"title")&&Co(o,"welcomeTitle")&&a.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Co(t,"subtitle")&&Co(o,"welcomeSubtitle")&&a.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Co(t,"variant")&&Co(o,"showWelcomeCard")&&a.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),n==="hero"&&Co(t,"message")&&a.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),n==="hero"&&Co(t,"dismiss")&&t.dismiss!=="on-first-message"&&a.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let i=t?.anchor==="center"?"center":"bottom",d=Al(t?.anchorComposerTop)!==null;return Co(t,"anchorComposerTop")&&!d&&a.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),i!=="center"&&(Co(t,"anchorComposerTop")||Co(t,"composerGap"))&&a.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),zP(e,a),{title:Co(t,"title")?t.title:o?.welcomeTitle??$P,kicker:t?.kicker??"",subtitle:Co(t,"subtitle")?t.subtitle:o?.welcomeSubtitle??jP,icon:t?.icon,align:t?.align==="start"||t?.align==="center"?t.align:void 0,iconPlacement:t?.icon&&typeof t.icon!="function"&&t.icon.placement==="inline"?"inline":"above",variant:n,dismiss:r,message:n==="hero"?void 0:t?.message,anchor:i,anchorComposerTop:d?t.anchorComposerTop:"44%",composerGap:t?.composerGap?.trim()||lu}},OS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Yr=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(o=>o.role==="user");var DS="16px",Ug="10px",qg="14px",_S=e=>{let t=e?.launcher?.enabled??!0,o=Ct(e);if(Qr(e)){let p=e?.launcher?.composerBar??{},m=R("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=p.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??ro);let h=R("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");h.style.width="100%",m.appendChild(h);let y=R("div","persona-widget-pill-root");return y.setAttribute("data-persona-composer-bar",""),y.dataset.state="collapsed",y.dataset.expandedSize=p.expandedSize??"anchored",y.style.zIndex=String(e?.launcher?.zIndex??ro),{wrapper:m,panel:h,pillRoot:y}}if(o){let p=R("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=R("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(m),{wrapper:p,panel:m}}if(!t){let p=R("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=R("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),h=e?.launcher?.width??"100%";return p.style.width=h,m.style.width="100%",p.appendChild(m),{wrapper:p,panel:m}}let r=e?.launcher??{},a=r.position&&Xo[r.position]?Xo[r.position]:Xo["bottom-right"],i=R("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??ro);let d=R("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=e?.launcher?.width??e?.launcherWidth??Ko;return d.style.width=u,d.style.maxWidth=u,i.appendChild(d),{wrapper:i,panel:d}},Vg=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Ag(e)}});return t.hidden=!0,t},NS=(e,t)=>{let o=Vg("starter"),n=kS(e,o,{flatShadow:Ct(e)}),r=Cn(e);Su(n,r),Ja(t,n.host,Yr(r,e?.initialMessages));let a=IS();return wu(a,r.message,e),{welcome:n,greetingHost:a}},KP=(e,t)=>{let o=R("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");o.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:r}=Ga(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:DS,iconSize:Ug});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,i=null,d=null;if(a){let L=Xa(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:DS,iconSize:qg});i=L.button,d=L.wrapper,d.style.position="absolute",d.style.top="8px",d.style.right="32px",d.style.zIndex="10"}let c=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:m}=NS(e,u),{host:h,title:y,subtitle:x}=p,M=p.starterSuggestions,S=R("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),k=Vg("followUp"),P=Gr(e,!0);P&&(S.style.maxWidth=P,S.style.marginLeft="auto",S.style.marginRight="auto",S.style.width="100%"),u.append(h,m,S,k);let H=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),b=vu({config:e}),{root:w,textNode:C}=CS();return o.append(c,r,u,H),d&&o.appendChild(d),{container:o,body:u,messagesWrapper:S,starterSuggestions:M,transcriptSuggestions:k,composerOverlay:H,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:h,welcomeIconHolder:p.iconHolder,greetingHost:m,introKicker:p.kicker,introTitle:y,introSubtitle:x,closeButton:n,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:d,iconHolder:R("span"),headerTitle:R("span"),headerSubtitle:R("span"),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:w,peekTextNode:C}},FS=(e,t=!0)=>{if(Qr(e))return KP(e,t);let o=Q("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),n=e?.layout?.header,r=e?.layout?.showHeader!==!1,a=n?Qa(e,n,{showClose:t}):gr({config:e,showClose:t}),i=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:c}=NS(e,i),{host:u,title:p,subtitle:m}=d,h=d.starterSuggestions,y=R("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),x=Vg("followUp"),M=Gr(e,!1);M&&(y.style.maxWidth=M,y.style.marginLeft="auto",y.style.marginRight="auto",y.style.width="100%"),i.append(u,c,y,x);let S=Vs({config:e}),k=e?.layout?.showFooter!==!1;r?Fs(o,a,e):(a.header.style.display="none",Fs(o,a,e)),o.append(i);let P=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return k||(S.footer.style.display="none"),o.append(S.footer),o.append(P),{container:o,body:i,messagesWrapper:y,starterSuggestions:h,transcriptSuggestions:x,composerOverlay:P,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,welcomeHost:u,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:p,introSubtitle:m,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode}};var $g=(e,t)=>{let o=R("button");o.type="button",o.innerHTML=`
|
|
23
|
+
`),d=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(d){let u=[];a&&u.push(an(a)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(c){let u=[];i&&u.push(an(i)),u.push(...r.contentParts),t.contentParts=u}else a&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,o){let n=t.trim(),r=!!o?.replayFields&&(o.replayFields.llmContent!==void 0||o.replayFields.rawContent!==void 0||(o.replayFields.contextMentions?.length??0)>0);if(!n&&(!o?.contentParts||o.contentParts.length===0)&&(!o?.mentions||o.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let a=ka(),i=Fr();this.activeAssistantMessageId=null;let d=o?.contentParts&&Ba(o.contentParts)?Wa:"",c={id:a,role:"user",content:n||d,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:o?.viaVoice||!1,...o?.contentParts&&o.contentParts.length>0&&{contentParts:o.contentParts},...o?.mentions&&o.mentions.refs.length>0&&{contextMentions:o.mentions.refs},...o?.contentSegments&&o.contentSegments.length>0&&{contentSegments:o.contentSegments},...o?.composerOptions&&{composerOptions:o.composerOptions},...o?.replayFields??{}};this.appendMessage(c),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,o?.mentions){let m=this.messages.find(h=>h.id===a)??c;if(await this.applyMentionBundle(m,n,o.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(o?.quote&&!o.replayFields){let m=this.messages.find(y=>y.id===a)??c,h=Lx({quote:o.quote,text:m.llmContent??m.content,contentParts:m.contentParts});h.contentParts&&(m.contentParts=h.contentParts),h.llmContent!==void 0&&(m.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(m.quote={...o.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=[...this.messages];try{await this.dispatchWithDeletedRecovery(p,u,i,a,{composerOptions:o?.composerOptions,interrupt:o?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let h=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!h){let y=sm(m,this.config.errorMessage);if(y){let C={id:i,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(C)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,o){let n=Ix(this.messages,t);if(!n)return!1;let r=this.messages[n.start],a=o.replacement,i=a?a.text:r.content,d=a?a.contentParts:r.contentParts;if(!(!!i?.trim()||(d?.length??0)>0||!a&&(r.llmContent?.trim()?.length??0)>0))return!1;let u=a?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},p=a?this.toComposerOptionsPayload(a.options):r.composerOptions,m=a?a.contentSegments:r.contentSegments,h=a?a.options?.quote:void 0,y=a?a.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(i??"",{...d?.length?{contentParts:[...d]}:{},...m?.length?{contentSegments:[...m]}:{},...p?{composerOptions:p}:{},...h?{quote:h}:{},...u&&Object.keys(u).length>0?{replayFields:u}:{},viaVoice:y===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=Fr();this.activeAssistantMessageId=null,this.setStreaming(!0);let o=new AbortController;this.abortController=o;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:o.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let i=sm(r,this.config.errorMessage);if(i){let d={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(d)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,o){if(this.streaming&&!o?.allowReentry)return;o?.allowReentry||this.abortController?.abort(),o?.preserveAssistantId&&o.assistantMessageId&&(this.activeAssistantMessageId=o.assistantMessageId);let n=o?.preserveAssistantId?o.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==n&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,o?.assistantMessageId,o?.seedContent)}catch(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(o=>this.requestWebMcpApproval(o))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let o={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},n=`approval-${o.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o}),new Promise(r=>{this.webMcpApprovalResolvers.set(n,r)})}resolveWebMcpApproval(t,o){let n=this.webMcpApprovalResolvers.get(t);if(!n)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:o,resolvedAt:Date.now()}}),n(o==="approved")}async resolveApproval(t,o,n){let r=`approval-${t.id}`,a={...t,status:o,resolvedAt:Date.now()},i=this.messages.find(p=>p.id===r),d={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(d),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,u=c&&typeof c=="object"?c.onDecision:void 0;try{let p;if(u?p=await u({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},o,n):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},o),p){let m=null;if(p instanceof Response){if(!p.ok){let h=await p.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m,{allowReentry:!0}):(o==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:o.answers,askUserQuestionIndex:o.currentIndex}})}markAskUserQuestionResolved(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...o?{askUserQuestionAnswers:o}:{}}})}async resolveAskUserQuestion(t,o){if(this.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof o=="string"?void 0:o;if(i===void 0&&typeof o=="string"){let p=t.toolCall?.args,m=Array.isArray(p?.questions)?p.questions:[];if(m.length===1){let h=typeof m[0]?.question=="string"?m[0].question:"";h&&(i={[h]:o})}}this.markAskUserQuestionResolved(t,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=t.toolCall.id,c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===0){let p=typeof o=="string"?o:Object.entries(o).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${d}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=i??{};u.forEach((m,h)=>{let y=typeof m?.question=="string"?m.question:"";if(!y)return;let C=p[y],A=Array.isArray(C)?C.join(", "):typeof C=="string"?C:"";this.appendMessage({id:`ask-user-q-${d}-${h}`,role:"assistant",content:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${d}-${h}`,role:"user",content:A||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[a]:o},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}enqueueWebMcpAwait(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.id;if(!o||!n){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(o);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(o,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let o of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(o)})}flushWebMcpAwaitBatch(t){let o=this.webMcpAwaitBatches.get(t);if(!o)return;this.webMcpAwaitBatches.delete(t);let{snapshots:n}=o;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(t,n)}resolveWebMcpToolStartedAt(t){let n=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of n)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==_n?!1:(this.messages.find(n=>n.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let o=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:o,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),o}markWebMcpToolComplete(t,o,n,r=Date.now(),a){this.messages.some(i=>i.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:o,startedAt:n,completedAt:r,duration:void 0,durationMs:Math.max(0,r-n)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,o){let n=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let a=async c=>{let u=c.toolCall?.name,p=c.toolCall?.id;if(!u||!p)return null;let m=`${t}:${p}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(m),n.push(m);let h=this.markWebMcpToolRunning(c),y=c.agentMetadata?.webMcpToolCallId??u;if(u===_n)return{dedupeKey:m,resumeKey:y,output:tx(),toolMessage:c,startedAt:h,completedAt:Date.now()};let C=this.client.executeWebMcpToolCall(u,c.toolCall?.args,r.signal),A;if(!C)A={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{A=await C}catch(M){let E=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));return E||this.callbacks.onError?.(M instanceof Error?M:new Error(String(M))),this.markWebMcpToolComplete(c,am(E?"Aborted by cancel()":XE(M)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(c,am("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:y,output:A,toolMessage:c,startedAt:h,completedAt:Date.now()}},i;if(this.config.webmcp?.execution==="sequential"){i=[];for(let c of o)i.push(await a(c))}else i=await Promise.all(o.map(a));let d=[];try{if(d=i.filter(m=>m!==null),d.length===0)return;let c={};for(let m of d)c[m.resumeKey]=m.output;let u=await this.client.resumeFlow(t,c,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}let p=d[0].dedupeKey;for(let m of d){this.webMcpResolvedKeys.add(m.dedupeKey);let h=m.toolMessage.toolCall?.name,y=m.toolMessage.agentMetadata?.webMcpToolCallId;this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt,{...h===_n?{suggestRepliesResolved:!0}:{},...h&&y?{clientToolAnswer:{toolCallId:y,toolName:h,args:m.toolMessage.toolCall?.args,result:m.output,batch:p}}:{}})}u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let p of d)this.markWebMcpToolComplete(p.toolMessage,am("Aborted by cancel()"),p.startedAt)}finally{for(let c of n)this.webMcpInflightKeys.delete(c);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.name,r=t.toolCall?.id;if(!o){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!n)return;if(!r){let i=`${o}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i))return;this.webMcpInflightKeys.add(i);try{await this.resumeWithToolOutput(o,n,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(i)}catch(d){this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}finally{this.webMcpInflightKeys.delete(i)}return}let a=`${o}:${r}`;if(!(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(o,[t])}async resumeWithToolOutput(t,o,n,r){let a=await this.client.resumeFlow(t,{[o]:n},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!a.ok){let i=await a.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${a.status}`)}r?.onHttpOk?.(),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let o=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=t.artifactType==="markdown"?{id:o,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:o,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(o,n),this.selectedArtifactId=o,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(n),n}injectArtifactRefBlock(t){let o=`artifact-ref-${t.id}`,n=Dn(this.config.features?.artifacts,t),r=Zi(n,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(i=>i.id===o);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:o,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let o of this.artifacts.values()){let n=this.messages.find(i=>i.id===`artifact-ref-${o.id}`);if(!n)continue;let r=Dn(this.config.features?.artifacts,o),a=Zi(r,{artifactId:o.id,title:o.title,artifactType:o.artifactType,status:o.status,...o.file?{file:o.file}:{},...o.presentation?{presentation:o.presentation}:{},...o.component?{component:o.component}:{},...o.props?{componentProps:o.props}:{},...o.markdown!==void 0?{markdown:o.markdown}:{}});n.rawContent!==a&&(n.rawContent=a,n.streaming=o.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);o?.artifactType==="markdown"&&(o.markdown=(o.markdown??"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);o?.artifactType==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>({...o,streaming:!1,sequence:o.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,o=null){this.artifacts.clear();for(let n of t)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=o,this.emitArtifactsState()}trackCursor(t){let o=this.agentExecution?.executionId;if(!o||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let n=this.resumable===null;this.resumable={executionId:o,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(n)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=_x().then(({createReconnectController:t})=>{let o=t(this.buildReconnectHost());return this.reconnectController=o,o}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:o=>t.setStatus(o),setStreaming:o=>t.setStreaming(o),setReconnecting:o=>{t.reconnecting=o},setAbortController:o=>{t.abortController=o},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(o,n,r)=>t.connectStream(o,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:o=>t.appendMessage(o),nextSequence:()=>t.nextSequence(),emitReconnect:o=>t.callbacks.onReconnect?.(o),buildErrorContent:o=>sm(new Error(o),t.config.errorMessage),onError:o=>t.callbacks.onError?.(o)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let o=this.reopenTrailingAssistant();o||(o=Fr(),this.appendMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=o,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:o,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let o=this.messages[t];if(o.role==="assistant"&&!o.variant)return o.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),o.id;if(o.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let o=this.config.onExecutionState;if(o){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),o(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let o=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),o&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let n=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=om(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ll(t)}toggleReadAloud(t){let o=this.messages.find(a=>a.id===t);if(!o||o.role!=="assistant")return;let n=om(o.content||"");if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let o=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let o=this.ensureSequence(t),n=this.messages.findIndex(r=>r.id===o.id);if(n===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,a)=>{if(a!==n)return r;let i={...r,...o};r.agentMetadata?.askUserQuestionAnswered===!0&&o.agentMetadata&&(i.agentMetadata={...o.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&o.agentMetadata&&(i.agentMetadata={...i.agentMetadata??o.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let d=r.agentMetadata?.clientToolAnswer;if(d&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:d}),r.approval&&o.approval&&r.approval.id===o.approval.id){let m=r.approval,h=o.approval;i.approval={...m,...h,executionId:h.executionId||m.executionId,toolName:h.toolName||m.toolName,description:h.description||m.description,toolType:h.toolType??m.toolType,reason:h.reason??m.reason,parameters:h.parameters??m.parameters}}let c=o.toolCall?.name,u=o.agentMetadata?.executionId,p=o.toolCall?.id;if(c&&Nx(c)&&u&&p&&o.agentMetadata?.awaitingLocalTool===!0){let m=`${u}:${p}`,h=this.webMcpInflightKeys.has(m),y=this.webMcpResolvedKeys.has(m),C=r.toolCall?.name,A=r.agentMetadata?.executionId===u&&r.toolCall?.id===p&&C!==void 0&&Nx(C)&&r.toolCall?.status==="complete";(h||y||A)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((o,n)=>{let r=new Date(o.createdAt).getTime(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let i=o.sequence??0,d=n.sequence??0;return i!==d?i-d:o.id.localeCompare(n.id)})}};var _a=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var im=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var lm=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var cl=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var dm=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var cm=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var um=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var pm=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Na=[["path",{d:"M20 6 9 17l-5-5"}]];var ul=[["path",{d:"m6 9 6 6 6-6"}]];var fm=[["path",{d:"m15 18-6-6 6-6"}]];var mm=[["path",{d:"m9 18 6-6-6-6"}]];var Ws=[["path",{d:"m18 15-6-6-6 6"}]];var gm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var hm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var Ic=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Fa=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var ym=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Rc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Hc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var bm=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var vm=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var pl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var fl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Bs=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var ml=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var xm=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Cm=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Wc=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Sm=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var wm=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var Am=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var gl=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var Mm=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Tm=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Em=[["path",{d:"M5 12h14"}]];var Bc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]];var Pm=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var km=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Lm=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Im=[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]];var Rm=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Hm=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Wm=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Bm=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Om=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Oc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Dm=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var _m=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Nm=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Fm=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Um=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var qm=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Vm=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var $m=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var hl=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Ut=(e,t=24,o="currentColor",n=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(n)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let i=a[0],d=a[1];if(!d)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(d).forEach(([u,p])=>{u!=="stroke"&&c.setAttribute(u,String(p))}),r.appendChild(c)}),r};var{setLoader:QE,load:YE}=mt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),Fx=QE,Dc=YE;var JE={activity:_a,"arrow-down":im,"arrow-up":cm,"arrow-up-right":dm,bot:pm,"chevron-down":ul,"chevron-up":Ws,"chevron-right":mm,"chevron-left":fm,check:Na,clipboard:hm,"clipboard-copy":gm,"code-xml":Ic,copy:Fa,file:ml,"file-code":pl,"file-spreadsheet":fl,"file-text":Bs,"image-plus":Cm,loader:Sm,"loader-circle":Wc,mic:Mm,paperclip:Pm,quote:Im,"refresh-cw":Rm,search:Hm,send:Wm,"shield-alert":Bm,"shield-check":Om,"shield-x":Oc,square:Dm,"thumbs-down":Nm,"thumbs-up":Fm,upload:Vm,"volume-2":$m,x:hl,"at-sign":um,"arrow-left":lm,"arrow-right":cl,"external-link":bm,ellipsis:Hc,"ellipsis-vertical":Rc,menu:Am,"panel-left":Bc,plus:Lm,minus:Em,pencil:km,trash:qm,"trash-2":Um,download:ym,maximize:wm,minimize:Tm,"message-square":gl,star:_m,eye:vm,history:xm},ZE=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],yl=new Map(Object.entries(JE)),Ua=new Set,_c=!1,Nc=new Set,Ux=e=>{let t=[...Nc];e&&Nc.clear();for(let o of t)try{o()}catch{}},qx=e=>_c?()=>{}:(Nc.add(e),()=>{Nc.delete(e)}),Vx=()=>{let e=0;for(let t of[...Ua]){let o=yl.get(t.name);if(!o)continue;Ua.delete(t),e++;let n=Ut(o,t.size,t.color,t.strokeWidth);if(n)for(t.el.removeAttribute("data-persona-icon-pending");n.firstChild;)t.el.appendChild(n.firstChild)}return e},$x=e=>{for(let[t,o]of Object.entries(e))yl.set(t,o);Vx()>0&&!_c&&Ux(!1)};var jm=!1,e0=()=>{Dc().then(e=>{if(!_c){for(let[t,o]of Object.entries(e.EXTRA_LUCIDE_ICONS))yl.has(t)||yl.set(t,o);_c=!0,Vx(),Ux(!0)}}).catch(e=>{jm=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},t0=(e,t,o)=>{let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n},le=(e,t=24,o="currentColor",n=2)=>{let r=yl.get(e);if(r)return Ut(r,t,o,n);if(ZE.includes(e)){jm&&(jm=!1);let a=t0(t,o,n);if(Ua.size>=500){let i=Ua.values().next().value;i&&Ua.delete(i)}return Ua.add({el:a,name:e,size:t,color:o,strokeWidth:n}),e0(),a}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null};var o0={add:e=>fx(e)},n0=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Fc={allowedTypes:mr,maxFileSize:10*1024*1024,maxFiles:4};function r0(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function s0(e){return e==="application/pdf"?Bs:e.startsWith("text/")?Bs:e.includes("word")?Bs:e.includes("excel")||e.includes("spreadsheet")?fl:e==="application/json"?pl:ml}var Os=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??Fc.allowedTypes,maxFileSize:t.maxFileSize??Fc.maxFileSize,maxFiles:t.maxFiles??Fc.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:o0}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let o of this.attachments)this.renderPreview(o)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Fc.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.destroyed)return;let o=[];for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let r=mx(n,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,i);continue}let a={id:r0(),file:n,previewUrl:Pc(n)?URL.createObjectURL(n):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(a),this.renderPreview(a),o.push(a)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(o.map(n=>this.runAdd(n)))}async runAdd(t){let o=new AbortController;this.pendingAdds.set(t.id,o);let n=()=>this.destroyed||o.signal.aborted||this.pendingAdds.get(t.id)!==o||!this.attachments.includes(t);try{let r=await this.adapter().add(t.file,{signal:o.signal,onProgress:a=>{n()||t.status!=="uploading"||(t.progress=n0(a),this.updatePreview(t),this.notify())}});if(n())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(n())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(t.id)===o&&this.pendingAdds.delete(t.id)}this.updatePreview(t),this.notify()}retryAttachment(t){let o=this.attachments.find(n=>n.id===t);!o||o.status!=="error"||this.destroyed||(o.status=this.hasCustomAdapter()?"uploading":"processing",o.progress=this.hasCustomAdapter()?0:void 0,o.error=void 0,this.updatePreview(o),this.notify(),this.runAdd(o))}abortAdd(t){let o=this.pendingAdds.get(t);o&&(this.pendingAdds.delete(t),o.abort())}removeAttachment(t){let o=this.attachments.findIndex(a=>a.id===t);if(o===-1)return;let n=this.attachments[o];this.abortAdd(t),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(o,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),n.status==="ready"&&n.contentPart&&this.releasePart(n.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(t){let o=this.config.adapter?.remove;if(o)try{let n=o(t,{signal:new AbortController().signal});n&&typeof n.catch=="function"&&n.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(n){console.error("[AttachmentManager] adapter.remove failed:",n)}}clearAttachments(){for(let t of this.attachments)this.abortAdd(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let t of this.pendingAdds.values())t.abort();this.pendingAdds.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let o=Pc(t.file),n=H("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",t.id),n.style.width="48px",n.style.height="48px",o&&t.previewUrl){let p=H("img");p.src=t.previewUrl,p.alt=t.file.name,p.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",p.style.width="48px",p.style.height="48px",p.style.objectFit="cover",p.style.borderRadius="8px",n.appendChild(p)}else{let p=H("div");p.style.width="48px",p.style.height="48px",p.style.borderRadius="8px",p.style.backgroundColor="var(--persona-container, #f3f4f6)",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.display="flex",p.style.flexDirection="column",p.style.alignItems="center",p.style.justifyContent="center",p.style.gap="2px",p.style.overflow="hidden";let m=s0(t.file.type),h=Ut(m,20,"var(--persona-muted, #6b7280)",1.5);h&&p.appendChild(h);let y=H("span");y.textContent=gx(t.file.type,t.file.name),y.style.fontSize="8px",y.style.fontWeight="600",y.style.color="var(--persona-muted, #6b7280)",y.style.textTransform="uppercase",y.style.lineHeight="1",p.appendChild(y),n.appendChild(p)}let r=Q("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),a=H("div","persona-attachment-progress");a.appendChild(H("div","persona-attachment-progress__bar"));let i=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),d=le("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);d?i.appendChild(d):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(a,i),n.appendChild(r);let c=H("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let u=Ut(hl,10,"var(--persona-text-inverse, #ffffff)",2);u?c.appendChild(u):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),n.appendChild(c),this.previewsContainer.appendChild(n),this.applyPreviewState(n,t)}updatePreview(t){let o=this.previewsContainer?.querySelector(`[data-attachment-id="${t.id}"]`);o&&this.applyPreviewState(o,t)}applyPreviewState(t,o){t.dataset.status=o.status;let n=o.status!=="ready"&&o.status!=="error";t.setAttribute("aria-busy",n?"true":"false"),t.title=o.status==="error"?`${o.file.name}: ${o.error??"Upload failed"}`:o.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let a=o.progress;r.style.width=typeof a=="number"?`${Math.round(a*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,o){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:o,adapter:t?.adapter})}};var jx=(e,t)=>e.length===t.length&&e.every((o,n)=>o===t[n]),a0=(e,t)=>e.length===t.length&&e.every((o,n)=>{let r=t[n];return o.id===r.id&&o.name===r.name&&o.mimeType===r.mimeType&&o.size===r.size&&o.status===r.status&&o.progress===r.progress&&o.error===r.error});function zx(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,o=null,n=!1,r=!1,a=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let p=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:p,inputDisabled:e.inputDisabled,sendDisabled:p!=="idle"||e.sendDisabled||e.inputDisabled})},d=()=>(o||(o=i()),o),c=()=>{if(n=!1,r||t.size===0)return;let p=d();for(let m of[...t])try{m(p)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},u=()=>{o=null,!(r||n)&&(n=!0,queueMicrotask(c))};return{getState:d,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,u())},setAttachments:p=>{a0(e.attachments,p)||(e.attachments=[...p],u())},setMentionRefs:p=>{jx(e.mentionRefs,p)||(e.mentionRefs=[...p],u())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,u())},setActiveModeIds:p=>{jx(e.activeModeIds,p)||(e.activeModeIds=[...p],u())},setQuote:p=>{let m=e.quote;m?.text===p?.text&&m?.messageId===p?.messageId&&m?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,u())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,u())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,u())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,u())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,u())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,u())},flush:()=>{n&&c()},destroy:()=>{r=!0,n=!1,t.clear()}}}var Oo=(e,...t)=>{for(let o of t){let n=e.querySelector(o);if(n)return n}return null},Kx=(e,t)=>{let o=H("div",e);return o.setAttribute(t,""),o.setAttribute("data-persona-composer-synthesized",""),o.style.display="contents",o};function Gx(e,t={}){let o=Oo(e,"[data-persona-composer-form]"),n=Oo(e,"[data-persona-composer-input]");if(!o||!n){let E=`[Persona] composer surface is missing required element(s): ${[!o&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(o||n))throw new Error(E);return typeof console<"u"&&console.warn(E),null}let r={header:Oo(e,"[data-persona-composer-header]"),body:Oo(e,"[data-persona-composer-body]"),actionsStart:Oo(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Oo(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Oo(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Oo(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Oo(e,"[data-persona-composer-status]")},a=new Set,i=r.header;i||(a.add("header"),i=Kx("persona-widget-composer__header","data-persona-composer-header"),o.parentNode?o.parentNode.insertBefore(i,o):e.appendChild(i));let d=r.body??n.parentElement??o,c=(M,E,T,I,b)=>{if(E)return E;a.add(M);let S=Kx(T,I);return b.appendChild(S),S},u=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",o),p=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",o),m=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),h=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),y=[],C=(M,E)=>M.target===E.target&&M.type===E.type&&M.handler===E.handler,A=Oo(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:o,input:n,header:i,body:d,actionsStart:u,actionsEnd:p,suggestions:m,status:h,attachmentInput:A,attachmentPreviews:Oo(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Oo(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Oo(e,"[data-persona-composer-submit]")??void 0,micButton:Oo(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:r,addListener:(M,E,T,I)=>{M.addEventListener(E,T,I),y.push({target:M,type:E,handler:T,options:I})},removeListener:(M,E,T,I)=>{M.removeEventListener(E,T,I),y=y.filter(b=>!C(b,{target:M,type:E,handler:T}))},destroy:()=>{for(let M of y)M.target.removeEventListener(M.type,M.handler,M.options);y=[]}}}var qt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},ro=1e5,qa=ro+1;var i0=8,l0=8,zm=10,Xx=200,Qx=300,Yx=0,qc=e=>Math.max(0,e);function Jx(e){e.delayMs!==void 0&&(Xx=qc(e.delayMs)),e.skipDelayMs!==void 0&&(Qx=qc(e.skipDelayMs))}var d0=()=>Date.now()<Yx,c0=e=>{Yx=e>0?Date.now()+e:0},Uc=new WeakMap,Gm="data-persona-tooltip-suppressed",u0=e=>typeof e.closest=="function"&&e.closest(`[${Gm}]`)!==null;function Zx(e){Uc.get(e)?.hide()}var eC=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,p0=e=>{let t=e.getRootNode?.();return eC(t)?t:e.ownerDocument.body},Km=(e,t,o)=>Math.min(Math.max(e,t),Math.max(t,o)),f0=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function Jt(e){Uc.get(e.anchor)?.destroy();let{anchor:t,trigger:o=t,text:n,hint:r,enabled:a=!0,gap:i=i0,viewportPadding:d=l0}=e,c=()=>t.ownerDocument,u=()=>c().defaultView??window,p=null,m=null,h=null,y=null,C,A=!1,M=!1,E=!1,T=()=>(typeof n=="function"?n():n).trim(),I=()=>(typeof r=="function"?r():r??"").trim(),b=()=>qc(e.delayMs??Xx),S=()=>qc(e.skipDelayMs??Qx),x=()=>{C!==void 0&&(u().clearTimeout(C),C=void 0)},L=()=>{x();let ye=p!==null;y?.(),y=null,p?.remove(),p=null,m=null,h=null,ye&&c0(S())},N=()=>{if(!p)return;let ye=c(),Re=u(),be=t.getBoundingClientRect(),pe=p.getBoundingClientRect(),yt=ye.documentElement.clientWidth||Re.innerWidth,Pe=ye.documentElement.clientHeight||Re.innerHeight,q=yt-d-pe.width,Ue=be.left+be.width/2-pe.width/2,Je=Km(Ue,d,q),so=be.top-d,Le=Pe-d-be.bottom,qe=pe.height+i,ve=so>=qe||so>=Le?"top":"bottom",po=ve==="top"?be.top-i-pe.height:be.bottom+i,dn=Pe-d-pe.height,Vn=Km(po,d,dn),wt=be.left+be.width/2,$n=Math.max(zm,pe.width-zm),z=Km(wt-Je,zm,$n);p.dataset.placement=ve,p.style.left=`${Je}px`,p.style.top=`${Vn}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${z}px`)},X=()=>{if(E||!a||p||!t.isConnected||u0(t))return;let ye=T(),Re=p0(t);if(!ye||!Re)return;let be=c(),pe=u();p=be.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(qa);let yt=pe.getComputedStyle?.(t);if(yt){for(let qe of f0){let ve=yt.getPropertyValue(qe).trim();ve&&p.style.setProperty(qe,ve)}yt.fontFamily&&(p.style.fontFamily=yt.fontFamily)}m=be.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ye,p.appendChild(m);let Pe=I();Pe&&(h=be.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=Pe,p.appendChild(h));let q=be.createElement("span");q.className="persona-control-tooltip__arrow",p.appendChild(q),Re.appendChild(p),N(),p.dataset.state="open";let Ue=()=>{if(!t.isConnected){L();return}m&&(m.textContent=T()),h&&(h.textContent=I()),N()};pe.addEventListener("scroll",Ue,!0),pe.addEventListener("resize",Ue);let Je=t.getRootNode(),so=eC(Je)?Je:be.documentElement,Le=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||L()});Le?.observe(so,{childList:!0,subtree:!0}),y=()=>{pe.removeEventListener("scroll",Ue,!0),pe.removeEventListener("resize",Ue),Le?.disconnect()}},V=ye=>{if(!(E||p)){if(x(),ye||b()<=0||d0()){X();return}C=u().setTimeout(()=>{C=void 0,X()},b())}},P=()=>{A||M?V(M):L()},O=()=>{let ye=u();(!ye.matchMedia||!ye.matchMedia("(hover: none)").matches)&&(A=!0,P())},D=()=>{A=!1,P()},W=()=>{try{M=t.matches(":focus-visible")}catch{M=!0}P()},ee=()=>{M=!1,P()},G=()=>{A=!1,M=!1,L()},ue=ye=>{ye.key==="Escape"&&G()};o.addEventListener("mouseenter",O),o.addEventListener("mouseleave",D),t.addEventListener("focus",W),t.addEventListener("blur",ee),t.addEventListener("keydown",ue),t.addEventListener("click",G);let ae={get isOpen(){return p!==null},show:X,hide:L,reposition:N,destroy:()=>{E||(E=!0,L(),o.removeEventListener("mouseenter",O),o.removeEventListener("mouseleave",D),t.removeEventListener("focus",W),t.removeEventListener("blur",ee),t.removeEventListener("keydown",ue),t.removeEventListener("click",G),Uc.delete(t))}};return Uc.set(t,ae),ae}var tC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Va(e,t){if(!e)return t;if(!t)return e;let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];tC(a)&&tC(r)?o[n]=Va(a,r):o[n]=r}return o}var Ko="min(440px, calc(100vw - 24px))",Vc="440px",Xm="How can I help...",m0={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Ko,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:m0,copy:{inputPlaceholder:Xm,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function oC(e,t){if(!(!e&&!t))return e?t?Va(e,t):e:t}function $a(e){return e?{...rt,...e,theme:oC(rt.theme,e.theme),darkTheme:oC(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...rt.tooltip,...e.tooltip},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,o=e.features?.artifacts,n=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,a=rt.features?.scrollBehavior,i=e.features?.scrollBehavior,d=rt.features?.streamAnimation,c=e.features?.streamAnimation,u=rt.features?.askUserQuestion,p=e.features?.askUserQuestion,m=rt.features?.history,h=e.features?.history,y=t===void 0&&o===void 0?void 0:{...t,...o,layout:{...t?.layout,...o?.layout}},C=n===void 0&&r===void 0?void 0:{...n,...r},A=a===void 0&&i===void 0?void 0:{...a,...i},M=d===void 0&&c===void 0?void 0:{...d,...c},E=u===void 0&&p===void 0?void 0:{...u,...p,styles:{...u?.styles,...p?.styles}},T=m===void 0&&h===void 0?void 0:{...m,...h,copy:{...m?.copy,...h?.copy}};return{...rt.features,...e.features,...C!==void 0?{scrollToBottom:C}:{},...A!==void 0?{scrollBehavior:A}:{},...y!==void 0?{artifacts:y}:{},...M!==void 0?{streamAnimation:M}:{},...E!==void 0?{askUserQuestion:E}:{},...T!==void 0?{history:T}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}function Qm(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let o=t.getComputedStyle(e).lineHeight;if(!o||!o.trim().endsWith("px"))return 20;let n=parseFloat(o);return Number.isFinite(n)&&n>0?n:20}function $c(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function nC(e,t){e.style.maxHeight=`${t*Qm(e)}px`,e.style.overflowY="auto"}function xl(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function rC(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function sC(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let o=e.metaKey===!0||e.ctrlKey===!0,n=t.submitKey??"enter";return n==="none"?!1:n==="mod-enter"?o:o||!rC(t)}function g0(e){return(e.submitKey??"enter")!=="enter"||rC(e)?"enter":"send"}function jc(e,t){e.setAttribute("enterkeyhint",g0(t))}function zc(e,t){let o=t?.autocomplete;e.setAttribute("autocomplete",typeof o=="string"&&o?o:"off");let n=(r,a)=>{a===void 0?e.removeAttribute(r):e.setAttribute(r,a)};n("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),n("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),n("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),n("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Ym(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var Go="persona-composer-control",xn="persona-composer-control--glyph",Zm=40,bo=24,Kc=(e,t,o)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let r=n.getComputedStyle(e);for(let a of o){let i=r.getPropertyValue(a).trim();i?t.style.setProperty(a,i):t.style.removeProperty(a)}},Gc=(e,t)=>{let o=H("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=e?.copy?.inputPlaceholder??Xm,o.dir="auto",jc(o,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:xl(o)}),zc(o,e?.composer?.inputAttributes),o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=$c(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${n*20}px`;o.style.maxHeight=r,o.style.overflowY="auto";let a=()=>{let d=o.style.maxHeight;if(d!==r){let u=parseFloat(d);if(Number.isFinite(u)&&u>0)return u}let c=n*Qm(o);return r=`${c}px`,o.style.maxHeight=r,c},i=()=>{o.addEventListener("input",()=>{o.style.height="auto";let d=Math.min(o.scrollHeight,a());o.style.height=`${d}px`})};return o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"}),{textarea:o,attachAutoResize:i}},y0="[data-persona-glyph-stack]",eg=(e,t,o="send")=>{let n=Q("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":o,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},Xc=e=>{let t=e?.sendButton??{},o=t.useIcon??!1,n=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",i=t.tooltipText??"Send message",d=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",u=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,m=t.size,h=parseFloat(m??"")||Zm,y=t.backgroundColor,C=t.textColor,A=H("div","persona-send-button-wrapper"),M=Q("button",{className:yo("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?`persona-flex persona-items-center persona-justify-center ${Go}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",o&&!y&&"persona-bg-persona-primary",!o&&!C&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:o?m:void 0,height:o?m:void 0,minWidth:o?m:void 0,minHeight:o?m:void 0,fontSize:o?"18px":void 0,lineHeight:o?"1":void 0,color:o?C||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":C||void 0,backgroundColor:o&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:o?"0":t.paddingX||void 0,paddingRight:o?"0":t.paddingX||void 0,paddingTop:o?"0":t.paddingY||void 0,paddingBottom:o?"0":t.paddingY||void 0}}),E=null,T=null,I=null;if(o){let x=parseFloat(t.iconSize??"")||Math.round(h*.5),L=t.iconStrokeWidth??2,N=C?.trim()||"currentColor";r&&(E=le(r,x,N,L)),T=le(a,x,N,L),E&&T?(I=eg(E,T),M.appendChild(I)):E?M.appendChild(E):(M.textContent=n,T=null)}else M.textContent=c;M.setAttribute("aria-label",i),A.appendChild(M),Jt({anchor:M,trigger:A,text:()=>M.getAttribute("aria-label")??"",enabled:p});let b="send";return{button:M,wrapper:A,setMode:x=>{if(x===b)return;b=x;let L=x==="stop"?d:i;M.setAttribute("aria-label",L),M.setAttribute("data-persona-send-mode",x),o?(M.querySelector(y0)??I)?.setAttribute("data-mode",x):M.textContent=x==="stop"?u:c},glyphStack:I}},ja=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let n=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",a=t.provider?.type==="custom";if(!(n||r||a))return null;let d=t.iconName??"mic",c=t.iconSize,u=parseFloat(c??"")||bo,p=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,h=H("div","persona-send-button-wrapper"),y=Q("button",{className:yo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Go,!c&&xn),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),A=le(d,u,m||"currentColor",1.5);A?y.appendChild(A):y.textContent="\u{1F3A4}",h.appendChild(y);let M=t.tooltipText??"Start voice recognition",E=t.showTooltip??!1;return Jt({anchor:y,trigger:h,text:()=>y.getAttribute("aria-label")??M,enabled:E}),{button:y,wrapper:h}},Qc=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let o=H("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=H("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??mr).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",a=H("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Go} ${xn}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),d=le(r,bo,"currentColor",1.5);d?i.appendChild(d):i.textContent="\u{1F4CE}",i.addEventListener("click",u=>{u.preventDefault(),n.click()}),a.appendChild(i);let c=t.buttonTooltipText??"Attach file";return Jt({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:a,input:n,previewsContainer:o}},Yc=e=>{let t=e?.statusIndicator??{},o=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",n=H("div",`persona-mt-2 ${o} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let r=t.visible??!0;n.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let i=H("a");i.href=t.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=a,i.style.color="inherit",i.style.textDecoration="none",n.appendChild(i)}else n.textContent=a;return n},Jc=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function b0(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Zc(e){let{anchor:t,content:o,placement:n="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:i,verticalOffset:d,zIndex:c=2147483e3,onOpen:u,onDismiss:p}=e,m=e.container??b0(t),h=!1,y=null,C=()=>{if(!h)return;let E=t.getBoundingClientRect();o.style.position="fixed",a&&(o.style.minWidth=`${E.width}px`),i&&(o.style.maxWidth=`${E.width}px`);let T=o.getBoundingClientRect(),I=d?.()??null,b=I!=null?E.top+I:E.top,S=n==="top-start"||n==="top-end"?b-r-T.height:E.bottom+r,L=n==="bottom-end"||n==="top-end"?E.right-T.width:E.left,N=i?.()??null;if(N!=null){let X=Math.max(E.left,E.right-T.width);L=Math.min(Math.max(E.left+N,E.left),X)}o.style.top=`${S}px`,o.style.left=`${L}px`},A=()=>{h&&(h=!1,y&&(y(),y=null),o.remove())},M=()=>{if(h)return;h=!0,c!=null&&(o.style.zIndex=String(c)),m.appendChild(o),C();let E=(t.ownerDocument??document).defaultView??window,T=t.ownerDocument??document,I=()=>{if(!t.isConnected){A(),p?.("anchor-removed");return}C()},b=x=>{let L=typeof x.composedPath=="function"?x.composedPath():[];L.includes(o)||L.includes(t)||(A(),p?.("outside"))},S=E.setTimeout(()=>{T.addEventListener("pointerdown",b,!0)},0);E.addEventListener("scroll",I,!0),E.addEventListener("resize",I),y=()=>{E.clearTimeout(S),T.removeEventListener("pointerdown",b,!0),E.removeEventListener("scroll",I,!0),E.removeEventListener("resize",I)},u?.()};return{get isOpen(){return h},open:M,close:A,toggle:()=>h?A():M(),reposition:C,destroy:A}}var v0='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',x0=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],tg="data-persona-menu-focus",C0=new Set(["ArrowDown","ArrowUp","Home","End"]);function aC(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(v0)??e}var S0=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function iC(e){let t=e.label,o=!1,n=H("div","persona-send-button-wrapper"),r=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Go} ${xn}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(r);let a=Q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let W=e.getButtonSize?.()??"";r.style.width=W,r.style.height=W,r.style.minWidth=W,r.style.minHeight=W,r.style.lineHeight="1",r.replaceChildren();let ee=le("plus",bo,"currentColor",1.5);ee?r.appendChild(ee):r.textContent="+"},d=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),a.setAttribute("aria-label",t)};d(),i();let c=[],u=-1,p=!1,m=()=>{let ee=a.getRootNode().activeElement;return ee instanceof HTMLElement?ee:null},h=()=>{let W=m();for(let ee of c){let G=!!W&&aC(ee)===W;ee.toggleAttribute(tg,G&&p)}},y=()=>c.filter(W=>W.isConnected||a.contains(W)).map(aC).filter(W=>!S0(W)),C=(W,ee)=>{W.forEach((G,ue)=>{G.setAttribute("tabindex",ue===ee?"0":"-1")})},A=W=>{let ee=y();if(ee.length===0)return;let G=(W%ee.length+ee.length)%ee.length;u=G,C(ee,G),ee[G].focus(),h()},M=()=>n.ownerDocument??document,E=null,T=null,I=null,b=()=>{E&&(M().removeEventListener("focusin",E,!0),E=null)},S=()=>{T&&(a.removeEventListener("focusin",T),T=null),I&&(a.removeEventListener("pointerdown",I,!0),I=null)},x=null,L=()=>(x||(x=Zc({anchor:r,content:a,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),b()}})),x),N=()=>x?.isOpen===!0,X=(W=!1)=>{if(N()){x?.close(),r.setAttribute("aria-expanded","false"),b(),S(),u=-1,p=!1;for(let ee of c)ee.removeAttribute(tg);W&&r.focus()}},V=(W=0,ee=!1)=>{if(o||N())return;p=ee,Kc(r,a,x0),L().open(),r.setAttribute("aria-expanded","true");let G=y();C(G,-1),A(W<0?G.length-1:W),E=ue=>{let ae=typeof ue.composedPath=="function"?ue.composedPath():[];ae.includes(a)||ae.includes(n)||X()},M().addEventListener("focusin",E,!0),T=()=>h(),a.addEventListener("focusin",T),I=()=>{p=!1},a.addEventListener("pointerdown",I,!0)},P=W=>{W.preventDefault(),W.stopPropagation(),N()?X(!0):V(0)},O=W=>{if(W.key==="ArrowDown"||W.key==="Enter"||W.key===" "){W.preventDefault(),p=!0,N()?A(0):V(0,!0);return}W.key==="ArrowUp"&&(W.preventDefault(),p=!0,N()?A(-1):V(-1,!0))},D=W=>{switch(C0.has(W.key)&&(p=!0),W.key){case"ArrowDown":W.preventDefault(),A(u+1);return;case"ArrowUp":W.preventDefault(),A(u-1);return;case"Home":W.preventDefault(),A(0);return;case"End":W.preventDefault(),A(y().length-1);return;case"Escape":W.preventDefault(),W.stopPropagation(),X(!0);return;case"Tab":X(!0);return;default:}};return r.addEventListener("click",P),r.addEventListener("keydown",O),a.addEventListener("keydown",D),{trigger:n,triggerButton:r,panel:a,setItems:W=>{for(let G of c)W.includes(G)||G.removeAttribute(tg);if(c=[...W],!N())return;let ee=y();C(ee,Math.min(u,ee.length-1)),h()},isOpen:N,open:()=>V(0),close:X,setLabel:W=>{W!==t&&(t=W,d())},applyButtonSize:i,destroy:()=>{o=!0,b(),S(),r.removeEventListener("click",P),r.removeEventListener("keydown",O),a.removeEventListener("keydown",D),x?.destroy(),x=null,n.remove(),a.remove(),c=[]}}}var Fn={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},lC="data-persona-composer-action",og="data-persona-composer-disable-when-streaming",w0="core:overflow",A0=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function M0(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let o=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(o))return o;let n=H("div");n.style.position="absolute",n.style.visibility="hidden",n.style.pointerEvents="none",n.style.height="0",n.style.width=e,t.appendChild(n);let r=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(o)?o:null}function ng(e){let t=e.clientWidth;if(!t)return 0;let o=e.ownerDocument?.defaultView;if(!o?.getComputedStyle)return t;let n=o.getComputedStyle(e),r=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-r)}var dC=(e,t)=>{!e||typeof console>"u"||console.warn(t)},T0=(e,t)=>t.includes(":")?t:`${e}:${t}`;function E0(e){let{debug:t}=e,o=[],n=new Map,r=0,a=d=>{let c=n.get(d.id);if(c){dC(t,`[Persona] composer action "${d.id}" is already contributed by ${cC(c)}; the ${cC(d)} copy is ignored.`);return}n.set(d.id,d),o.push(d)};for(let d of e.builtIns)a({id:d.id,placement:d.placement,presentation:"bar",order:d.order,sequence:r++,source:"core",builtIn:d});let i=(d,c,u)=>{let p=u?T0(u,d.id):d.id,m=d.order??Fn.custom;d.placement==="end"&&m>=Fn.send&&(dC(t,`[Persona] composer action "${p}" ordered at ${m} would render after send; clamped to ${Fn.send-1}.`),m=Fn.send-1),a({id:p,placement:d.placement,presentation:d.presentation??"bar",order:m,sequence:r++,source:c,pluginId:u,action:d})};for(let d of e.configActions??[])i(d,"config");for(let d of e.plugins){if(!d.contributeComposerActions)continue;let c;try{c=d.contributeComposerActions(e.contributionContext)}catch(u){typeof console<"u"&&console.error(`[Persona] plugin "${d.id}" contributeComposerActions failed:`,u);continue}for(let u of c??[])i(u,"plugin",d.id)}return o.sort((d,c)=>d.order===c.order?d.sequence-c.sequence:d.order-c.order)}var cC=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",uC=(e,t,o)=>e===void 0?o:typeof e=="function"?e(t)===!0:e===!0,P0=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function k0(e,t){if(!e||e==="always")return!0;let o=P0(t);return e==="when-text"?o:!o}var zr=e=>e.kind==="custom",rg=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,L0=e=>{let t=rg(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},I0='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function R0(e){let t="",o=n=>{if(n.nodeType===Node.TEXT_NODE){t+=n.nodeValue??"";return}if(n.nodeType!==Node.ELEMENT_NODE)return;let r=n;typeof r.matches=="function"&&r.matches(I0)||n.childNodes.forEach(o)};return o(e),t.trim()}var H0=e=>R0(e).length===0;function pC(e){let t=new Map,o=[],n=!1,r=()=>e.getButtonSize?.(),a=(P,O)=>{let D=P.button;if(!D)return;D.setAttribute("role","menuitem"),D.setAttribute("tabindex","-1"),D.className="persona-composer-overflow-menu__item";for(let G of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])D.style[G]="";D.style.lineHeight="1",O.tooltipText?D.setAttribute("title",O.tooltipText):D.removeAttribute("title"),D.replaceChildren();let W=H("span","persona-composer-overflow-menu__icon");if(O.iconName){let G=le(O.iconName,16,"currentColor",1.5);G&&W.appendChild(G)}let ee=H("span","persona-composer-overflow-menu__label");ee.textContent=O.shortLabel??O.label,D.append(W,ee)},i=(P,O)=>{let D=P.button;if(!D)return;if(D.setAttribute("aria-label",O.label),O.pressed===void 0?D.removeAttribute("aria-pressed"):D.setAttribute("aria-pressed",O.pressed?"true":"false"),D.toggleAttribute(og,O.disableWhenStreaming===!0),P.mode==="menu"){P.tooltip?.destroy(),P.tooltip=void 0,a(P,O);return}D.removeAttribute("role"),D.removeAttribute("tabindex"),D.removeAttribute("title");let W=r(),ee=!!O.shortLabel;if(D.className=yo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Go,xn,ee&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),D.style.width=W&&!ee?W:"",D.style.height=W??"",D.style.minWidth=W&&!ee?W:"",D.style.minHeight=W??"",D.style.fontSize=ee?"":"18px",D.style.lineHeight="1",D.style.color=O.iconColor??"",D.style.backgroundColor=O.backgroundColor??"",D.replaceChildren(),O.iconName){let G=le(O.iconName,bo,"currentColor",1.5);G&&D.appendChild(G)}if(ee){let G=H("span","persona-composer-action-button__label");G.textContent=O.shortLabel,D.appendChild(G)}else D.firstChild||(D.textContent=O.label);P.tooltip?.destroy(),P.tooltip=Jt({anchor:D,trigger:P.element,text:()=>O.tooltipText??O.label,enabled:!!O.tooltipText})},d=(P,O)=>{let D=P.action,W=Q("button",{attrs:{type:"button"}}),ee=W;if(O==="bar"){let ae=H("div","persona-send-button-wrapper");ae.appendChild(W),ee=ae}ee.setAttribute(lC,P.id);let G={resolved:P,element:ee,button:W,owned:!0,managed:!0,busy:!1,visible:!0,mode:O},ue=ae=>{if(ae.preventDefault(),ae.stopPropagation(),G.busy||W.disabled)return;let ye=G.resolved.action;G.mode==="menu"&&y?.close(!0);let Re;try{Re=ye.onSelect(e.actionContext,ae)}catch(be){e.reportError(be,{actionId:G.resolved.id});return}!Re||typeof Re.then!="function"||(G.busy=!0,W.setAttribute("aria-busy","true"),Re.catch(be=>{e.reportError(be,{actionId:G.resolved.id})}).finally(()=>{G.busy=!1,W.removeAttribute("aria-busy")}))};return W.addEventListener("click",ue),G.detach=()=>W.removeEventListener("click",ue),i(G,D),G},c=P=>{let O=P.action,D;try{D=O.render({...e.actionContext,id:P.id,action:O})}catch(W){return e.reportError(W,{actionId:P.id}),null}return D?.element?(D.element.setAttribute(lC,P.id),D.element.toggleAttribute(og,O.disableWhenStreaming===!0),{resolved:P,element:D.element,owned:!0,managed:!0,destroy:D.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(P,O)=>{if(P.builtIn){let W=P.builtIn.element;return W?{resolved:P,element:W,owned:!1,managed:P.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let D=P.action;return D?zr(D)?c(P):d(P,O):null},p=P=>{if(P.detach?.(),P.tooltip?.destroy(),P.detachMenuSlot?.(),P.detachMenuSlot=void 0,P.menuLabel?.remove(),P.menuLabel=void 0,P.menuSlot?.remove(),P.menuSlot=void 0,P.owned){try{P.destroy?.()}catch(O){e.reportError(O,{actionId:P.resolved.id})}P.element.remove()}},m=(P,O)=>{for(let D=0;D<O.length;D++){let W=O[D];if(!W.managed)continue;let ee=null;for(let G=D+1;G<O.length;G++){let ue=O[G];if(!ue.managed&&ue.element.parentElement===P){ee=ue.element;break}}ee?(W.element.parentElement!==P||W.element.nextSibling!==ee)&&P.insertBefore(W.element,ee):P.lastChild!==W.element&&P.appendChild(W.element)}},h=(P,O)=>{if(P.button){P.button.disabled=O;return}if(!P.owned)return;let D=P.element;D.toggleAttribute("data-disabled",O),D.setAttribute("aria-disabled",O?"true":"false");let W=D instanceof HTMLButtonElement||D instanceof HTMLSelectElement||D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement?D:D.querySelector("button, select, input, textarea");W&&(W.disabled=O)},y=null,C=null,A=null,M=0,E=()=>{let P=e.getOverflow?.();return P?.enabled===!0?P:void 0},T=()=>(y?y.setLabel(e.getOverflowLabel?.()??"More actions"):y=iC({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),y),I=P=>{C!==P&&(A?.disconnect(),C=P,M=ng(P),!(typeof ResizeObserver>"u")&&(A=new ResizeObserver(O=>{let W=O[O.length-1]?.contentRect?.width??ng(P);W!==M&&(M=W,X())}),A.observe(P)))},b=(P,O)=>{let D=M0(P.collapseAutoActionsBelow,O);if(D===null)return!1;let W=M||ng(O);return W>0&&W<D},S=(P,O,D)=>{if(!O)return"bar";if(P.resolved.builtIn){let ee=A0(P.resolved.id);return ee&&O.includeBuiltIns?.includes(ee)?"menu":"bar"}let W=P.resolved.presentation;return W==="overflow"||W==="auto"&&D?"menu":"bar"},x=P=>{let O=P.menuSlot;if(!O)return;if(!H0(P.element)){P.menuLabel?.remove(),P.menuLabel=void 0;return}let D=L0(P.element);if(!D){P.menuLabel?.remove(),P.menuLabel=void 0;return}P.menuLabel||(P.menuLabel=H("span","persona-composer-overflow-menu__label")),P.menuLabel.textContent!==D&&(P.menuLabel.textContent=D),P.menuLabel.parentElement!==O&&O.appendChild(P.menuLabel)},L=(P,O)=>{if(P.mode===O)return P;let D=P.resolved.action;if(D&&!zr(D)){p(P),t.delete(P.resolved.id);let W=d(P.resolved,O);return t.set(P.resolved.id,W),W}if(O==="menu"){let W=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Gm]:""}});W.appendChild(P.element),Zx(rg(P.element)),P.menuSlot=W;let ee=G=>{let ue=rg(P.element);if(ue.disabled)return;let ae=G.target===ue||ue.contains(G.target);y?.close(!0),ae||ue.click()};W.addEventListener("click",ee,!0),P.detachMenuSlot=()=>W.removeEventListener("click",ee,!0),P.managed=!0,x(P)}else P.detachMenuSlot?.(),P.detachMenuSlot=void 0,P.menuLabel?.remove(),P.menuLabel=void 0,P.menuSlot?.remove(),P.menuSlot=void 0;return P.mode=O,P},N=(P,O)=>{let D=O.map(W=>W.menuSlot??W.element);for(D.forEach((W,ee)=>{let G=P.children[ee];G!==W&&(G?P.insertBefore(W,G):P.appendChild(W))});P.children.length>D.length;)P.lastElementChild?.remove()},X=()=>{if(n)return;let P=e.getBindings();if(!P)return;let O=e.getState(),D=O.phase==="streaming",W=E();W&&I(P.footer);let ee=W?b(W,P.footer):!1,G={start:[],end:[]},ue=[];for(let ae of o){let ye=t.get(ae.id);if(!ye)continue;let Re=ae.action,be=Re?uC(Re.visible,O,!0)&&k0(Re.visibility,O):!0;if(ye.visible!==be&&(ye.visible=be,!be&&ye.managed&&(ye.menuSlot??ye.element).remove()),!!be){if(ye=L(ye,S(ye,W,ee)),Re){let pe=uC(Re.disabled,O,!1)||Re.disableWhenStreaming===!0&&D;h(ye,pe),!zr(Re)&&Re.pressed!==void 0&&ye.button?.setAttribute("aria-pressed",Re.pressed?"true":"false")}ye.mode==="menu"?(x(ye),ue.push(ye)):G[ae.placement].push(ye)}}if(ue.length>0){let ae=T();N(ae.panel,ue),ae.setItems(ue.map(pe=>pe.menuSlot??pe.element)),ae.applyButtonSize();let ye=Number.isFinite(W?.order)?W?.order:Fn.overflow,Re=G.start.findIndex(pe=>pe.resolved.order>ye),be={resolved:{id:w0,placement:"start",presentation:"bar",order:ye,sequence:-1,source:"core"},element:ae.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};G.start.splice(Re<0?G.start.length:Re,0,be)}else y&&(y.close(),y.trigger.remove(),y.setItems([]));m(P.actionsStart,G.start),m(P.actionsEnd,G.end)};return{resolve:()=>{if(n)return;let P=E0(e.collect()),O=new Set(P.map(D=>D.id));for(let[D,W]of t)O.has(D)||(p(W),t.delete(D));for(let D of P){let W=t.get(D.id);if(!W){let ae=u(D,"bar");ae&&t.set(D.id,ae);continue}let ee=W.resolved.action,G=D.action;if(!!ee!=!!G||ee&&G&&zr(ee)!==zr(G)||ee&&G&&zr(ee)&&zr(G)&&ee.render!==G.render){p(W),t.delete(D.id);let ae=u(D,W.mode);ae&&t.set(D.id,ae);continue}W.resolved=D,D.builtIn?(W.managed=D.builtIn.managed===!0||W.mode==="menu",D.builtIn.element&&W.mode==="bar"&&(W.element=D.builtIn.element)):G&&!zr(G)?i(W,G):G&&W.element.toggleAttribute(og,G.disableWhenStreaming===!0)}o=P,X()},sync:X,getResolved:()=>o,getOverflowMenu:()=>y,destroy:()=>{if(!n){n=!0,A?.disconnect(),A=null,C=null;for(let P of t.values())p(P);t.clear(),y?.destroy(),y=null,o=[]}}}}var W0="core:model",B0=700,fC=16,O0=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],mC=()=>{let e=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function gC(e){let t=e.label??"Model",o=e.presentation??"native",n=null,r=c=>{let u=e.getSelectedModelId();return c.find(p=>p.id===u)??c[0]},a=()=>{let c=Q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),u="",p=()=>{let A=e.getModels(),M=A.map(E=>`${E.id}:${E.label}`).join("|");M!==u&&(u=M,c.replaceChildren(...A.map(E=>{let T=Q("option",{attrs:{value:E.id}});return T.textContent=E.label,T}))),c.value=r(A)?.id??""};p(),n=p;let m=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",m);let h=A=>A.stopPropagation();c.addEventListener("click",h);let{wrapper:y,chevron:C}=mC();return y.append(c,C),{element:y,destroy:()=>{n===p&&(n=null),c.removeEventListener("change",m),c.removeEventListener("click",h)}}},i=()=>{let c=Q("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),u=H("span","persona-composer-model-picker-label"),p=H("span","persona-composer-model-picker-suffix");c.append(u,p);let m=Q("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),h=new Map,y="",C=null,A=()=>C?.isOpen===!0,M=(O=!1)=>{A()&&(C?.close(),c.setAttribute("aria-expanded","false"),O&&c.focus())},E=O=>{let D=[...h.values()];if(D.length===0)return;let W=(O%D.length+D.length)%D.length;D[W].focus()},T=O=>{if(A())return;C||(C=Zc({anchor:c,content:m,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Kc(c,m,O0),C.open(),c.setAttribute("aria-expanded","true");let W=[...h.keys()].indexOf(r(e.getModels())?.id??"");E(O??(W>=0?W:0))},I=O=>{M(!0),e.onSelect(O)},b=O=>{O.preventDefault(),O.stopPropagation();let D=O.currentTarget.getAttribute("data-persona-model-option");D&&I(D)},S=O=>{let D=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":O.id}});if(O.icon){let ae=le(O.icon,fC,"currentColor",1.5);if(ae){let ye=H("span","persona-composer-model-option-icon");ye.appendChild(ae),D.appendChild(ye)}}let W=H("span","persona-composer-model-option-body"),ee=H("span","persona-composer-model-option-label");if(ee.textContent=O.label,W.appendChild(ee),O.description){let ae=H("span","persona-composer-model-option-description");ae.textContent=O.description,W.appendChild(ae)}D.appendChild(W);let G=H("span","persona-composer-model-option-check");G.setAttribute("aria-hidden","true");let ue=le("check",fC,"currentColor",2);return ue&&G.appendChild(ue),D.appendChild(G),D.addEventListener("click",b),D},x=()=>{let O=e.getModels(),D=O.map(G=>`${G.id}:${G.label}:${G.icon??""}:${G.description??""}`).join("|");if(D!==y){y=D;for(let G of h.values())G.removeEventListener("click",b);h.clear(),m.replaceChildren(...O.map(G=>{let ue=S(G);return h.set(G.id,ue),ue}))}let W=r(O);for(let[G,ue]of h)ue.setAttribute("aria-selected",String(G===W?.id));u.textContent=W?.label??"";let ee=e.getSuffix?.()??"";p.textContent=ee,c.setAttribute("aria-label",[t,[W?.label,ee].filter(Boolean).join(" ")].filter(Boolean).join(": "))};x(),n=x;let L=O=>{O.preventDefault(),O.stopPropagation(),A()?M(!0):T()},N=O=>{if(O.key==="ArrowDown"){O.preventDefault(),A()?E(0):T(0);return}O.key==="ArrowUp"&&(O.preventDefault(),A()?E(-1):T(-1))},X=O=>{let D=[...h.values()],W=D.indexOf(O.target?.closest?.(".persona-composer-model-option"));switch(O.key){case"ArrowDown":O.preventDefault(),E(W+1);return;case"ArrowUp":O.preventDefault(),E(W-1);return;case"Home":O.preventDefault(),E(0);return;case"End":O.preventDefault(),E(D.length-1);return;case"Escape":O.preventDefault(),O.stopPropagation(),M(!0);return;case"Tab":M(!0);return;default:}};c.addEventListener("click",L),c.addEventListener("keydown",N),m.addEventListener("keydown",X);let{wrapper:V,chevron:P}=mC();return V.append(c,P),{element:V,destroy:()=>{n===x&&(n=null),c.removeEventListener("click",L),c.removeEventListener("keydown",N),m.removeEventListener("keydown",X);for(let O of h.values())O.removeEventListener("click",b);h.clear(),C?.destroy(),C=null,m.remove()}}};return{action:{id:W0,kind:"custom",placement:"end",order:B0,presentation:o==="popover"?"bar":"auto",label:t,render:()=>o==="popover"?i():a()},repaint:()=>n?.()}}var sg="[data-persona-composer-chip-row]";function eu(e){e.style.display=e.childElementCount>0?"flex":"none"}function ag(e){let t=e.querySelector(sg);if(t)return t;let o=Q("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});o.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(o,n):e.appendChild(o),o}var D0=":scope > [data-persona-composer-mode]";function hC(e){let t=e.row,o="",n=!1,r=new Set(e.initialIds??[]),a=u=>{let p=Q("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let C=H("span","persona-mention-chip-icon"),A=le(u.iconName,12,"currentColor",1.5);A&&C.appendChild(A),p.appendChild(C)}let m=H("span","persona-mention-chip-label");m.textContent=u.shortLabel??u.label,p.appendChild(m);let h=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),y=le("x",12,"currentColor",2);return y?h.appendChild(y):h.textContent="\xD7",h.addEventListener("click",C=>{C.preventDefault(),C.stopPropagation(),e.onRemove(u.id)}),p.appendChild(h),p},i=()=>Array.from(t.querySelectorAll(D0)),d=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let p=()=>{u.remove(),eu(t)},m=t.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(u).animationName:"";if(!h||h==="none"){p();return}u.addEventListener("animationend",p,{once:!0}),u.addEventListener("animationcancel",p,{once:!0})},c=()=>{for(let u of i())u.remove()};return{element:t,render:(u,p)=>{if(n)return;let m=p.filter(A=>u.includes(A.id)),h=m.map(A=>`${A.id}:${A.shortLabel??A.label}`).join("|");if(h===o)return;o=h;let y=new Map;for(let A of i()){let M=A.getAttribute("data-persona-composer-mode");M&&m.some(T=>T.id===M)&&!A.hasAttribute("data-persona-chip-exit")?y.set(M,A):A.hasAttribute("data-persona-chip-exit")||d(A)}let C=t.firstChild;for(let A of m){let M=y.get(A.id);M||(M=a(A),r.has(A.id)||(M.setAttribute("data-persona-chip-enter",""),M.addEventListener("animationend",()=>M?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(A.id),M!==C&&t.insertBefore(M,C),C=M.nextSibling}eu(t)},destroy:()=>{n=!0,c(),eu(t)}}}var yC=e=>`core:mode:${e}`;var ig=e=>Math.min(300+e,499),bC=e=>`core:mode-group:${e}`;function tu(e,t){return e?t?.find(o=>o.id===e)?.presentation==="segmented":!1}function _0(e,t){return e?t?.find(o=>o.id===e)?.chipVisibility==="hidden":!1}function vC(e,t){return e?.length?e.filter(o=>!tu(o.groupId,t)&&!_0(o.groupId,t)):[]}var N0=(e,t)=>e.groupId?t?.find(o=>o.id===e.groupId)?.selection??null:null;function xC(e,t,o,n){let r=o.find(d=>d.id===t);if(!r)return[...e];let a=e.includes(t),i=new Set(e);if(a)i.delete(t);else{if(N0(r,n)==="single"){let d=o.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!d.includes(c)))}i.add(t)}return o.filter(d=>i.has(d.id)).map(d=>d.id)}function ou(e,t){return t?.length?t.filter(o=>e.includes(o.id)).map(o=>o.id):[]}function CC(e,t){return t?.length?t.filter(o=>e.includes(o.id)&&(o.persistence??"sticky")!=="once").map(o=>o.id):[]}function SC(e,t){if(!(!t?.length||e.length===0))return t.find(o=>e.includes(o.id)&&o.placeholder)?.placeholder}var F0=16;function wC(e){let t=null;return{action:{id:bC(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let n=Q("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,a="",i=u=>{u.preventDefault(),u.stopPropagation();let m=u.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},d=u=>{let p=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let h=le(u.iconName,F0,"currentColor",1.5);h&&p.appendChild(h)}let m=H("span","persona-composer-segmented-label");return m.textContent=u.shortLabel??u.label,p.appendChild(m),p.addEventListener("click",i),p},c=()=>{let u=e.getGroup();u?.label?(n.setAttribute("role","group"),n.setAttribute("aria-label",u.label)):(n.removeAttribute("role"),n.removeAttribute("aria-label"));let p=e.getModes(),m=p.map(y=>`${y.id}:${y.shortLabel??y.label}:${y.iconName??""}`).join("|");if(m!==a){a=m;for(let C of r.values())C.removeEventListener("click",i);r.clear();let y=p.map(C=>{let A=d(C);return r.set(C.id,A),A});n.replaceChildren(...y)}let h=e.getActiveIds();for(let[y,C]of r)C.setAttribute("aria-pressed",String(h.includes(y)))};return c(),t=c,{element:n,destroy:()=>{t===c&&(t=null);for(let u of r.values())u.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}function AC(e){let t=Q("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let o="",n=!1,r=a=>{let i=H("span","persona-composer-quote-bar"),d=H("div","persona-composer-quote-content");if(a.sourceLabel){let m=H("div","persona-composer-quote-source");m.textContent=a.sourceLabel,d.appendChild(m)}let c=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Lc(a.text),d.appendChild(c);let u=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=le("x",12,"currentColor",2);p?u.appendChild(p):u.textContent="\xD7",u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,d,u)};return{element:t,render:a=>{if(n)return;let i=a?`${a.sourceLabel??""}\0${a.text}`:"";if(i!==o){if(o=i,!a){t.replaceChildren(),t.style.display="none";return}r(a),t.style.display="flex"}},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function MC(e){let t=Q("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let o,n=!1,r=(i,d,c,u)=>{let p=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":d,[c]:""}}),m=le(i,12,"currentColor",2);return m?p.appendChild(m):p.textContent=d,p.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),u()}),p},a=i=>{let d=Lc(i.text??"",90);if(d)return d;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(p=>p.label).join(", "):"Queued message"};return{element:t,render:i=>{if(n||i===o)return;if(o=i,!i){t.replaceChildren(),t.style.display="none";return}let d=H("span","persona-composer-pending-badge");d.textContent=e.label??"Sends next";let c=Q("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=a(i),t.replaceChildren(d,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function TC(e){let t=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),o=Q("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});o.value=e.initialText;let n=()=>{o.style.height="auto",o.style.height=`${o.scrollHeight}px`};o.addEventListener("input",n);let r=H("div","persona-message-edit-actions"),a=(d,c,u,p)=>{let m=Q("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[u]:""},text:d});return m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),m},i=()=>{let d=o.value.trim();d&&e.onSave(d)};return r.append(a(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),a(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),o.addEventListener("keydown",d=>{if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),e.onCancel();return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),i())}),t.append(o,r),{element:t,getValue:()=>o.value,focus:()=>{o.focus();let d=o.value.length;o.setSelectionRange(d,d),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}function EC(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function PC(e,t){if(!e||typeof e.text!="string")return;let o=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(c=>o.has(c.sourceId)),r=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>a.has(c)),d=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:n}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...d?{selectedModelId:d}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function kC(e){let t=e.delay??500,o=null,n=!1,r=()=>{o!==null&&(clearTimeout(o),o=null)};return{schedule:()=>{n||(r(),o=setTimeout(()=>{o=null,e.write()},t))},flush:()=>{n||o===null||(r(),e.write())},cancel:r,destroy:()=>{n=!0,r()}}}function LC(e){return e.wrapped||e.text.includes(`
|
|
24
|
+
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function IC(){let e=!1;return{observe:(t,o)=>o?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function RC(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let o=t.getComputedStyle(e),n=Number.parseFloat(o.lineHeight),r=Number.parseFloat(o.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(r)&&r>0?r*1.4:0;if(!a)return!1;let i=(Number.parseFloat(o.paddingTop)||0)+(Number.parseFloat(o.paddingBottom)||0);return e.scrollHeight-i>a*1.5}function HC(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function lg(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function BC(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var U0=e=>typeof e?.then=="function";function WC(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function OC(e,t,o){let n;try{n=e(lg(t),{signal:o})}catch(r){return{status:"error",error:r}}return U0(n)?Promise.resolve(n).then(r=>o.aborted?{status:"aborted"}:WC(t,r),r=>o.aborted?{status:"aborted"}:{status:"error",error:r}):WC(t,n)}var DC=/\s/;function q0(e,t,o){if(o==="input-start")return t===0;let n=t>0?e[t-1]:"";return o==="line-start"?n===""||n===`
|
|
25
|
+
`:n===""||DC.test(n)}function V0(e,t,o="@",n="anywhere",r=!1){if(!o||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let i=e[a];if(i===o)return q0(e,a,n)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(i===`
|
|
26
|
+
`||i==="\uFFFC"||!r&&DC.test(i))return null;a--}return null}function _C(e,t,o){for(let n of o){let r=V0(e,t,n.trigger,n.position??"anywhere",n.allowSpaces??!1);if(r)return{channel:n,match:r}}return null}function NC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function FC(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},o=(e.triggers??[]).map(n=>({trigger:n.trigger,position:n.triggerPosition??"anywhere",allowSpaces:n.allowSpaces??!1,sources:Array.isArray(n.sources)?n.sources:[],searchPlaceholder:n.searchPlaceholder,showButton:n.showButton===!0,buttonIconName:n.buttonIconName,buttonTooltipText:n.buttonTooltipText}));return[t,...o]}function UC(e){let{config:t,onOpen:o}=e,n=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",a=H("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Go} ${xn}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),d=le(n,bo,"currentColor",1.5);return d?i.appendChild(d):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),o()}),a.appendChild(i),Jt({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:a}}var{setLoader:$0,load:j0}=mt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),qC=$0,dg=j0;var{setLoader:z0,load:K0}=mt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),VC=z0,$C=K0;function Cl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let o=Q("span",{className:yo("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&o.style.setProperty("--persona-mention-token-accent",e.color);let n=le(e.iconName??"at-sign",13,"currentColor",2);if(n){let r=H("span","persona-mention-token-icon");r.appendChild(n),o.appendChild(r)}return o.appendChild(Q("span",{className:"persona-mention-token-label",text:`@${e.label}`})),o}function jC(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let o=FC(t).filter(b=>b.sources.length>0);if(o.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let n=o.filter(b=>b.sources.some(S=>typeof S.matchCommand=="function")),r=b=>n.some(S=>S.trigger?S.position==="line-start"?b.split(`
|
|
27
|
+
`).some(L=>L.startsWith(S.trigger)):(S.position==="anywhere"?b:b.split(`
|
|
28
|
+
`)[0]).startsWith(S.trigger):!1),a=(b,S)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${b}`,{detail:S}))}catch{}},i=!e.chipRow,d=e.chipRow??Q("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),c=null,u=null,p=e.textarea,m=null,h=null,y=null,C=null,A=()=>{if(c)return Promise.resolve(c);if(u)return u;let b=dg().then(S=>(S.setMentionIconRenderer(le),c=S.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:I,emit:a}),c)).catch(S=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",S),u===b&&(u=null),null));return u=b,b},M=()=>{$C().then(b=>{let S=b.mountInlineComposer({textarea:e.textarea,renderToken:L=>Cl(L,{render:t.renderMentionToken}),onMentionRemoved:L=>c?.untrackMention(L)});m=S.input,h=S.destroy;let x=p;x.replaceWith(S.element),p=S.element,C={next:S.element,prev:x},y?.(S.element,x),c?c.rebindComposer(S.input):u&&u.then(L=>L?.rebindComposer(S.input))}).catch(b=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",b)})};t.display==="inline"&&M();let E=[],T=new Map;for(let b of o){if(!b.showButton)continue;let S=UC({config:{...t,buttonIconName:b.buttonIconName,buttonTooltipText:b.buttonTooltipText},onOpen:()=>{A().then(x=>x?.openMenu(b.trigger))}});E.push(S),T.set(b.trigger,S.button)}let I=(b,S,x)=>{let L=T.get(S);L&&(L.setAttribute("aria-expanded",b?"true":"false"),b?L.setAttribute("aria-controls",x):L.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(b=>b.wrapper),contextRow:d,handleInput:b=>{if(c){c.handleInput();return}if(!NC(b))return;let S=p,x=S.selectionStart??0;_C(S.value,x,o)&&A().then(L=>L?.handleInput())},handleKeydown:b=>{if(c?.isMenuOpen())return c.handleKeydown(b);if(b.key==="Backspace"&&c?.hasMentions()&&!C){let S=p,x=S.selectionStart===0&&S.selectionEnd===0;if((S.value.length===0||x)&&c.removeLastChip())return b.preventDefault(),!0}return!1},isMenuOpen:()=>c?.isMenuOpen()??!1,hasMentions:()=>c?.hasMentions()??!1,getMentionRefs:()=>c?.getMentionRefs()??[],collectForSubmit:()=>c?.collectForSubmit()??null,takeInlineCommand:async b=>r(b)?(c??await A())?.dispatchInlineCommand(b)??null:null,clear:()=>c?.clear(),prefetch:()=>{dg().catch(()=>{})},onComposerSwap:b=>{y=b,C&&b(C.next,C.prev)},destroy:()=>{c?.destroy(),h?.();for(let b of E)b.wrapper.remove();i&&d.remove()}}}var nu="16px",ru="transparent",G0=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),ug={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:G0,typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},pg={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},fg={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Ko,maxWidth:Vc,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:nu,canvasBackground:ru},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function vo(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let o=t.split("."),n=e;for(let r of o){if(n==null)return;n=n[r]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?vo(e,n):n}function su(e){let t={};function o(n,r){for(let[a,i]of Object.entries(n)){let d=`${r}.${a}`;if(typeof i=="string"){let c=vo(e,i);c!==void 0&&(t[d]={path:d,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&o(i,d)}}return o(e.palette,"palette"),o(e.semantic,"semantic"),o(e.components,"components"),t}function mg(e){let t=[],o=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||o.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||o.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:o}}function KC(e,t){let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?o[n]=KC(a,r):o[n]=r}return o}function X0(e,t){return t?KC(e,t):e}function Sl(e,t={}){let o={palette:ug,semantic:pg,components:fg},n={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:X0(o.components,e?.components)};if(t.validate!==!1){let r=mg(n);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)n=r.transform(n);return n}var cg=e=>e.trim()==="0"?"0px":e,zC="--persona-",Q0=e=>{if(!e)return;let t=e.trim().toLowerCase(),o;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?o=[0,1,2].map(d=>parseInt(i[d]+i[d],16)):(i.length===6||i.length===8)&&(o=[0,2,4].map(d=>parseInt(i.slice(d,d+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let d=i[1].split(/[,/\s]+/).filter(Boolean);d.length>=3&&(o=d.slice(0,3).map(c=>{let u=c.endsWith("%"),p=parseFloat(u?c.slice(0,-1):c);return u?p/100*255:p}))}}if(!o||o.some(i=>!Number.isFinite(i)))return;let[n,r,a]=o.map(i=>{let d=Math.max(0,Math.min(255,i))/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)});return .2126*n+.7152*r+.0722*a},Y0=.179,Zt=(e,t)=>{for(let[o,...n]of t){let r;for(let a of n)if(r=a.charCodeAt(0)===61?a.slice(1):e[zC+a],r!==void 0)break;r!==void 0&&(e[zC+o]=r)}};function au(e){let t=su(e),o={};for(let[q,Ue]of Object.entries(t)){let Je=q.replace(/\./g,"-");o[`--persona-${Je}`]=Ue.value}Zt(o,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let n=o["--persona-components-launcher-foreground"];o["--persona-launcher-fg-muted"]=n&&n!==o["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:o["--persona-muted"],Zt(o,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),Zt(o,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),o["--persona-panel-border"]=o["--persona-components-panel-border"]??`1px solid ${o["--persona-border"]}`,Zt(o,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),o["--persona-panel-inset"]=o["--persona-components-panel-inset"]??nu,o["--persona-panel-canvas-bg"]=o["--persona-components-panel-canvasBackground"]??ru,Zt(o,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),Zt(o,[["header-bg","components-header-background","surface"]]);let r=o["--persona-header-bg"],a=o["--persona-components-header-foreground"],i=a?`color-mix(in srgb, ${a} 72%, ${r})`:void 0;o["--persona-header-border"]=o["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${r})`:void 0)??o["--persona-divider"],Zt(o,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),o["--persona-header-title-fg"]=o["--persona-components-header-title-color"]??o["--persona-components-header-titleForeground"]??a??o["--persona-primary"],o["--persona-header-subtitle-fg"]=o["--persona-components-header-subtitle-color"]??o["--persona-components-header-subtitleForeground"]??i??o["--persona-text-muted"],o["--persona-header-action-icon-fg"]=o["--persona-components-header-actionIconForeground"]??i??o["--persona-muted"],Zt(o,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let d=e.components?.header;d?.shadow&&(o["--persona-header-shadow"]=d.shadow),d?.borderBottom&&(o["--persona-header-border-bottom"]=d.borderBottom),d?.minHeight&&(o["--persona-header-min-height"]=d.minHeight);let c=o["--persona-components-history-railHeader-background"];c&&(o["--persona-history-rail-header-bg"]=c);let u=o["--persona-components-history-railHeader-border"];u&&(o["--persona-history-rail-header-border"]=u);let p=o["--persona-components-history-railHeader-minHeight"];p&&(o["--persona-history-rail-header-min-height"]=p);for(let[q,Ue]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Je=o[`--persona-components-history-overlay-${q}`];Je&&(o[`--persona-history-overlay-${Ue}`]=Je)}for(let[q,Ue]of[["background","bg"],["borderRadius","radius"]]){let Je=o[`--persona-components-history-menu-${q}`];Je&&(o[`--persona-history-menu-${Ue}`]=Je)}let m=e.components?.history?.motion;if(m){let q=so=>{if(so===void 0)return;let Le=String(so).trim();return/^\d+(\.\d+)?$/.test(Le)?`${Le}ms`:Le},Ue=q(m.enterDurationMs);Ue!==void 0&&(o["--persona-history-enter-ms"]=Ue);let Je=q(m.exitDurationMs);Je!==void 0&&(o["--persona-history-exit-ms"]=Je),m.enterEasing&&(o["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(o["--persona-history-exit-easing"]=m.exitEasing)}let h=o["--persona-components-history-dangerForeground"];h&&(o["--persona-history-danger-fg"]=h),o["--persona-danger"]=o["--persona-components-history-confirm-dangerBackground"]??o["--persona-palette-colors-error-700"]??"#b42318",o["--persona-danger-fg"]=o["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let q of["scrim","shadow"]){let Ue=o[`--persona-components-history-confirm-${q}`];Ue&&(o[`--persona-history-confirm-${q}`]=Ue)}for(let[q,Ue]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Je=o[`--persona-components-tooltip-${q}`];Je&&(o[`--persona-tooltip-${Ue}`]=Je)}e.components?.tooltip?.arrow===!1&&(o["--persona-tooltip-arrow-display"]="none");for(let[q,Ue]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Je=o[`--persona-components-messageActions-${q}`];Je&&(o[`--persona-message-action-${Ue}`]=Je)}Zt(o,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let y=o["--persona-components-introCard-background"],C=o["--persona-components-introCard-shadow"],A=(!y||y==="transparent"||y==="none")&&(!C||C==="none"),M=o["--persona-components-introCard-padding"]??"1.5rem";o["--persona-intro-card-padding"]=A&&M==="1.5rem"?"1.5rem 0":M,Zt(o,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),Zt(o,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let E=o["--persona-components-markdown-heading-h1-fontSize"];E&&(o["--persona-md-h1-size"]=E);let T=o["--persona-components-markdown-heading-h1-fontWeight"];T&&(o["--persona-md-h1-weight"]=T);let I=o["--persona-components-markdown-heading-h2-fontSize"];I&&(o["--persona-md-h2-size"]=I);let b=o["--persona-components-markdown-heading-h2-fontWeight"];b&&(o["--persona-md-h2-weight"]=b);let S=o["--persona-components-markdown-prose-fontFamily"];S&&S!=="inherit"&&(o["--persona-md-prose-font-family"]=S),Zt(o,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),Zt(o,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Zt(o,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Zt(o,[["md-hr-color","components-markdown-hr-color","divider"]]),Zt(o,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]),o["--cw-container"]=o["--persona-components-collapsibleWidget-container"]??o["--persona-surface"],o["--cw-surface"]=o["--persona-components-collapsibleWidget-surface"]??o["--persona-surface"],o["--cw-border"]=o["--persona-components-collapsibleWidget-border"]??o["--persona-border"],Zt(o,[["message-border","components-message-border","border"]]),Zt(o,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let x=e.components,L=x?.iconButton;L&&(L.background&&(o["--persona-icon-btn-bg"]=L.background),L.border&&(o["--persona-icon-btn-border"]=L.border),L.color&&(o["--persona-icon-btn-color"]=L.color),L.padding&&(o["--persona-icon-btn-padding"]=L.padding),L.borderRadius&&(o["--persona-icon-btn-radius"]=L.borderRadius),L.hoverBackground&&(o["--persona-icon-btn-hover-bg"]=L.hoverBackground),L.hoverColor&&(o["--persona-icon-btn-hover-color"]=L.hoverColor),L.activeBackground&&(o["--persona-icon-btn-active-bg"]=L.activeBackground),L.activeBorder&&(o["--persona-icon-btn-active-border"]=L.activeBorder));let N=x?.labelButton;N&&(N.background&&(o["--persona-label-btn-bg"]=N.background),N.border&&(o["--persona-label-btn-border"]=N.border),N.color&&(o["--persona-label-btn-color"]=N.color),N.padding&&(o["--persona-label-btn-padding"]=N.padding),N.borderRadius&&(o["--persona-label-btn-radius"]=N.borderRadius),N.hoverBackground&&(o["--persona-label-btn-hover-bg"]=N.hoverBackground),N.fontSize&&(o["--persona-label-btn-font-size"]=N.fontSize),N.gap&&(o["--persona-label-btn-gap"]=N.gap));let X=x?.toggleGroup;X&&(X.gap&&(o["--persona-toggle-group-gap"]=X.gap),X.borderRadius&&(o["--persona-toggle-group-radius"]=X.borderRadius));let V=x?.artifact;if(V?.toolbar){let q=V.toolbar;q.iconHoverColor&&(o["--persona-artifact-toolbar-icon-hover-color"]=q.iconHoverColor),q.iconHoverBackground&&(o["--persona-artifact-toolbar-icon-hover-bg"]=q.iconHoverBackground),q.iconPadding&&(o["--persona-artifact-toolbar-icon-padding"]=q.iconPadding),q.iconBorderRadius&&(o["--persona-artifact-toolbar-icon-radius"]=q.iconBorderRadius),q.iconBorder&&(o["--persona-artifact-toolbar-icon-border"]=q.iconBorder),q.toggleGroupGap&&(o["--persona-artifact-toolbar-toggle-group-gap"]=cg(q.toggleGroupGap)),q.toggleBorderRadius&&(o["--persona-artifact-toolbar-toggle-radius"]=q.toggleBorderRadius),q.toggleGroupPadding&&(o["--persona-artifact-toolbar-toggle-group-padding"]=cg(q.toggleGroupPadding)),q.toggleGroupBorder&&(o["--persona-artifact-toolbar-toggle-group-border"]=q.toggleGroupBorder),q.toggleGroupBorderRadius&&(o["--persona-artifact-toolbar-toggle-group-radius"]=q.toggleGroupBorderRadius),q.toggleGroupBackground&&(o["--persona-artifact-toolbar-toggle-group-bg"]=vo(e,q.toggleGroupBackground)??q.toggleGroupBackground),q.copyBackground&&(o["--persona-artifact-toolbar-copy-bg"]=q.copyBackground),q.copyBorder&&(o["--persona-artifact-toolbar-copy-border"]=q.copyBorder),q.copyColor&&(o["--persona-artifact-toolbar-copy-color"]=q.copyColor),q.copyBorderRadius&&(o["--persona-artifact-toolbar-copy-radius"]=cg(q.copyBorderRadius)),q.copyPadding&&(o["--persona-artifact-toolbar-copy-padding"]=q.copyPadding),q.copyMenuBackground&&(o["--persona-artifact-toolbar-copy-menu-bg"]=q.copyMenuBackground,o["--persona-dropdown-bg"]=o["--persona-dropdown-bg"]??q.copyMenuBackground),q.copyMenuBorder&&(o["--persona-artifact-toolbar-copy-menu-border"]=q.copyMenuBorder,o["--persona-dropdown-border"]=o["--persona-dropdown-border"]??q.copyMenuBorder),q.copyMenuShadow&&(o["--persona-artifact-toolbar-copy-menu-shadow"]=q.copyMenuShadow,o["--persona-dropdown-shadow"]=o["--persona-dropdown-shadow"]??q.copyMenuShadow),q.copyMenuBorderRadius&&(o["--persona-artifact-toolbar-copy-menu-radius"]=q.copyMenuBorderRadius,o["--persona-dropdown-radius"]=o["--persona-dropdown-radius"]??q.copyMenuBorderRadius),q.copyMenuItemHoverBackground&&(o["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=q.copyMenuItemHoverBackground,o["--persona-dropdown-item-hover-bg"]=o["--persona-dropdown-item-hover-bg"]??q.copyMenuItemHoverBackground),q.iconBackground&&(o["--persona-artifact-toolbar-icon-bg"]=q.iconBackground),q.toolbarBorder&&(o["--persona-artifact-toolbar-border"]=q.toolbarBorder)}if(V?.tab){let q=V.tab;q.background&&(o["--persona-artifact-tab-bg"]=q.background),q.activeBackground&&(o["--persona-artifact-tab-active-bg"]=q.activeBackground),q.activeBorder&&(o["--persona-artifact-tab-active-border"]=q.activeBorder),q.borderRadius&&(o["--persona-artifact-tab-radius"]=q.borderRadius),q.textColor&&(o["--persona-artifact-tab-color"]=q.textColor),q.hoverBackground&&(o["--persona-artifact-tab-hover-bg"]=q.hoverBackground),q.listBackground&&(o["--persona-artifact-tab-list-bg"]=q.listBackground),q.listBorderColor&&(o["--persona-artifact-tab-list-border-color"]=q.listBorderColor),q.listPadding&&(o["--persona-artifact-tab-list-padding"]=q.listPadding)}if(V?.pane){let q=V.pane;if(q.toolbarBackground){let Ue=vo(e,q.toolbarBackground)??q.toolbarBackground;o["--persona-artifact-toolbar-bg"]=Ue}}if(V?.card){let q=V.card;q.background&&(o["--persona-artifact-card-bg"]=q.background),q.border&&(o["--persona-artifact-card-border"]=q.border),q.borderRadius&&(o["--persona-artifact-card-radius"]=q.borderRadius),q.hoverBackground&&(o["--persona-artifact-card-hover-bg"]=q.hoverBackground),q.hoverBorderColor&&(o["--persona-artifact-card-hover-border"]=q.hoverBorderColor)}if(V?.inline){let q=V.inline;q.background&&(o["--persona-artifact-inline-bg"]=vo(e,q.background)??q.background),q.border&&(o["--persona-artifact-inline-border"]=q.border),q.borderRadius&&(o["--persona-artifact-inline-radius"]=q.borderRadius),q.chromeBackground&&(o["--persona-artifact-inline-chrome-bg"]=vo(e,q.chromeBackground)??q.chromeBackground),q.chromeBorder&&(o["--persona-artifact-inline-chrome-border"]=vo(e,q.chromeBorder)??q.chromeBorder),q.titleColor&&(o["--persona-artifact-inline-title-color"]=vo(e,q.titleColor)??q.titleColor),q.mutedColor&&(o["--persona-artifact-inline-muted-color"]=vo(e,q.mutedColor)??q.mutedColor),q.frameHeight&&(o["--persona-artifact-inline-frame-height"]=q.frameHeight)}let P=x?.code;P&&(P.keywordColor&&(o["--persona-code-keyword-color"]=P.keywordColor),P.stringColor&&(o["--persona-code-string-color"]=P.stringColor),P.commentColor&&(o["--persona-code-comment-color"]=P.commentColor),P.numberColor&&(o["--persona-code-number-color"]=P.numberColor),P.tagColor&&(o["--persona-code-tag-color"]=P.tagColor),P.attrColor&&(o["--persona-code-attr-color"]=P.attrColor),P.propertyColor&&(o["--persona-code-property-color"]=P.propertyColor),P.lineNumberColor&&(o["--persona-code-line-number-color"]=P.lineNumberColor),P.gutterBorderColor&&(o["--persona-code-gutter-border-color"]=P.gutterBorderColor),P.background&&(o["--persona-code-bg"]=vo(e,P.background)??P.background));let O=o["--persona-surface"],D=o["--persona-container"],W=o["--persona-palette-colors-gray-100"]??"#f3f4f6",ee=o["--persona-palette-colors-gray-200"]??"#e5e7eb",G=o["--persona-palette-colors-gray-300"]??"#d1d5db",ue=!D||D===O,ae=Q0(O??o["--persona-background"]),ye=ue&&ae!==void 0&&ae<Y0,Re=ye?"rgba(255, 255, 255, 0.08)":W,be=ye?"rgba(255, 255, 255, 0.12)":ee,pe=ye?"rgba(255, 255, 255, 0.16)":G,yt=ue?Re:D,Pe=ue?be:D;return o["--persona-icon-btn-hover-bg"]=o["--persona-icon-btn-hover-bg"]??yt,o["--persona-icon-btn-active-bg"]=o["--persona-icon-btn-active-bg"]??Pe,ue&&(o["--persona-icon-btn-active-border"]=o["--persona-icon-btn-active-border"]??pe),o["--persona-label-btn-hover-bg"]=o["--persona-label-btn-hover-bg"]??yt,o["--persona-artifact-tab-hover-bg"]=o["--persona-artifact-tab-hover-bg"]??yt,o["--persona-artifact-card-hover-bg"]=o["--persona-artifact-card-hover-bg"]??yt,o}var GC={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var J0={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Z0={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},XC=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},wl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",eP=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":wl()},iu=e=>eP(e),tP=e=>Sl(e),oP=e=>{let t=Va(Z0,e??{})??{};return Sl({...t,palette:{...t.palette,colors:{...J0.colors,...t.palette?.colors}}},{validate:!1})},Kr=e=>{let t=iu(e),o=XC(e?.theme),n=XC(e?.darkTheme);return t==="dark"?oP(Va(o??{},n??{})):tP(o)},nP=e=>au(e),Ds=(e,t)=>{let o=Kr(t),n=nP(o);for(let[r,a]of Object.entries(n))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",iu(t))},za=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let o=new MutationObserver(()=>{e(wl())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>o.disconnect())}if(typeof window<"u"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(wl());o.addEventListener?(o.addEventListener("change",n),t.push(()=>o.removeEventListener("change",n))):o.addListener&&(o.addListener(n),t.push(()=>o.removeListener(n)))}return()=>{t.forEach(o=>o())}};var Gr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var lu="24px",gg=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Al=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let o=Number(t[1])/100;return o>0&&o<1?o:null},QC=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var YC=null;var hg=()=>{if(YC!==null)return YC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},rP="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",du=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},cu=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),o=t.pop(),n={key:o,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")n.mod=!0;else if(r==="shift")n.shift=!0;else if(r==="alt"||r==="option")n.alt=!0;else return du("unknown modifier in",e),null;return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(o)||!/^([^+\s]|[a-z]{2,12})$/.test(o)?(du("unsupported",e),null):(o==="space"&&(n.key=" "),n)},sP=e=>rP.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),JC=(e,t)=>{let o=cu(e);if(!o)return"";let n=hg(),r=sP(o.key);if(!t&&n)return`${o.alt?"\u2325":""}${o.shift?"\u21E7":""}\u2318${r}`;let a=[t?n?"Meta":"Control":"Ctrl"];return o.alt&&a.push("Alt"),o.shift&&a.push("Shift"),a.push(r),a.join("+")},uu=e=>JC(e,!1),Ml=e=>JC(e,!0),aP=(e,t)=>t.key?.toLowerCase()===e.key&&(hg()?t.metaKey:t.ctrlKey)===e.mod&&!(hg()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,iP=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},ZC=e=>{let t=new Map,o=e?.ownerDocument??(typeof document<"u"?document:null),n=(a,i)=>{if((a.scope??"widget")==="page")return!0;if(!e)return!1;let d=i.composedPath?.();return d?.length?d.includes(e):e.contains(i.target)},r=a=>{if(a.isComposing||!t.size)return;let i=a.composedPath?.()[0]??a.target;for(let d of t.values())if(aP(d.parsed,a)&&d.when?.()!==!1&&n(d,a)&&!(!d.allowInInput&&iP(i))){a.preventDefault();try{d.run(a)}catch(c){du(`${d.id} threw on`,d.combo),console.warn(c)}return}};return o?.addEventListener("keydown",r),{register(a){let i=cu(a.combo);if(!i)return()=>{};let d=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(d);return c?(du(`${c.id} already owns`,a.combo),()=>{}):(t.set(d,{...a,parsed:i}),a.element?.setAttribute("aria-keyshortcuts",Ml(a.combo)),()=>{t.get(d)?.id===a.id&&t.delete(d),a.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),o?.removeEventListener("keydown",r)}}};var eS=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:h=>h.getAttribute("im-preserve")==="true",shouldReAppend:h=>h.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function o(h,y,C={}){h=p(h);let A=m(y),M=u(h,A,C),E=r(M,()=>d(M,h,A,T=>T.morphStyle==="innerHTML"?(a(T,h,A),Array.from(h.childNodes)):n(T,h,A)));return M.pantry.remove(),E}function n(h,y,C){let A=m(y);return a(h,A,C,y,y.nextSibling),Array.from(A.childNodes)}function r(h,y){if(!h.config.restoreFocus)return y();let C=document.activeElement;if(!(C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement))return y();let{id:A,selectionStart:M,selectionEnd:E}=C,T=y();return A&&A!==document.activeElement?.getAttribute("id")&&(C=h.target.querySelector(`[id="${A}"]`),C?.focus()),C&&!C.selectionEnd&&E&&C.setSelectionRange(M,E),T}let a=(function(){function h(b,S,x,L=null,N=null){S instanceof HTMLTemplateElement&&x instanceof HTMLTemplateElement&&(S=S.content,x=x.content),L||(L=S.firstChild);for(let X of x.childNodes){if(L&&L!=N){let P=C(b,X,L,N);if(P){P!==L&&M(b,L,P),i(P,X,b),L=P.nextSibling;continue}}if(X instanceof Element){let P=X.getAttribute("id");if(b.persistentIds.has(P)){let O=E(S,P,L,b);i(O,X,b),L=O.nextSibling;continue}}let V=y(S,X,L,b);V&&(L=V.nextSibling)}for(;L&&L!=N;){let X=L;L=L.nextSibling,A(b,X)}}function y(b,S,x,L){if(L.callbacks.beforeNodeAdded(S)===!1)return null;if(L.idMap.has(S)){let N=document.createElement(S.tagName);return b.insertBefore(N,x),i(N,S,L),L.callbacks.afterNodeAdded(N),N}else{let N=document.importNode(S,!0);return b.insertBefore(N,x),L.callbacks.afterNodeAdded(N),N}}let C=(function(){function b(L,N,X,V){let P=null,O=N.nextSibling,D=0,W=X;for(;W&&W!=V;){if(x(W,N)){if(S(L,W,N))return W;P===null&&(L.idMap.has(W)||(P=W))}if(P===null&&O&&x(W,O)&&(D++,O=O.nextSibling,D>=2&&(P=void 0)),L.activeElementAndParents.includes(W))break;W=W.nextSibling}return P||null}function S(L,N,X){let V=L.idMap.get(N),P=L.idMap.get(X);if(!P||!V)return!1;for(let O of V)if(P.has(O))return!0;return!1}function x(L,N){let X=L,V=N;return X.nodeType===V.nodeType&&X.tagName===V.tagName&&(!X.getAttribute?.("id")||X.getAttribute?.("id")===V.getAttribute?.("id"))}return b})();function A(b,S){if(b.idMap.has(S))I(b.pantry,S,null);else{if(b.callbacks.beforeNodeRemoved(S)===!1)return;S.parentNode?.removeChild(S),b.callbacks.afterNodeRemoved(S)}}function M(b,S,x){let L=S;for(;L&&L!==x;){let N=L;L=L.nextSibling,A(b,N)}return L}function E(b,S,x,L){let N=L.target.getAttribute?.("id")===S&&L.target||L.target.querySelector(`[id="${S}"]`)||L.pantry.querySelector(`[id="${S}"]`);return T(N,L),I(b,N,x),N}function T(b,S){let x=b.getAttribute("id");for(;b=b.parentNode;){let L=S.idMap.get(b);L&&(L.delete(x),L.size||S.idMap.delete(b))}}function I(b,S,x){if(b.moveBefore)try{b.moveBefore(S,x)}catch{b.insertBefore(S,x)}else b.insertBefore(S,x)}return h})(),i=(function(){function h(T,I,b){return b.ignoreActive&&T===document.activeElement?null:(b.callbacks.beforeNodeMorphed(T,I)===!1||(T instanceof HTMLHeadElement&&b.head.ignore||(T instanceof HTMLHeadElement&&b.head.style!=="morph"?c(T,I,b):(y(T,I,b),E(T,b)||a(b,T,I))),b.callbacks.afterNodeMorphed(T,I)),T)}function y(T,I,b){let S=I.nodeType;if(S===1){let x=T,L=I,N=x.attributes,X=L.attributes;for(let V of X)M(V.name,x,"update",b)||x.getAttribute(V.name)!==V.value&&x.setAttribute(V.name,V.value);for(let V=N.length-1;0<=V;V--){let P=N[V];if(P&&!L.hasAttribute(P.name)){if(M(P.name,x,"remove",b))continue;x.removeAttribute(P.name)}}E(x,b)||C(x,L,b)}(S===8||S===3)&&T.nodeValue!==I.nodeValue&&(T.nodeValue=I.nodeValue)}function C(T,I,b){if(T instanceof HTMLInputElement&&I instanceof HTMLInputElement&&I.type!=="file"){let S=I.value,x=T.value;A(T,I,"checked",b),A(T,I,"disabled",b),I.hasAttribute("value")?x!==S&&(M("value",T,"update",b)||(T.setAttribute("value",S),T.value=S)):M("value",T,"remove",b)||(T.value="",T.removeAttribute("value"))}else if(T instanceof HTMLOptionElement&&I instanceof HTMLOptionElement)A(T,I,"selected",b);else if(T instanceof HTMLTextAreaElement&&I instanceof HTMLTextAreaElement){let S=I.value,x=T.value;if(M("value",T,"update",b))return;S!==x&&(T.value=S),T.firstChild&&T.firstChild.nodeValue!==S&&(T.firstChild.nodeValue=S)}}function A(T,I,b,S){let x=I[b],L=T[b];if(x!==L){let N=M(b,T,"update",S);N||(T[b]=I[b]),x?N||T.setAttribute(b,""):M(b,T,"remove",S)||T.removeAttribute(b)}}function M(T,I,b,S){return T==="value"&&S.ignoreActiveValue&&I===document.activeElement?!0:S.callbacks.beforeAttributeUpdated(T,I,b)===!1}function E(T,I){return!!I.ignoreActiveValue&&T===document.activeElement&&T!==document.body}return h})();function d(h,y,C,A){if(h.head.block){let M=y.querySelector("head"),E=C.querySelector("head");if(M&&E){let T=c(M,E,h);return Promise.all(T).then(()=>{let I=Object.assign(h,{head:{block:!1,ignore:!0}});return A(I)})}}return A(h)}function c(h,y,C){let A=[],M=[],E=[],T=[],I=new Map;for(let S of y.children)I.set(S.outerHTML,S);for(let S of h.children){let x=I.has(S.outerHTML),L=C.head.shouldReAppend(S),N=C.head.shouldPreserve(S);x||N?L?M.push(S):(I.delete(S.outerHTML),E.push(S)):C.head.style==="append"?L&&(M.push(S),T.push(S)):C.head.shouldRemove(S)!==!1&&M.push(S)}T.push(...I.values());let b=[];for(let S of T){let x=document.createRange().createContextualFragment(S.outerHTML).firstChild;if(C.callbacks.beforeNodeAdded(x)!==!1){if("href"in x&&x.href||"src"in x&&x.src){let L,N=new Promise(function(X){L=X});x.addEventListener("load",function(){L()}),b.push(N)}h.appendChild(x),C.callbacks.afterNodeAdded(x),A.push(x)}}for(let S of M)C.callbacks.beforeNodeRemoved(S)!==!1&&(h.removeChild(S),C.callbacks.afterNodeRemoved(S));return C.head.afterHeadMorphed(h,{added:A,kept:E,removed:M}),b}let u=(function(){function h(b,S,x){let{persistentIds:L,idMap:N}=T(b,S),X=y(x),V=X.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(V))throw`Do not understand how to morph style ${V}`;return{target:b,newContent:S,config:X,morphStyle:V,ignoreActive:X.ignoreActive,ignoreActiveValue:X.ignoreActiveValue,restoreFocus:X.restoreFocus,idMap:N,persistentIds:L,pantry:C(),activeElementAndParents:A(b),callbacks:X.callbacks,head:X.head}}function y(b){let S=Object.assign({},t);return Object.assign(S,b),S.callbacks=Object.assign({},t.callbacks,b.callbacks),S.head=Object.assign({},t.head,b.head),S}function C(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function A(b){let S=[],x=document.activeElement;if(x?.tagName!=="BODY"&&b.contains(x))for(;x&&(S.push(x),x!==b);)x=x.parentElement;return S}function M(b){let S=Array.from(b.querySelectorAll("[id]"));return b.getAttribute?.("id")&&S.push(b),S}function E(b,S,x,L){for(let N of L){let X=N.getAttribute("id");if(S.has(X)){let V=N;for(;V;){let P=b.get(V);if(P==null&&(P=new Set,b.set(V,P)),P.add(X),V===x)break;V=V.parentElement}}}}function T(b,S){let x=M(b),L=M(S),N=I(x,L),X=new Map;E(X,N,b,x);let V=S.__idiomorphRoot||S;return E(X,N,V,L),{persistentIds:N,idMap:X}}function I(b,S){let x=new Set,L=new Map;for(let{id:X,tagName:V}of b)L.has(X)?x.add(X):L.set(X,V);let N=new Set;for(let{id:X,tagName:V}of S)N.has(X)?x.add(X):L.get(X)===V&&N.add(X);for(let X of x)N.delete(X);return N}return h})(),{normalizeElement:p,normalizeParent:m}=(function(){let h=new WeakSet;function y(E){return E instanceof Document?E.documentElement:E}function C(E){if(E==null)return document.createElement("div");if(typeof E=="string")return C(M(E));if(h.has(E))return E;if(E instanceof Node){if(E.parentNode)return new A(E);{let T=document.createElement("div");return T.append(E),T}}else{let T=document.createElement("div");for(let I of[...E])T.append(I);return T}}class A{constructor(T){this.originalNode=T,this.realParentNode=T.parentNode,this.previousSibling=T.previousSibling,this.nextSibling=T.nextSibling}get childNodes(){let T=[],I=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;I&&I!=this.nextSibling;)T.push(I),I=I.nextSibling;return T}querySelectorAll(T){return this.childNodes.reduce((I,b)=>{if(b instanceof Element){b.matches(T)&&I.push(b);let S=b.querySelectorAll(T);for(let x=0;x<S.length;x++)I.push(S[x])}return I},[])}insertBefore(T,I){return this.realParentNode.insertBefore(T,I)}moveBefore(T,I){return this.realParentNode.moveBefore(T,I)}get __idiomorphRoot(){return this.originalNode}}function M(E){let T=new DOMParser,I=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(I.match(/<\/html>/)||I.match(/<\/head>/)||I.match(/<\/body>/)){let b=T.parseFromString(E,"text/html");if(I.match(/<\/html>/))return h.add(b),b;{let S=b.firstChild;return S&&h.add(S),S}}else{let S=T.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return h.add(S),S}}return{normalizeElement:y,normalizeParent:C}})();return{morph:o,defaults:t}})();var pu=(e,t,o={})=>{let{preserveTypingAnimation:n=!0}=o;eS.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&n){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let i=r.textContent??"",d=a.textContent??"";if(i!==d)return}return!1}}}}})};var tS=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var yg={index:-1,draft:""};function oS(e){let{direction:t,history:o,currentValue:n,atStart:r,state:a}=e,i=a.index!==-1;if(o.length===0)return{handled:!1,state:a};if(t==="up"){if(!i&&!r)return{handled:!1,state:a};if(!i){let d=o.length-1;return{handled:!0,value:o[d],state:{index:d,draft:n}}}if(a.index>0){let d=a.index-1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,state:a}}if(!i)return{handled:!1,state:a};if(a.index<o.length-1){let d=a.index+1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function nS(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function rS(){return new Map}function sS(e,t,o){let n=e.get(t);return n&&n.fingerprint===o?n.wrapper:null}function aS(e,t,o,n){e.set(t,{fingerprint:o,wrapper:n})}function iS(e,t){for(let o of e.keys())t.has(o)||e.delete(o)}function lS(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function dS(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Un(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function _s(e,t){return Un(e)-e.scrollTop<=t}function cS(e){let{following:t,currentScrollTop:o,lastScrollTop:n,nearBottom:r,userScrollThreshold:a,isAutoScrolling:i=!1,pauseOnUpwardScroll:d=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:u=!1}=e,p=o-n;return i||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:o}:!t&&r&&(!u||p>0)?{action:"resume",delta:p,nextLastScrollTop:o}:t&&d&&p<0?{action:"pause",delta:p,nextLastScrollTop:o}:t&&c&&!r?{action:"pause",delta:p,nextLastScrollTop:o}:{action:"none",delta:p,nextLastScrollTop:o}}function uS(e){let{following:t,deltaY:o,nearBottom:n=!1,resumeWhenNearBottom:r=!1}=e;return t&&o<0?"pause":!t&&r&&o>0&&n?"resume":"none"}function pS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function bg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),o=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:o}}function fS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Tl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},lP=["pre","code","a","script","style"],fu=e=>({type:e?.type??Tl.type,placeholder:e?.placeholder??Tl.placeholder,speed:e?.speed??Tl.speed,duration:e?.duration??Tl.duration,buffer:e?.buffer??Tl.buffer}),gS=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],El=new Map;for(let e of gS)El.set(e.name,e);var hS=["wipe","glyph-cycle"],Ka=e=>{El.set(e.name,e)},Cg=e=>{gS.some(t=>t.name===e)||El.delete(e)},Sg=()=>Array.from(El.keys()),Pl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:El.get(e)??null,mu=(e,t,o,n,r)=>{if(!r)return e;if(o?.bufferContent)return o.bufferContent(e,n);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
|
|
29
|
+
`);return a<0?"":e.slice(0,a)}return e},dP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${o}-${n}`,r.style.setProperty("--char-index",String(n)),r.textContent=t,r},cP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${o}-${n}`,r.style.setProperty("--word-index",String(n)),r.textContent=t,r},vg=/\s/,uP=(e,t)=>{let o=e.parentNode;for(;o;){if(o.nodeType===1){let n=o;if(t.has(n.tagName.toLowerCase()))return!0}o=o.parentNode}return!1},pP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=0;for(;d<a.length;)if(vg.test(a[d])){let c=d;for(;c<a.length&&vg.test(a[c]);)c+=1;i.appendChild(n.createTextNode(a.slice(d,c))),d=c}else{let c=n.createElement("span");c.className="persona-stream-word-group";let u=d;for(;u<a.length&&!vg.test(a[u]);)c.appendChild(dP(n,a[u],t,o.value)),o.value+=1,u+=1;i.appendChild(c),d=u}r.replaceChild(i,e)},fP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=a.split(/(\s+)/);for(let c of d)c&&(/^\s+$/.test(c)?i.appendChild(n.createTextNode(c)):(i.appendChild(cP(n,c,t,o.value)),o.value+=1));r.replaceChild(i,e)},kl=(e,t,o,n)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((n?.skipTags??lP).map(m=>m.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),d=[],c=i.nextNode();for(;c;)uP(c,a)||d.push(c),c=i.nextNode();let u={value:n?.startIndex??0},p=t==="char"?pP:fP;for(let m of d)p(m,o,u);return r.innerHTML},gu=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ll=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let o=e.createElement("div");return o.className="persona-stream-skeleton-line",t.appendChild(o),t},mS=new WeakMap,mP=(e,t)=>{if(!e.styles)return;let o=mS.get(t);if(o||(o=new Set,mS.set(t,o)),o.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;o.delete(e.name)}o.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},xg=new WeakMap,gP=(e,t)=>{if(!e.onAttach)return;let o=xg.get(t);if(o||(o=new Map,xg.set(t,o)),o.has(e.name))return;let n=e.onAttach(t);o.set(e.name,n)},yS=e=>{let t=xg.get(e);if(t){for(let o of t.values())typeof o=="function"&&o();t.clear()}},Il=(e,t)=>{mP(e,t),gP(e,t)};var{setLoader:hP,load:yP}=mt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),bS=hP,vS=yP;function wg(e,t=ro){let o=e.style.position,n=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),i=a.position==="static"||a.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=o),e.style.zIndex=n,e.style.isolation=r}}var Rl=0,Xr=null;function Ag(e=document){if(Rl++,Rl===1){let o=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Xr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:r},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${r}px`,o.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Rl=Math.max(0,Rl-1),Rl===0&&Xr)){let o=e.body,n=e.defaultView??window;o.style.overflow=Xr.originalOverflow,o.style.position=Xr.originalPosition,o.style.top=Xr.originalTop,o.style.width=Xr.originalWidth,n.scrollTo(0,Xr.scrollY),Xr=null}}}var Hl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ct=e=>(e?.launcher?.mountMode??"floating")==="docked",Qr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Do=e=>{let t=e?.launcher?.dock;return{side:t?.side??Hl.side,width:t?.width??Hl.width,animate:t?.animate??Hl.animate,reveal:t?.reveal??Hl.reveal,maxHeight:t?.maxHeight??Hl.maxHeight}};var Mg=e=>e==="followUp"?"follow-up":e,Tg=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let o=e.label.trim();if(!o)return null;let n=e.prompt?.trim()||o;return{id:e.id?.trim()||n||`suggestion-${t}`,label:o,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},bP=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},xS=new WeakSet,vP=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,xP=e=>{vP()||e.forEach((t,o)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:o*60,easing:"ease-out",fill:"backwards"})})},Eg=e=>{var I,b,S;let{item:t,index:o,surface:n,source:r,variant:a,streaming:i,config:d,plugins:c,chipsConfig:u,session:p,getTextarea:m,eventTarget:h,submitPrompt:y}=e,C=n==="followUp",A=t.behavior,M=()=>{if(p.isStreaming())return;let x={suggestion:{...t},surface:n,source:r,behavior:A},L=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:x,bubbles:!0,composed:!0,cancelable:!0}));if(C&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!L)return;for(let X of c)if(X.onSuggestionSelect?.({suggestion:{...t},surface:n,source:r,variant:a,config:d})===!1)return;let N=m();if(A==="fill"){N.value=t.prompt,N.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),N.focus();return}if(y){y(t.prompt);return}N.value="",p.sendMessage(t.prompt)},E=()=>{let x=H("button",`persona-suggestion persona-suggestion--${a}`);if(x.type="button",x.disabled=i,x.dataset.suggestionId=t.id,x.dataset.emphasis=t.emphasis,x.dataset.behavior=A,a==="chip"&&(u?.fontFamily&&(x.style.fontFamily=bP(u.fontFamily)),u?.fontWeight&&(x.style.fontWeight=u.fontWeight),u?.paddingX&&(x.style.paddingLeft=u.paddingX,x.style.paddingRight=u.paddingX),u?.paddingY&&(x.style.paddingTop=u.paddingY,x.style.paddingBottom=u.paddingY)),t.icon){let N=le(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);N&&(N.classList.add("persona-suggestion__icon"),t.iconColor&&(N.style.color=t.iconColor),x.appendChild(N))}let L=H("span","persona-suggestion__copy");if(L.appendChild(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&a!=="chip"&&L.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),x.appendChild(L),a!=="chip"){let N=Ut(cl,16,"currentColor",1.8);N&&(N.classList.add("persona-suggestion__arrow"),x.appendChild(N))}return x.addEventListener("click",M),x},T=null;for(let x of c)if(x.renderSuggestion&&(T=x.renderSuggestion({suggestion:{...t},index:o,surface:n,source:r,variant:a,streaming:i,config:d,defaultRenderer:E,select:M}),T))break;return T??(T=E()),(I=T.dataset).suggestionId||(I.suggestionId=t.id),(b=T.dataset).behavior||(b.behavior=A),(S=T.dataset).emphasis||(S.emphasis=t.emphasis),T instanceof HTMLButtonElement||T.setAttribute("aria-disabled",i?"true":"false"),T},Wl=e=>{let t=[],o=[],n=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){a();return}let m=getComputedStyle(e).direction==="rtl",h=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),y=4,C=h<=y,A=h>=p-y,M=m?!A:!C,E=m?!C:!A;e.toggleAttribute("data-scroll-left",M),e.toggleAttribute("data-scroll-right",E)},d=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",d,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(d):null;return c?.observe(e),{buttons:t,elements:o,destroy:()=>{e.removeEventListener("scroll",d),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,m,h,y,C,A)=>{e.replaceChildren(),t.length=0,o.length=0;let M=A?.source??"config",E=A?.surface??(M==="config"?"starter":"followUp"),T=E==="followUp",I=A?.variant??"chip",b=A?.behavior??"send",S=A?.overflow??"wrap",x=A?.config??{},L=A?.plugins??[],N=typeof A?.maxItems=="number"?Math.max(0,Math.floor(A.maxItems)):void 0,X=T?"followUps":"starters";!xS.has(x)&&x.debug===!0&&I!=="chip"&&x.suggestions?.[X]?.overflow!==void 0&&(xS.add(x),console.info(`[persona] suggestions.${X}.overflow applies to the "chip" variant only; the "${I}" variant manages its own stacking.`));let V=G=>G.map(Tg).filter(ue=>ue!==null).map(ue=>({...ue,behavior:ue.behavior??b})),P=V(p??[]);L.forEach(G=>{G.transformSuggestions&&(P=V(G.transformSuggestions({suggestions:P.map(ue=>({...ue})),surface:E,source:M,config:x})))});let O=N===void 0?P:P.slice(0,N);if(!O.length){e.hidden=!0,n=null,a();return}if(!T&&(y??m.getMessages()).some(ue=>ue.role==="user")){e.hidden=!0,n=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Mg(E),e.dataset.variant=I,e.dataset.overflow=S;let D=document.createDocumentFragment(),W=m.isStreaming();O.forEach((G,ue)=>{let ae=Eg({item:G,index:ue,surface:E,source:M,variant:I,streaming:W,config:x,plugins:L,chipsConfig:C,session:m,getTextarea:()=>h,eventTarget:e,submitPrompt:A?.submitPrompt});D.appendChild(ae),o.push(ae),[...ae instanceof HTMLButtonElement?[ae]:[],...Array.from(ae.querySelectorAll("button"))].forEach(Re=>{t.includes(Re)||(Re.disabled=W,t.push(Re))})}),e.appendChild(D),i(),d();let ee=JSON.stringify({normalized:O,surface:E,variant:I,source:M});ee!==n&&(n=ee,xP(o),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:O.map(G=>({...G})),surface:E,source:M,variant:I},bubbles:!0,composed:!0})),T&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:O.map(G=>G.prompt)},bubbles:!0,composed:!0})))}}};var Xo={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var CP="persona-header-control",SP="persona-header-control--glyph",wP="persona-header-control--sparse",AP=20,MP={x:[1.4,1.05]},CS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",TP="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",hu=(e,t,o={})=>{let{iconSize:n,iconText:r}=o,[a,i]=MP[t]??[1,1.5],d=!n;e.classList.toggle(SP,d),e.classList.toggle(wP,d&&a!==1);let c=parseFloat(n??"")||AP,u=le(t,`${Math.round(c*a)}px`,"currentColor",i);u?(u.style.display="block",d||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(u)):r&&(e.textContent=r)},Ns=e=>{let{ariaLabel:t,tooltip:o=!0,tooltipHint:n,iconName:r,iconText:a,wrapperClassName:i=CS,size:d,iconSize:c,color:u,backgroundColor:p,borderWidth:m,borderColor:h,borderRadius:y,paddingX:C,paddingY:A,hidden:M,extraClassName:E,attrs:T}=e,I=H("div",i),b=!!(m||h),S=Q("button",{className:yo(CP,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!b&&"persona-border-none",!y&&"persona-rounded-full",E),attrs:{type:"button","aria-label":t,...T},style:{width:d,height:d,minWidth:d,minHeight:d,display:M?"none":void 0,color:u||xo.actionIconColor,backgroundColor:p,border:b?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:y,paddingLeft:C,paddingRight:C,paddingTop:A,paddingBottom:A}});return r?hu(S,r,{iconSize:c,iconText:a}):a&&(S.textContent=a),I.appendChild(S),Jt({anchor:S,trigger:I,text:()=>S.getAttribute("aria-label")??t,hint:n,enabled:o}),{button:S,wrapper:I}},Ga=(e,t={})=>{let{showClose:o=!0,wrapperClassName:n=CS,buttonSize:r,iconSize:a}=t,i=e?.launcher??{},d=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:u,wrapper:p}=Ns({ariaLabel:d,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:n,size:r??i.closeButtonSize,iconSize:a,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!o});return{button:u,wrapper:p}},Xa=(e,t={})=>{let{wrapperClassName:o=TP,buttonSize:n,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},d=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:u,wrapper:p}=Ns({ariaLabel:d,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:o,size:n??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:u,wrapper:p}};var xo={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},Pg={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},EP={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},gr=e=>{let{config:t,showClose:o=!0}=e,n=Q("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:xo.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},a=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",d=r.headerIconHidden??!1,c=r.headerIconName,u=Q("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!d)if(c){let S=parseFloat(a)||24,x=le(c,S*.6,"currentColor",1);x?u.replaceChildren(x):u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let S=H("img");S.src=t.launcher.iconUrl,S.alt="",S.className="persona-rounded-xl persona-object-cover",S.style.height=a,S.style.width=a,u.replaceChildren(S)}else u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=H("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Q("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:xo.titleColor,...Pg}}),h=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:xo.subtitleColor,...EP}});p.append(m,h),d?n.append(p):n.append(u,p);let y=r.clearChat??{},C=y.enabled??!0,A=y.placement??"inline",M=null,E=null;if(C){let x=Xa(t,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=x.button,E=x.wrapper,A==="top-right"&&(E.style.right="48px"),A==="inline"&&n.appendChild(E)}let T=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:I,wrapper:b}=Ga(t,{showClose:o,wrapperClassName:T});return i!=="top-right"&&n.appendChild(b),{header:n,iconHolder:u,headerTitle:m,headerSubtitle:h,closeButton:I,closeButtonWrapper:b,clearChatButton:M,clearChatButtonWrapper:E}},Fs=(e,t,o)=>{let n=o?.launcher??{},r=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Us(e){let{items:t,onSelect:o,anchor:n,position:r="bottom-left",portal:a,onOpenChange:i}=e,d=H("div","persona-dropdown-menu persona-hidden");d.setAttribute("role","menu"),d.setAttribute("data-persona-theme-zone","dropdown"),a?(d.style.position="fixed",d.style.zIndex=String(qa)):(d.style.position="absolute",d.style.top="100%",d.style.marginTop="4px",r==="bottom-right"?d.style.right="0":d.style.left="0");for(let C of t){if(C.dividerBefore){let E=document.createElement("hr");d.appendChild(E)}let A=document.createElement("button");if(A.type="button",A.setAttribute("role","menuitem"),A.setAttribute("data-dropdown-item-id",C.id),C.destructive&&A.setAttribute("data-destructive",""),C.icon){let E=le(C.icon,16,"currentColor",1.5);E&&A.appendChild(E)}let M=document.createElement("span");M.textContent=C.label,A.appendChild(M),A.addEventListener("click",E=>{E.stopPropagation(),m(),o(C.id)}),d.appendChild(A)}let c=null;function u(){if(!a)return;let C=n.getBoundingClientRect();d.style.top=`${C.bottom+4}px`,r==="bottom-right"?(d.style.right=`${window.innerWidth-C.right}px`,d.style.left="auto"):(d.style.left=`${C.left}px`,d.style.right="auto")}function p(){let C=d.classList.contains("persona-hidden");u(),d.classList.remove("persona-hidden"),C&&i?.(!0),requestAnimationFrame(()=>{let A=M=>{!d.contains(M.target)&&!n.contains(M.target)&&m()};document.addEventListener("click",A,!0),c=()=>document.removeEventListener("click",A,!0)})}function m(){let C=!d.classList.contains("persona-hidden");d.classList.add("persona-hidden"),c?.(),c=null,C&&i?.(!1)}function h(){d.classList.contains("persona-hidden")?p():m()}function y(){m(),d.remove()}return a&&a.appendChild(d),{element:d,show:p,hide:m,toggle:h,destroy:y}}function qs(e){let{icon:t,label:o,size:n,strokeWidth:r,className:a,chromeless:i,onClick:d,aria:c}=e,u=H("button",yo(!i&&"persona-icon-btn",a));u.type="button",u.setAttribute("aria-label",o),u.title=o;let p=le(t,n??16,"currentColor",r??2);if(p&&u.appendChild(p),d&&u.addEventListener("click",d),c)for(let[m,h]of Object.entries(c))u.setAttribute(m,h);return u}function kg(e){let{icon:t,label:o,variant:n="default",size:r="sm",iconSize:a,className:i,onClick:d,aria:c}=e,u="persona-label-btn";n!=="default"&&(u+=" persona-label-btn--"+n),u+=" persona-label-btn--"+r,i&&(u+=" "+i);let p=H("button",u);if(p.type="button",p.setAttribute("aria-label",o),t){let h=le(t,a??14,"currentColor",2);h&&p.appendChild(h)}let m=H("span");if(m.textContent=o,p.appendChild(m),d&&p.addEventListener("click",d),c)for(let[h,y]of Object.entries(c))p.setAttribute(h,y);return p}function SS(e){let{items:t,selectedId:o,onSelect:n,className:r}=e,a=H("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let i=o,d=[];function c(){for(let p of d)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let m;p.icon?m=qs({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,c(),n(p.id)}}):(m=H("button","persona-icon-btn"+(p.className?" "+p.className:"")),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{i=p.id,c(),n(p.id)})),m.setAttribute("aria-pressed",p.id===i?"true":"false"),d.push({id:p.id,btn:m}),a.appendChild(m)}function u(p){i=p,c()}return{element:a,setSelected:u}}function wS(e){let{label:t,icon:o,iconSize:n,iconOnly:r,menuItems:a,onSelect:i,onPrimary:d,position:c="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:m,className:h,primaryClassName:y,chevronClassName:C}=e,A=H("div","persona-split-btn"+(h?" "+h:"")),M={label:t,className:"persona-split-btn-primary"+(y?" "+y:""),onClick:d},E=r&&o?qs({...M,icon:o,size:n??14}):kg({...M,icon:o,iconSize:n??14}),T=qs({icon:"chevron-down",label:p,size:m??14,className:"persona-split-btn-chevron"+(C?" "+C:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});A.append(E,T);let I=null,b=()=>{if(I)return I;let S=(typeof u=="function"?u():u)??void 0;return I=Us({items:a,onSelect:i,anchor:A,position:c,portal:S,onOpenChange:x=>{T.setAttribute("aria-expanded",x?"true":"false")}}),S||A.appendChild(I.element),I};return A.isConnected?b():requestAnimationFrame(()=>{I||b()}),T.addEventListener("click",S=>{S.stopPropagation(),b().toggle()}),{element:A,primaryButton:E,chevronButton:T,openMenu:()=>b().show(),closeMenu:()=>I?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{I?.destroy(),A.remove()}}}function yu(e){let{label:t,icon:o="chevron-down",menuItems:n,onSelect:r,position:a="bottom-left",portal:i,className:d,hover:c}=e,u=H("div","persona-combo-btn"+(d?" "+d:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",t);let p=H("span","persona-combo-btn-label");p.textContent=t,u.appendChild(p);let m=le(o,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",u.appendChild(m)),c&&(u.style.borderRadius=c.borderRadius??"10px",u.style.padding=c.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=c.background??"",u.style.borderColor=c.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let h=Us({items:n,onSelect:C=>{u.setAttribute("aria-expanded","false"),r(C)},anchor:u,position:a,portal:i});i||u.appendChild(h.element);let y=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",C=>{if(C.stopPropagation(),y())return;let A=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",A?"false":"true"),h.toggle()}),u.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),u.click())}),{element:u,setLabel:C=>{p.textContent=C,u.setAttribute("aria-label",C)},open:()=>{u.setAttribute("aria-expanded","true"),h.show()},close:()=>{u.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let C=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",C?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),u.remove()}}}var Lg=e=>{let t=gr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),o=e.layoutHeaderConfig?.onTitleClick;if(o){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>o()),n.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),o())}))}return t};function PP(e,t,o){if(t?.length)for(let n of t){let{button:r,wrapper:a}=Ns({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?uu(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",n.id),n.shortcut){let i=Ml(n.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(n.menuItems?.length){let i=Us({items:n.menuItems,onSelect:d=>o?.(d),anchor:a,position:"bottom-right"});a.appendChild(i.element),r.addEventListener("click",d=>{d.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>o?.(n.id));e.appendChild(a)}}var Ig=e=>{let{config:t,showClose:o=!0,onClose:n,layoutHeaderConfig:r,onHeaderAction:a}=e,i=t?.launcher??{},d=H("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");d.setAttribute("data-persona-theme-zone","header"),d.style.minHeight=xo.minHeight,d.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",d.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",d.style.boxShadow="var(--persona-header-shadow, none)",d.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,u,p;if(c){let b=yu({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:S=>{let x=N=>{N===!1&&b.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:S}}))},L=c.onSelect(S);L instanceof Promise?L.then(x,()=>{}):x(L)},hover:c.hover,className:""});u=b.element,u.style.color=xo.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=H("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=H("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=xo.titleColor,Object.assign(p.style,Pg),p.textContent=i.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let S=r.onTitleClick;u.addEventListener("click",x=>{x.target.closest("button")||S()}),u.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),S())})}let b=r?.titleRowHover;b&&(u.style.borderRadius=b.borderRadius??"10px",u.style.padding=b.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=b.background??"",u.style.borderColor=b.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}d.appendChild(u);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:y}=Ga(t,{showClose:o,wrapperClassName:m});n&&h.addEventListener("click",n);let C=H("div","persona-flex persona-items-center persona-gap-1");c||PP(C,r?.trailingActions,r?.onAction??a);let A=i.clearChat??{},M=null,E=null;if(A.enabled??!0){let b=A.placement??"inline",S=Xa(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});M=S.button,E=S.wrapper,b==="top-right"?E.style.right="48px":C.appendChild(E)}C.appendChild(y),d.appendChild(C);let T=H("div");T.style.display="none";let I=H("span");return I.style.display="none",{header:d,iconHolder:T,headerTitle:p,headerSubtitle:I,closeButton:h,closeButtonWrapper:y,clearChatButton:M,clearChatButtonWrapper:E}},bu={default:Lg,minimal:Ig},Rg=e=>bu[e]??bu.default,Qa=(e,t,o)=>{if(t?.render){let i=t.render({config:e,onClose:o?.onClose,onClearChat:o?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),d=H("div");d.style.display="none";let c=H("span"),u=H("span"),p=H("button");p.style.display="none";let m=H("div");return m.style.display="none",{header:i,iconHolder:d,headerTitle:c,headerSubtitle:u,closeButton:p,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let n=t?.layout??"default",a=Rg(n)({config:e,showClose:t?.showCloseButton??o?.showClose??!0,onClose:o?.onClose,onClearChat:o?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Vs=e=>{let{config:t}=e,o=Q("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),n=Jc(),r=Q("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:i}=Gc(t);i();let d=Xc(t),c=ja(t),u=Qc(t),p=Yc(t),m=Q("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),u&&(u.previewsContainer.style.gap="8px",m.append(u.previewsContainer),r.append(u.input)),r.append(a);let h=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),C=Q("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return u&&y.append(u.wrapper),c&&C.append(c.wrapper),C.append(d.wrapper),h.append(y,C),r.append(h),r.addEventListener("click",A=>{A.target!==d.button&&A.target!==d.wrapper&&A.target!==c?.button&&A.target!==c?.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&a.focus()}),o.append(n,r,p),{footer:o,suggestions:n,composerForm:r,header:m,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:h,leftActions:y,rightActions:C,setSendButtonMode:d.setMode}};var AS=()=>{let e=Q("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=H("span","persona-pill-peek__icon"),o=Ut(gl,16,"currentColor",1.5);o&&t.appendChild(o);let n=H("span","persona-pill-peek__text"),r=H("span","persona-pill-peek__caret"),a=Ut(Ws,16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,n,r),{root:e,textNode:n}},vu=e=>{let{config:t}=e,o=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=Jc(),r=Yc(t);r.style.display="none";let{textarea:a,attachAutoResize:i}=Gc(t,{defaultMaxLines:5});i();let d=Xc(t),c=ja(t),u=Qc(t);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&m.append(u.wrapper);let h=Q("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&h.append(c.wrapper),h.append(d.wrapper),p.addEventListener("click",A=>{A.target!==d.button&&A.target!==d.wrapper&&A.target!==c?.button&&A.target!==c?.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&a.focus()}),u&&p.append(u.input),p.append(m,a,h);let y=Q("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(y),u&&y.append(u.previewsContainer),o.append(n,p,r);let C=p;return{footer:o,suggestions:n,composerForm:p,header:y,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:C,leftActions:m,rightActions:h,setSendButtonMode:d.setMode}};var kP=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},LP=(e,t)=>{if(!e)return null;let o=kP(e);if(o===null)return null;let n=t?.[e],r=n!==void 0?n:o;return r||null},IP=(e,t)=>{let o=H("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return o.setAttribute("data-stop-reason",e),o.setAttribute("role","note"),o.style.opacity="0.75",o.textContent=t,o},RP=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Wg=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Bg=320,kS=320,HP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),WP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),BP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),OP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),DP=e=>{if(!e||e.length===0)return null;let t=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let o of e){let n=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:o.label}}),r=H("span","persona-mention-chip-icon"),a=le(o.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),n.appendChild(r),n.appendChild(Q("span",{className:"persona-mention-chip-label",text:o.label})),t.appendChild(n)}return t},_P=(e,t)=>{let o=document.createDocumentFragment();for(let n of e){if(n.kind==="text"){o.appendChild(document.createTextNode(n.text));continue}o.appendChild(Cl(n.ref,{readonly:!0,render:t}))}return o},MS="\uE000",TS="\uE001",NP=(e,t,o,n)=>{let r=Math.random().toString(36).slice(2,8),a=h=>`${MS}${r}:${h}${TS}`,i=t.map((h,y)=>h.kind==="text"?h.text:a(y)).join(""),d=o(i);if(!t.every((h,y)=>h.kind==="text"||d.includes(a(y)))){e.replaceChildren(_P(t,n));return}e.innerHTML=d;let u=new RegExp(`${MS}${r}:(\\d+)${TS}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let h=p.nextNode();h;h=p.nextNode())m.push(h);for(let h of m){let y=h;for(let C=u.exec(y.data);C;C=u.exec(y.data)){let A=t[Number(C[1])],M=y.splitText(C.index);M.data=M.data.slice(C[0].length),A?.kind==="mention"&&M.parentNode?.insertBefore(Cl(A.ref,{readonly:!0,render:n}),M),y=M}}},FP=(e,t,o)=>{if(e.length===0)return null;try{let n=H("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let r=0,a=!1,i=()=>{a||(a=!0,n.remove(),o?.())};return e.forEach((d,c)=>{let u=H("img");u.alt=d.alt?.trim()||`Attached image ${c+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${Bg}px`,u.style.maxHeight=`${kS}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&i())}),u.addEventListener("load",()=>{p=!0}),RP(d.image)?(u.src=d.image,n.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(i(),null):n}catch{return o?.(),null}},UP=e=>{if(e.length===0)return null;try{let t=H("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let o=0;return e.forEach(n=>{if(!Wg(n.audio))return;let r=H("audio");r.controls=!0,r.preload="metadata",r.src=n.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Bg}px`,t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},qP=e=>{if(e.length===0)return null;try{let t=H("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let o=0;return e.forEach(n=>{if(!Wg(n.video))return;let r=H("video");r.controls=!0,r.preload="metadata",r.src=n.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Bg}px`,r.style.maxHeight=`${kS}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},VP=e=>{if(e.length===0)return null;try{let t=H("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let o=0;return e.forEach(n=>{if(!Wg(n.data))return;let r=H("a");r.href=n.data,r.download=n.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=n.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},$s=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(o),e.appendChild(n),e.appendChild(r),e},Og=(e,t,o)=>{let n={config:o??{},streaming:!0,location:e,defaultRenderer:$s};if(t){let r=t(n);if(r!==null)return r}return $s()},$P=(e,t)=>{let o=H("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=t==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let r=H("img");r.src=n,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",o.appendChild(r)}else o.textContent=n,o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else o.textContent=t==="user"?"U":"A",o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return o},ES=(e,t,o="div")=>{let n=H(o,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Bl=(e,t="bubble")=>{let o=["persona-message-bubble"];switch(t){case"flat":e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):o.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":o.push("persona-text-sm","persona-leading-relaxed"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:o.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return o},PS={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},jP=(e,t,o="bubble",n)=>{if(!n)return;let r=t==="user"?"user":"assistant",a=PS[o??"bubble"]??PS.bubble;n.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},xu="custom:",zP=e=>`${xu}${e}`,LS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(o=>(o.roles??["assistant"]).includes(t)),Dg=(e,t,o,n)=>{let r=t.showCopy??!0,a=t.showUpvote??!0,i=t.showDownvote??!0,d=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&n?.canRegenerate===!0,u=(t.showEdit??!1)&&n?.canEdit===!0,p=(t.showQuote??!1)&&n?.canQuote!==!1,m=LS(t,e.role);if(!r&&!a&&!i&&!d&&!c&&!u&&!p&&m.length===0){let I=H("div");return I.style.display="none",I.id=`actions-${e.id}`,I.setAttribute("data-actions-for",e.id),I}let h=t.visibility??"hover",y=t.align??"right",C=t.layout??"pill-inside",A={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[y],M={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[C],E=H("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${A} ${M} ${h==="hover"?"persona-message-actions-hover":""}`);E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id);let T=(I,b,S)=>{let x=qs({icon:I,label:b,size:14,className:"persona-message-action-btn",chromeless:!0});return x.setAttribute("data-action",S),x};r&&E.appendChild(T("copy","Copy message","copy")),d&&E.appendChild(T("volume-2","Read aloud","read-aloud")),a&&E.appendChild(T("thumbs-up","Upvote","upvote")),i&&E.appendChild(T("thumbs-down","Downvote","downvote")),c&&E.appendChild(T("refresh-cw","Regenerate response","regenerate")),u&&E.appendChild(T("pencil","Edit message","edit")),p&&E.appendChild(T("quote","Quote message","quote"));for(let I of m)E.appendChild(T(I.iconName??"ellipsis",I.label,zP(I.id)));return E},Ya=(e,t,o,n,r,a)=>{let i=o??{},d=i.layout??"bubble",c=i.avatar,u=i.timestamp,p=c?.show??!1,m=u?.show??!1,h=c?.position??"left",y=u?.position??"below",C=Bl(e.role,d),A=H("div",C.join(" "));A.id=`bubble-${e.id}`,A.setAttribute("data-message-id",e.id),A.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let M=a?.widgetConfig?.theme?.components?.message;jP(A,e.role,d,e.role==="user"?M?.user:M?.assistant),d==="flat"?(A.style.backgroundColor="transparent",A.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=HP(e),T=e.content?.trim()??"",b=E.length>0&&T===Wa,S=fu(a?.widgetConfig?.features?.streamAnimation),x=a?.widgetConfig?.features?.streamAnimation?.plugins,L=e.role==="assistant"&&S.type!=="none"?Pl(S.type,x):null,N=e.role==="assistant"&&L?.isAnimating?.(e)===!0,X=e.role==="assistant"&&L!==null&&(!!e.streaming||N);X&&L?.bubbleClass&&A.classList.add(L.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),e.streaming&&V.classList.add("persona-content-streaming"),X&&L&&(L.containerClass&&V.classList.add(L.containerClass),V.style.setProperty("--persona-stream-step",`${S.speed}ms`),V.style.setProperty("--persona-stream-duration",`${S.duration}ms`));let P=X?mu(e.content??"",S.buffer,L,e,!!e.streaming):e.content??"",O=()=>{let Pe=t({text:P,message:e,streaming:!!e.streaming,raw:e.rawContent});return X&&L?.wrap==="char"?kl(Pe,"char",e.id,{skipTags:L.skipTags}):X&&L?.wrap==="word"?kl(Pe,"word",e.id,{skipTags:L.skipTags}):Pe},D=null;if(b?(D=document.createElement("div"),D.innerHTML=O(),D.style.display="none",V.appendChild(D)):e.contentSegments?.length?NP(V,e.contentSegments,Pe=>t({text:Pe,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=O(),X&&L?.useCaret&&!b&&T){let Pe=gu(),q=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ue=q[q.length-1];if(Ue?.parentNode)Ue.parentNode.insertBefore(Pe,Ue.nextSibling);else{let Je=V.lastElementChild;Je?Je.appendChild(Pe):V.appendChild(Pe)}}if(m&&y==="inline"&&e.createdAt){let Pe=ES(e,u,"span");Pe.classList.add("persona-timestamp-inline");let q=V.lastElementChild;q?q.appendChild(Pe):V.appendChild(Pe)}if(E.length>0){let Pe=FP(E,!b&&!!T,()=>{b&&D&&(D.style.display="")});Pe?A.appendChild(Pe):b&&D&&(D.style.display="")}let W=WP(e);if(W.length>0){let Pe=UP(W);Pe&&A.appendChild(Pe)}let ee=BP(e);if(ee.length>0){let Pe=qP(ee);Pe&&A.appendChild(Pe)}let G=OP(e);if(G.length>0){let Pe=VP(G);Pe&&A.appendChild(Pe)}let ue=e.contentSegments?.length?null:DP(e.contextMentions);if(ue&&A.appendChild(ue),A.appendChild(V),m&&y==="below"&&e.createdAt){let Pe=ES(e,u);Pe.classList.add("persona-mt-1"),A.appendChild(Pe)}let ae=e.role==="assistant"?LP(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Pe=!!(P&&P.trim()),q=S.placeholder==="skeleton",Ue=q&&S.buffer==="line"&&Pe;if(Pe)Ue&&A.appendChild(Ll());else if(q)A.appendChild(Ll());else{let Je=Og("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Je&&A.appendChild(Je)}}ae&&e.stopReason&&!e.streaming&&(T||(V.style.display="none"),A.appendChild(IP(e.stopReason,ae)));let ye=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&n?.enabled!==!1,Re=a?.actionEligibility,be=e.role==="user"&&!e.streaming&&n?.enabled!==!1&&(n?.showEdit===!0&&Re?.canEdit===!0||n?.showQuote===!0&&Re?.canQuote===!0||LS(n,"user").length>0);if((ye||be)&&n){let Pe=Dg(e,be?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,r,Re);A.appendChild(Pe)}if(!p||e.role==="system")return A;let pe=H("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),yt=$P(c,e.role);return h==="right"||h==="left"&&e.role==="user"?pe.append(A,yt):pe.append(yt,A),pe},IS=(e,t,o,n,r,a)=>{let i=o??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ya(e,t,o,n,r,a)};var KP=40,GP=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let o=null;try{o=t()}catch(n){console.warn("[persona] welcome.icon renderer threw",n)}if(!o){e.hidden=!0;return}e.appendChild(o),e.hidden=!1;return}if(t.type==="lucide"){let o=le(t.name,KP);if(!o){e.hidden=!0;return}e.appendChild(o)}else t.type==="image"?e.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Q("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},RS=(e,t,o={})=>{let n=Q("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let r=H("p","persona-welcome-kicker");r.hidden=!0;let a=H("h2","persona-welcome-title"),i=H("p","persona-welcome-subtitle"),d=Q("div",{className:"persona-welcome-head-text"},r,a),c=Q("div",{className:"persona-welcome-title-row"},n,d);return{host:Q("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:o.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,i,t),iconHolder:n,kicker:r,title:a,subtitle:i,starterSuggestions:t}},Ja=(e,t,o)=>{t.hidden=!o,t.style.display=o?"":"none",e.classList.toggle("persona-gap-6",o),e.classList.toggle("persona-gap-3",!o)},Su=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",GP(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},XP="data-persona-welcome-plugin",HS="data-persona-welcome-overlay",Cu="persona-welcome-overlay-active",_g=new WeakMap,Ng=(e,t,o)=>{o.setAttribute(XP,""),t.appendChild(o),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(HS,""),e.classList.contains(Cu)||(_g.set(e,e.scrollTop),e.classList.add(Cu),e.scrollTop=0)},Fg=(e,t,o)=>{o&&o!==t&&o.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(HS),e.classList.contains(Cu)&&(e.classList.remove(Cu),e.scrollTop=_g.get(e)??e.scrollTop,_g.delete(e))},WS=()=>{let e=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},wu=(e,t,o)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let n=o?.layout?.messages?.layout??"bubble",r=Q("div",{className:Bl("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:n==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Q("div",{className:"persona-flex"},r)),e.hidden=!1},BS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,OS=(e,t)=>{if(BS()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let o=e.getBoundingClientRect(),n=e.parentElement,r=0,a=0,i=0;if(n){let C=getComputedStyle(n);r=parseFloat(C.rowGap)||0;let A=e.previousElementSibling,M=e.nextElementSibling,T=n.getBoundingClientRect().top+(parseFloat(C.borderTopWidth)||0)+(parseFloat(C.paddingTop)||0)-n.scrollTop;a=Math.max(0,A?o.top-A.getBoundingClientRect().bottom-r:o.top-T),i=Math.max(0,M?M.getBoundingClientRect().top-o.bottom-r:0)}let d=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),u=parseFloat(c.paddingTop)||0,p=parseFloat(c.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${o.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${a}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,y=()=>{h||(h=!0,e.style.overflow=d,t(m))};return m.finished.then(y).catch(y),m},DS=(e,t,o)=>{if(t<=1||BS()||typeof e.animate!="function"||!e.isConnected)return null;let n=o==="drop"?-t:t;return e.animate([{transform:`translateY(${n}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var QP="Hello \u{1F44B}",YP="I can answer questions and help you get things done here.",_S=new WeakSet,Co=(e,t)=>!!e&&e[t]!==void 0,JP=(e,t)=>{!e||e.debug!==!0||!t.length||_S.has(e)||(_S.add(e),t.forEach(o=>console.warn(`[persona] ${o}`)))},Cn=e=>{let t=e?.welcome,o=e?.copy,n=Co(t,"variant")?t.variant:o?.showWelcomeCard===!1?"none":"card",r=n==="hero"?"on-first-message":Co(t,"dismiss")?t.dismiss:"never",a=[];Co(t,"title")&&Co(o,"welcomeTitle")&&a.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Co(t,"subtitle")&&Co(o,"welcomeSubtitle")&&a.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Co(t,"variant")&&Co(o,"showWelcomeCard")&&a.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),n==="hero"&&Co(t,"message")&&a.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),n==="hero"&&Co(t,"dismiss")&&t.dismiss!=="on-first-message"&&a.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let i=t?.anchor==="center"?"center":"bottom",d=Al(t?.anchorComposerTop)!==null;return Co(t,"anchorComposerTop")&&!d&&a.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),i!=="center"&&(Co(t,"anchorComposerTop")||Co(t,"composerGap"))&&a.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),JP(e,a),{title:Co(t,"title")?t.title:o?.welcomeTitle??QP,kicker:t?.kicker??"",subtitle:Co(t,"subtitle")?t.subtitle:o?.welcomeSubtitle??YP,icon:t?.icon,align:t?.align==="start"||t?.align==="center"?t.align:void 0,iconPlacement:t?.icon&&typeof t.icon!="function"&&t.icon.placement==="inline"?"inline":"above",variant:n,dismiss:r,message:n==="hero"?void 0:t?.message,anchor:i,anchorComposerTop:d?t.anchorComposerTop:"44%",composerGap:t?.composerGap?.trim()||lu}},NS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Yr=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(o=>o.role==="user");var FS="16px",qg="10px",Vg="14px",US=e=>{let t=e?.launcher?.enabled??!0,o=Ct(e);if(Qr(e)){let p=e?.launcher?.composerBar??{},m=H("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=p.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??ro);let h=H("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");h.style.width="100%",m.appendChild(h);let y=H("div","persona-widget-pill-root");return y.setAttribute("data-persona-composer-bar",""),y.dataset.state="collapsed",y.dataset.expandedSize=p.expandedSize??"anchored",y.style.zIndex=String(e?.launcher?.zIndex??ro),{wrapper:m,panel:h,pillRoot:y}}if(o){let p=H("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=H("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(m),{wrapper:p,panel:m}}if(!t){let p=H("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=H("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),h=e?.launcher?.width??"100%";return p.style.width=h,m.style.width="100%",p.appendChild(m),{wrapper:p,panel:m}}let r=e?.launcher??{},a=r.position&&Xo[r.position]?Xo[r.position]:Xo["bottom-right"],i=H("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??ro);let d=H("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=e?.launcher?.width??e?.launcherWidth??Ko;return d.style.width=u,d.style.maxWidth=u,i.appendChild(d),{wrapper:i,panel:d}},$g=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Mg(e)}});return t.hidden=!0,t},qS=(e,t)=>{let o=$g("starter"),n=RS(e,o,{flatShadow:Ct(e)}),r=Cn(e);Su(n,r),Ja(t,n.host,Yr(r,e?.initialMessages));let a=WS();return wu(a,r.message,e),{welcome:n,greetingHost:a}},ZP=(e,t)=>{let o=H("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");o.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:r}=Ga(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:FS,iconSize:qg});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,i=null,d=null;if(a){let L=Xa(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:FS,iconSize:Vg});i=L.button,d=L.wrapper,d.style.position="absolute",d.style.top="8px",d.style.right="32px",d.style.zIndex="10"}let c=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:m}=qS(e,u),{host:h,title:y,subtitle:C}=p,A=p.starterSuggestions,M=H("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),E=$g("followUp"),T=Gr(e,!0);T&&(M.style.maxWidth=T,M.style.marginLeft="auto",M.style.marginRight="auto",M.style.width="100%"),u.append(h,m,M,E);let I=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),b=vu({config:e}),{root:S,textNode:x}=AS();return o.append(c,r,u,I),d&&o.appendChild(d),{container:o,body:u,messagesWrapper:M,starterSuggestions:A,transcriptSuggestions:E,composerOverlay:I,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:h,welcomeIconHolder:p.iconHolder,greetingHost:m,introKicker:p.kicker,introTitle:y,introSubtitle:C,closeButton:n,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:d,iconHolder:H("span"),headerTitle:H("span"),headerSubtitle:H("span"),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:S,peekTextNode:x}},VS=(e,t=!0)=>{if(Qr(e))return ZP(e,t);let o=Q("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),n=e?.layout?.header,r=e?.layout?.showHeader!==!1,a=n?Qa(e,n,{showClose:t}):gr({config:e,showClose:t}),i=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:c}=qS(e,i),{host:u,title:p,subtitle:m}=d,h=d.starterSuggestions,y=H("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),C=$g("followUp"),A=Gr(e,!1);A&&(y.style.maxWidth=A,y.style.marginLeft="auto",y.style.marginRight="auto",y.style.width="100%"),i.append(u,c,y,C);let M=Vs({config:e}),E=e?.layout?.showFooter!==!1;r?Fs(o,a,e):(a.header.style.display="none",Fs(o,a,e)),o.append(i);let T=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return E||(M.footer.style.display="none"),o.append(M.footer),o.append(T),{container:o,body:i,messagesWrapper:y,starterSuggestions:h,transcriptSuggestions:C,composerOverlay:T,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,welcomeHost:u,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:p,introSubtitle:m,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode}};var jg=(e,t)=>{let o=H("button");o.type="button",o.innerHTML=`
|
|
30
30
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
31
31
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
32
32
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -34,14 +34,14 @@ _Details: ${o.message}_`:n}var sm=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
34
34
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
35
35
|
</span>
|
|
36
36
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
37
|
-
`,o.addEventListener("click",t);let n=a=>{let i=a.launcher??{},d=Ct(a),c=o.querySelector("[data-role='launcher-title']");if(c){let H=i.title??"Chat Assistant";c.textContent=H,c.setAttribute("title",H)}let u=o.querySelector("[data-role='launcher-subtitle']");if(u){let H=i.subtitle??"Here to help you get answers fast";u.textContent=H,u.setAttribute("title",H)}let p=o.querySelector(".persona-flex-col");p&&(i.textHidden||d?p.style.display="none":p.style.display="");let m=o.querySelector("[data-role='launcher-icon']");if(m)if(i.agentIconHidden)m.style.display="none";else{let H=i.agentIconSize??"40px";if(m.style.height=H,m.style.width=H,i.agentIconBackgroundColor?(m.style.backgroundColor=i.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",i.agentIconName){let b=parseFloat(H)||24,w=le(i.agentIconName,b*.6,"var(--persona-text-inverse, #ffffff)",1.5);w?(m.appendChild(w),m.style.display=""):(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}else i.iconUrl?m.style.display="none":(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}let h=o.querySelector("[data-role='launcher-image']");if(h){let H=i.agentIconSize??"40px";h.style.height=H,h.style.width=H,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(h.src=i.iconUrl,h.style.display="block"):h.style.display="none"}let y=o.querySelector("[data-role='launcher-call-to-action-icon']");if(y){let H=i.callToActionIconSize??"32px";y.style.height=H,y.style.width=H,i.callToActionIconBackgroundColor?(y.style.backgroundColor=i.callToActionIconBackgroundColor,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(y.style.color=i.callToActionIconColor,y.classList.remove("persona-text-persona-call-to-action")):(y.style.color="",y.classList.add("persona-text-persona-call-to-action"));let b=0;if(i.callToActionIconPadding?(y.style.boxSizing="border-box",y.style.padding=i.callToActionIconPadding,b=(parseFloat(i.callToActionIconPadding)||0)*2):(y.style.boxSizing="",y.style.padding=""),i.callToActionIconHidden)y.style.display="none";else if(y.style.display=d?"none":"",y.innerHTML="",i.callToActionIconName){let w=parseFloat(H)||24,C=Math.max(w-b,8),L=le(i.callToActionIconName,C,"currentColor",1.5);L?y.appendChild(L):y.textContent=i.callToActionIconText??"\u2197"}else y.textContent=i.callToActionIconText??"\u2197"}let x=i.position&&Xo[i.position]?Xo[i.position]:Xo["bottom-right"],M="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",S="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";o.className=d?S:`${M} ${x}`,d||(o.style.zIndex=String(i.zIndex??ro));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",P="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";o.style.border=i.border??k,o.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:P,d?(o.style.width="0",o.style.minWidth="0",o.style.maxWidth="0",o.style.padding="0",o.style.overflow="hidden",o.style.border="none",o.style.boxShadow="none"):(o.style.width="",o.style.minWidth="",o.style.maxWidth=i.collapsedMaxWidth??"",o.style.justifyContent="",o.style.padding="",o.style.overflow="")},r=()=>{o.removeEventListener("click",t),o.remove()};return e&&n(e),{element:o,update:n,destroy:r}},GP="teaser-dismissed",qS=new Set,US=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${GP}`},XP=(e,t)=>{if(qS.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},QP=(e,t)=>{if(qS.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},YP=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,JP=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Ct(e??{})?null:t},VS=(e,t)=>{let o=R("div","persona-launcher-surface");o.setAttribute("data-persona-launcher-surface","true");let n=e??{},r=null,a=null,i=null,d=null,c=null,u=!1,p=!1,m=!1,h=!1,y=()=>(r?.frequency??"once")==="once"&&n.persistState!==!1,x=()=>{c!==null&&(clearTimeout(c),c=null)},M=()=>{!a||!u||(u=!1,a.hidden=!0)},S=ee=>{x(),m=!0,M(),QP(US(n),ee&&y())},k=ee=>{!r||m||S(ee==="user"&&u)},P=()=>{c=null,!(!a||m||h)&&(p=!0,u=!0,a.hidden=!1,!(YP()||typeof a.animate!="function")&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},H=()=>{!r||!a||m||p||h||XP(US(n),y())||(x(),c=setTimeout(P,Math.max(0,r.delayMs??0)))},b=()=>{S(y()),t()},w=ee=>{ee.stopPropagation(),S(y())},L=$g(e,()=>{k("user"),t()}),N=()=>{x(),d?.removeEventListener("click",b),i?.removeEventListener("click",w),a?.remove(),a=null,d=null,i=null,u=!1},X=()=>{d=Q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),d.addEventListener("click",b),i=Q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",w),a=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},d,i),o.insertBefore(a,L.element)},V=()=>{let ee=n.launcher?.position??"bottom-right",G=Xo[ee]??Xo["bottom-right"];if(!a){o.className="persona-launcher-surface",o.removeAttribute("data-teaser"),o.style.zIndex="",L.element.style.position="";return}o.className=yo("persona-launcher-surface",G),o.setAttribute("data-teaser",ee),o.style.zIndex=String(n.launcher?.zIndex??ro),L.element.style.position="static"},T=ee=>{let G=JP(ee);if(r=G,!G){N();return}a||X(),d.textContent=G.text,i.hidden=G.dismissible===!1,i.setAttribute("aria-label",G.dismissLabel??"Dismiss message"),H()},O=ee=>{n=ee,L.update(ee),T(ee),V()},D=(ee,G="user")=>{h=ee,ee&&k(G)},W=()=>{N(),L.destroy(),o.remove()};return o.appendChild(L.element),e&&(T(e),V()),{element:o,launcher:L,get teaser(){return a?{element:a,show:P,dismiss:S}:null},setPanelOpen:D,update:O,destroy:W}};var $S=({config:e,showClose:t})=>{let{wrapper:o,panel:n,pillRoot:r}=_S(e),a=FS(e,t),i={wrapper:o,panel:n,pillRoot:r},d={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},u={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:i,panelElements:a,transcript:d,header:c,composer:u,replaceHeader:h=>(c.element.replaceWith(h.header),c.element=h.header,c.iconHolder=h.iconHolder,c.headerTitle=h.headerTitle,c.headerSubtitle=h.headerSubtitle,c.closeButton=h.closeButton,c.closeButtonWrapper=h.closeButtonWrapper,c.clearChatButton=h.clearChatButton,c.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{u.footer.replaceWith(h),u.footer=h}}},jg=({config:e,plugins:t,onToggle:o})=>{let n=t.find(a=>a.renderLauncher);if(n?.renderLauncher){let a=n.renderLauncher({config:e,defaultRenderer:()=>$g(e,o).element,onToggle:o});if(a)return{instance:null,element:a}}let r=VS(e,o);return{instance:r,element:r.element}};var ZP=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},ek=(e,t,o)=>`${ZP(e)}plugin:${t}:${o}`,jS=e=>{let t=new Map,o=!1,n=()=>{if(o||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return o=!0,null}};return r=>{let a=i=>ek(e(),r,i);return{get:i=>{let d=a(i),c=n();if(c)try{return c.getItem(d)}catch{o=!0}return t.get(d)??null},set:(i,d)=>{let c=a(i),u=n();if(u)try{u.setItem(c,d);return}catch{o=!0}t.set(c,d)},remove:i=>{let d=a(i);t.delete(d);let c=n();if(c)try{c.removeItem(d)}catch{o=!0}}}}};var Za=(e,t,o)=>{let n=o;for(let r of t){let a=R("span","persona-tool-char");a.style.setProperty("--char-index",String(n)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),n++}return n};var tk=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],ok="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",nk="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",rk=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Au=(e,t)=>{let o=R("div",["persona-message-bubble",e,...tk].join(" "));return o.id=`bubble-${t}`,o.setAttribute("data-message-id",t),o},Mu=e=>{let t=R("button",e.expandable?ok:nk);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},zg=(e,t,o)=>{e.innerHTML="";let n=Ut(t?Ws:ul,16,o,2);n?e.appendChild(n):e.textContent=t?"Hide":"Show"},Tu=(e,t,o)=>{if(!o.expandable)return e.append(t),null;let n=R("div","persona-flex persona-items-center");zg(n,o.expanded,o.iconColor);let r=R("div",o.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(n),e.append(t,r),n},Eu=e=>{let t=R("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let o=e.renderPreview?.();rk(t,o)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Pu=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&zg(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},ku=(e,t,o)=>{let n=o.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${o.previewKind}"]`);if(!r||!a)return;r.setAttribute("aria-expanded",n?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&zg(c,n,o.iconColor),a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")};var ei=new Set,sk=(e,t)=>{let o=e.reasoning?.chunks.join("").trim()??"";return o?o.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).slice(0,t).join(`
|
|
38
|
-
`):""},
|
|
37
|
+
`,o.addEventListener("click",t);let n=a=>{let i=a.launcher??{},d=Ct(a),c=o.querySelector("[data-role='launcher-title']");if(c){let I=i.title??"Chat Assistant";c.textContent=I,c.setAttribute("title",I)}let u=o.querySelector("[data-role='launcher-subtitle']");if(u){let I=i.subtitle??"Here to help you get answers fast";u.textContent=I,u.setAttribute("title",I)}let p=o.querySelector(".persona-flex-col");p&&(i.textHidden||d?p.style.display="none":p.style.display="");let m=o.querySelector("[data-role='launcher-icon']");if(m)if(i.agentIconHidden)m.style.display="none";else{let I=i.agentIconSize??"40px";if(m.style.height=I,m.style.width=I,i.agentIconBackgroundColor?(m.style.backgroundColor=i.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",i.agentIconName){let b=parseFloat(I)||24,S=le(i.agentIconName,b*.6,"var(--persona-text-inverse, #ffffff)",1.5);S?(m.appendChild(S),m.style.display=""):(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}else i.iconUrl?m.style.display="none":(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}let h=o.querySelector("[data-role='launcher-image']");if(h){let I=i.agentIconSize??"40px";h.style.height=I,h.style.width=I,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(h.src=i.iconUrl,h.style.display="block"):h.style.display="none"}let y=o.querySelector("[data-role='launcher-call-to-action-icon']");if(y){let I=i.callToActionIconSize??"32px";y.style.height=I,y.style.width=I,i.callToActionIconBackgroundColor?(y.style.backgroundColor=i.callToActionIconBackgroundColor,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(y.style.color=i.callToActionIconColor,y.classList.remove("persona-text-persona-call-to-action")):(y.style.color="",y.classList.add("persona-text-persona-call-to-action"));let b=0;if(i.callToActionIconPadding?(y.style.boxSizing="border-box",y.style.padding=i.callToActionIconPadding,b=(parseFloat(i.callToActionIconPadding)||0)*2):(y.style.boxSizing="",y.style.padding=""),i.callToActionIconHidden)y.style.display="none";else if(y.style.display=d?"none":"",y.innerHTML="",i.callToActionIconName){let S=parseFloat(I)||24,x=Math.max(S-b,8),L=le(i.callToActionIconName,x,"currentColor",1.5);L?y.appendChild(L):y.textContent=i.callToActionIconText??"\u2197"}else y.textContent=i.callToActionIconText??"\u2197"}let C=i.position&&Xo[i.position]?Xo[i.position]:Xo["bottom-right"],A="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";o.className=d?M:`${A} ${C}`,d||(o.style.zIndex=String(i.zIndex??ro));let E="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",T="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";o.style.border=i.border??E,o.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:T,d?(o.style.width="0",o.style.minWidth="0",o.style.maxWidth="0",o.style.padding="0",o.style.overflow="hidden",o.style.border="none",o.style.boxShadow="none"):(o.style.width="",o.style.minWidth="",o.style.maxWidth=i.collapsedMaxWidth??"",o.style.justifyContent="",o.style.padding="",o.style.overflow="")},r=()=>{o.removeEventListener("click",t),o.remove()};return e&&n(e),{element:o,update:n,destroy:r}},ek="teaser-dismissed",jS=new Set,$S=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${ek}`},tk=(e,t)=>{if(jS.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},ok=(e,t)=>{if(jS.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},nk=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,rk=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Ct(e??{})?null:t},zS=(e,t)=>{let o=H("div","persona-launcher-surface");o.setAttribute("data-persona-launcher-surface","true");let n=e??{},r=null,a=null,i=null,d=null,c=null,u=!1,p=!1,m=!1,h=!1,y=()=>(r?.frequency??"once")==="once"&&n.persistState!==!1,C=()=>{c!==null&&(clearTimeout(c),c=null)},A=()=>{!a||!u||(u=!1,a.hidden=!0)},M=ee=>{C(),m=!0,A(),ok($S(n),ee&&y())},E=ee=>{!r||m||M(ee==="user"&&u)},T=()=>{c=null,!(!a||m||h)&&(p=!0,u=!0,a.hidden=!1,!(nk()||typeof a.animate!="function")&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},I=()=>{!r||!a||m||p||h||tk($S(n),y())||(C(),c=setTimeout(T,Math.max(0,r.delayMs??0)))},b=()=>{M(y()),t()},S=ee=>{ee.stopPropagation(),M(y())},L=jg(e,()=>{E("user"),t()}),N=()=>{C(),d?.removeEventListener("click",b),i?.removeEventListener("click",S),a?.remove(),a=null,d=null,i=null,u=!1},X=()=>{d=Q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),d.addEventListener("click",b),i=Q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",S),a=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},d,i),o.insertBefore(a,L.element)},V=()=>{let ee=n.launcher?.position??"bottom-right",G=Xo[ee]??Xo["bottom-right"];if(!a){o.className="persona-launcher-surface",o.removeAttribute("data-teaser"),o.style.zIndex="",L.element.style.position="";return}o.className=yo("persona-launcher-surface",G),o.setAttribute("data-teaser",ee),o.style.zIndex=String(n.launcher?.zIndex??ro),L.element.style.position="static"},P=ee=>{let G=rk(ee);if(r=G,!G){N();return}a||X(),d.textContent=G.text,i.hidden=G.dismissible===!1,i.setAttribute("aria-label",G.dismissLabel??"Dismiss message"),I()},O=ee=>{n=ee,L.update(ee),P(ee),V()},D=(ee,G="user")=>{h=ee,ee&&E(G)},W=()=>{N(),L.destroy(),o.remove()};return o.appendChild(L.element),e&&(P(e),V()),{element:o,launcher:L,get teaser(){return a?{element:a,show:T,dismiss:M}:null},setPanelOpen:D,update:O,destroy:W}};var KS=({config:e,showClose:t})=>{let{wrapper:o,panel:n,pillRoot:r}=US(e),a=VS(e,t),i={wrapper:o,panel:n,pillRoot:r},d={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},u={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:i,panelElements:a,transcript:d,header:c,composer:u,replaceHeader:h=>(c.element.replaceWith(h.header),c.element=h.header,c.iconHolder=h.iconHolder,c.headerTitle=h.headerTitle,c.headerSubtitle=h.headerSubtitle,c.closeButton=h.closeButton,c.closeButtonWrapper=h.closeButtonWrapper,c.clearChatButton=h.clearChatButton,c.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{u.footer.replaceWith(h),u.footer=h}}},zg=({config:e,plugins:t,onToggle:o})=>{let n=t.find(a=>a.renderLauncher);if(n?.renderLauncher){let a=n.renderLauncher({config:e,defaultRenderer:()=>jg(e,o).element,onToggle:o});if(a)return{instance:null,element:a}}let r=zS(e,o);return{instance:r,element:r.element}};var sk=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},ak=(e,t,o)=>`${sk(e)}plugin:${t}:${o}`,GS=e=>{let t=new Map,o=!1,n=()=>{if(o||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return o=!0,null}};return r=>{let a=i=>ak(e(),r,i);return{get:i=>{let d=a(i),c=n();if(c)try{return c.getItem(d)}catch{o=!0}return t.get(d)??null},set:(i,d)=>{let c=a(i),u=n();if(u)try{u.setItem(c,d);return}catch{o=!0}t.set(c,d)},remove:i=>{let d=a(i);t.delete(d);let c=n();if(c)try{c.removeItem(d)}catch{o=!0}}}}};var Za=(e,t,o)=>{let n=o;for(let r of t){let a=H("span","persona-tool-char");a.style.setProperty("--char-index",String(n)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),n++}return n};var ik=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],lk="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",dk="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",ck=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Au=(e,t)=>{let o=H("div",["persona-message-bubble",e,...ik].join(" "));return o.id=`bubble-${t}`,o.setAttribute("data-message-id",t),o},Mu=e=>{let t=H("button",e.expandable?lk:dk);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},Kg=(e,t,o)=>{e.innerHTML="";let n=Ut(t?Ws:ul,16,o,2);n?e.appendChild(n):e.textContent=t?"Hide":"Show"},Tu=(e,t,o)=>{if(!o.expandable)return e.append(t),null;let n=H("div","persona-flex persona-items-center");Kg(n,o.expanded,o.iconColor);let r=H("div",o.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(n),e.append(t,r),n},Eu=e=>{let t=H("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let o=e.renderPreview?.();ck(t,o)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Pu=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Kg(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},ku=(e,t,o)=>{let n=o.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${o.previewKind}"]`);if(!r||!a)return;r.setAttribute("aria-expanded",n?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&Kg(c,n,o.iconColor),a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")};var ei=new Set,uk=(e,t)=>{let o=e.reasoning?.chunks.join("").trim()??"";return o?o.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).slice(0,t).join(`
|
|
38
|
+
`):""},XS=(e,t)=>{ku(e,t,{stateSet:ei,previewKind:"reasoning",iconColor:"currentColor"})},Gg=(e,t)=>{let o=e.reasoning,n=Au("persona-reasoning-bubble",e.id);if(!o)return n;let r=t?.features?.reasoningDisplay??{},a=r.expandable!==!1,i=a&&ei.has(e.id),d=o.status!=="complete",c=uk(e,r.previewMaxLines??3),u=Mu({expandable:a,expanded:i,bubbleType:"reasoning"}),p=H("div","persona-flex persona-flex-col persona-text-left"),m=H("span","persona-text-xs persona-text-persona-primary"),h="Thinking...",y=t?.reasoning??{},C=String(o.startedAt??Date.now()),A=()=>{let W=H("span","");return W.setAttribute("data-tool-elapsed",C),W.textContent=xc(o),W},M=y.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:h,previewText:c,isActive:d,config:t??{},elapsed:xc(o),createElapsedElement:A});typeof M=="string"&&M.trim()?(m.textContent=M,p.appendChild(m)):M instanceof HTMLElement?p.appendChild(M):(m.textContent=h,p.appendChild(m));let E=H("span","persona-text-xs persona-text-persona-primary");E.textContent=ox(o),p.appendChild(E);let T=r.loadingAnimation??"none",I=y.activeTextTemplate,b=y.completeTextTemplate,S=d?I:b,x=M instanceof HTMLElement,L=(W,ee)=>{m.textContent="";let G=Cc(W,""),ue=0;for(let ae of G){let ye=ae.styles.length>0?(()=>{let Re=H("span",ae.styles.map(be=>`persona-tool-text-${be}`).join(" "));return m.appendChild(Re),Re})():m;if(ae.isDuration&&d)ye.appendChild(A());else{let Re=ae.isDuration?xc(o):ae.text;ee?ue=Za(ye,Re,ue):ye.appendChild(document.createTextNode(Re))}}};if(!x&&S)if(E.style.display="none",m.style.display="",d&&T!=="none"){let W=y.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),T==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),L(S,!1)):(m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),T==="shimmer-color"&&(y.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",y.loadingAnimationColor),y.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",y.loadingAnimationSecondaryColor)),L(S,!0))}else L(S,!1);else if(!x&&d&&T!=="none"){m.style.display="";let W=y.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),T==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`);else{m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),T==="shimmer-color"&&(y.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",y.loadingAnimationColor),y.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",y.loadingAnimationSecondaryColor));let ee=m.textContent||h;m.textContent="",Za(m,ee,0)}o.status==="complete"&&(m.style.display="none")}else x||(o.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!x){let W=H("span","persona-reasoning-header-icon"),ee=le(r.iconName,16,"currentColor",2);ee&&(W.appendChild(ee),u.appendChild(W))}let N="currentColor",X=Tu(u,p,{expandable:a,expanded:i,iconColor:N,metaGap:!1}),V=Eu({bubble:n,previewKind:"reasoning",expanded:i,isActive:d,previewText:c,activePreview:r.activePreview,activeMinHeight:r.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:c,isActive:d,config:t??{}})});if(!a)return n.append(u,V),n;let P=H("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");P.style.display=i?"":"none";let O=o.chunks.join(""),D=H("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return D.textContent=O||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),P.appendChild(D),Pu({expanded:i,header:u,toggleIcon:X,content:P,collapsedPreview:V,iconColor:N}),n.append(u,V,P),n};var ti=new Set,QS=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",pk=(e,t)=>{let o=e.toolCall;if(!o)return"";let n=(o.chunks??[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
39
39
|
`);let r=bc(o.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
40
|
-
`):""},Gg=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},ik=(e,t)=>{let o=e.toolCall,n=t?.features?.toolCallDisplay,r=n?.collapsedMode??"tool-call",a=o?.success===!1?o.error||"Tool failed":ak(e,n?.previewMaxLines??3),i=o?nx(o):"";if(!o)return{summary:i,previewText:a,isActive:!1};let d=o.status!=="complete",c=t?.toolCall??{},u=i;return r==="tool-name"?u=o.name?.trim()||i:r==="tool-preview"&&a&&(u=a),d&&c.activeTextTemplate?u=Gf(o,c.activeTextTemplate,u):!d&&c.completeTextTemplate&&(u=Gf(o,c.completeTextTemplate,u)),o.success===!1&&(u+=" \xB7 Failed"),{summary:u,previewText:a,isActive:d}},GS=(e,t,o)=>{ku(e,t,{stateSet:ti,previewKind:"tool",iconColor:KS(o?.toolCall??{})})},Xg=(e,t)=>{let o=e.toolCall,n=t?.toolCall??{},r=Au("persona-tool-bubble",e.id);if(n.backgroundColor&&(r.style.backgroundColor=n.backgroundColor),n.borderColor&&(r.style.borderColor=n.borderColor),n.borderWidth&&(r.style.borderWidth=n.borderWidth),n.borderRadius&&(r.style.borderRadius=n.borderRadius),r.style.boxShadow=n.shadow!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!o)return r;let a=t?.features?.toolCallDisplay??{},i=a.expandable!==!1,d=i&&ti.has(e.id),{summary:c,previewText:u,isActive:p}=ik(e,t),m=Mu({expandable:i,expanded:d,bubbleType:"tool"});n.headerBackgroundColor&&(m.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(m.style.paddingLeft=n.headerPaddingX,m.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(m.style.paddingTop=n.headerPaddingY,m.style.paddingBottom=n.headerPaddingY);let h=R("div","persona-flex persona-flex-col persona-text-left"),y=R("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(y.style.color=n.headerTextColor);let x=String(o.startedAt??Date.now()),M=()=>{let T=R("span","");return T.setAttribute("data-tool-elapsed",x),T.textContent=rl(o),T},S=n.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:c,previewText:u,collapsedMode:a.collapsedMode??"tool-call",isActive:p,config:t??{},elapsed:rl(o),createElapsedElement:M});typeof S=="string"&&S.trim()?(y.textContent=S,h.appendChild(y)):S instanceof HTMLElement?h.appendChild(S):(y.textContent=c,h.appendChild(y));let k=a.loadingAnimation??"none",P=n.activeTextTemplate,H=n.completeTextTemplate,b=p?P:H,w=S instanceof HTMLElement,C=(T,O)=>{y.textContent="";let D=o.name?.trim()||"tool",W=Cc(T,D),ee=0;for(let G of W){let ue=G.styles.length>0?(()=>{let ae=R("span",G.styles.map(ye=>`persona-tool-text-${ye}`).join(" "));return y.appendChild(ae),ae})():y;if(G.isDuration&&p)ue.appendChild(M());else{let ae=G.isDuration?rl(o):G.text;O?ee=Za(ue,ae,ee):ue.appendChild(document.createTextNode(ae))}}};if(!w)if(p&&k!=="none"){let T=n.loadingAnimationDuration??2e3;if(y.setAttribute("data-preserve-animation","true"),k==="pulse")y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${T}ms`),b&&C(b,!1);else if(y.classList.add(`persona-tool-loading-${k}`),y.style.setProperty("--persona-tool-anim-duration",`${T}ms`),k==="shimmer-color"&&(n.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),b)C(b,!0);else{let O=y.textContent||c;y.textContent="",Za(y,O,0)}}else b&&C(b,!1);let L=KS(n),N=Tu(m,h,{expandable:i,expanded:d,iconColor:L,metaGap:!0}),X=Eu({bubble:r,previewKind:"tool",expanded:d,isActive:p,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>n.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:u,isActive:p,config:t??{}})});if(!i)return r.append(m,X),r;let V=R("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(V.style.display=d?"":"none",n.contentBackgroundColor&&(V.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(V.style.color=n.contentTextColor),n.contentPaddingX&&(V.style.paddingLeft=n.contentPaddingX,V.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(V.style.paddingTop=n.contentPaddingY,V.style.paddingBottom=n.contentPaddingY),o.name){let T=R("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?T.style.color=n.contentTextColor:n.headerTextColor&&(T.style.color=n.headerTextColor),T.textContent=o.name,V.appendChild(T)}if(o.args!==void 0){let T=R("div","persona-space-y-1"),O=R("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Arguments";let D=R("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",Gg(D,n),D.textContent=bc(o.args),T.append(O,D),V.appendChild(T)}if(o.chunks&&o.chunks.length){let T=R("div","persona-space-y-1"),O=R("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Activity";let D=R("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",Gg(D,n),D.textContent=o.chunks.join(""),T.append(O,D),V.appendChild(T)}if(o.success===!1&&V.appendChild(Q("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let T=R("div","persona-space-y-1"),O=R("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Result";let D=R("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",Gg(D,n),D.textContent=bc(o.result),T.append(O,D),V.appendChild(T)}if(o.status==="complete"&&typeof o.duration=="number"){let T=R("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(T.style.color=n.contentTextColor),T.textContent=`Duration: ${o.duration}ms`,V.appendChild(T)}return Pu({expanded:d,header:m,toggleIcon:N,content:V,collapsedPreview:X,iconColor:L}),r.append(m,X,V),r};var{setLoader:lk,load:dk,provide:TD,getSync:ck}=mt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),XS=lk,QS=dk;var YS=ck;var{setLoader:uk,load:pk}=mt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),JS=uk,Qg=pk;var Yg=class{constructor(){this.components=new Map;this.options=new Map}register(t,o,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,o),n?this.options.set(t,n):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([o,n])=>{this.register(o,n)})}},Sn=new Yg;var Jg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:fk,load:mk,provide:BD,getSync:gk}=mt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),oi=null,Lu=new Set,ZS=e=>{if(oi)return oi;oi=e,e.initArtifactsUi({componentRegistry:Sn});for(let n of Jg)Sn.has(n)||Sn.register(n,n==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=On();t?e.__provideMarkdownParsers(t):Pa(()=>{let n=On();n&&e.__provideMarkdownParsers(n)}),e.__setIconsExtraLoader(()=>Dc());let o=[...Lu];Lu.clear();for(let n of o)try{n()}catch{}return e},ew=fk,Iu=()=>mk().then(ZS);var hr=()=>{if(oi)return oi;let e=gk();return e?ZS(e):null},Zg=e=>oi?()=>{}:(Lu.add(e),()=>{Lu.delete(e)});function So(e){return e?.features?.artifacts?.enabled===!0}function tw(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!So(t))return;let o=t.features?.artifacts?.layout,n=o?.paneBorder?.trim(),r=o?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function hk(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var ow=["panel","seamless","detached"];function eh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&ow.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function th(e){return!e||!So(e)?!1:eh(e)==="detached"}function Ol(e,t){if(!So(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),hk(e),tw(e,t);return}let o=t.features?.artifacts?.layout,n=eh(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",o?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",o?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",o?.paneMaxWidth??"28rem"),o?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",o.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),o?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",o.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=o?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=o?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[o?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[o?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[o?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[o?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[d,c]of i){let u=d?.trim();u?e.style.setProperty(c,u):e.style.removeProperty(c)}tw(e,t)}function Dl(e,t){for(let d of ow)e.classList.remove(`persona-artifact-appearance-${d}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!So(t))return;let o=t.features?.artifacts?.layout,n=eh(t);e.classList.add(`persona-artifact-appearance-${n}`);let r=o?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=o?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let i=o?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function nw(e,t){return!t||!So(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var yk=new Set(["__proto__","prototype","constructor"]),bk=new Set(["collapsed","card","panel","inline"]),rw=new Set(["markdown","component"]),vk=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,js=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hu=e=>!yk.has(e),oh=e=>typeof e=="string"&&bk.has(e),zs=e=>Object.keys(e).length>0;function qn(e,t,o,n){e.push({path:t,code:o,message:n})}var xk="Ignored because this key is not part of the persisted preference schema.",Ru="Ignored an unsupported value.",Ck="Expected collapsed, panel, or inline.",Sk='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',sw={kind:"mode",message:Ru},ni={kind:"string",message:"Expected a CSS length string."},yr={kind:"boolean"},wk={paneWidth:ni,paneMaxWidth:ni,paneMinWidth:ni,expandedPanelWidth:ni,resizableMinWidth:ni,resizableMaxWidth:ni,expandLauncherPanelWhenOpen:yr,resizable:yr},Ak={kind:"object",message:"Expected a preference object.",children:{showToolCalls:yr,showReasoning:yr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ru},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ru},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ru},expandable:yr,grouped:yr}},reasoningDisplay:{kind:"object",children:{expandable:yr,activePreview:yr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:sw,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:sw,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:rw,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:rw}}},filePreview:{kind:"object",children:{enabled:yr}},layout:{kind:"object",children:wk}}}}};function aw(e,t,o,n){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:qn(n,o,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:qn(n,o,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:qn(n,o,"invalid_value",t.message);case"mode":return oh(e)?Bo(e):qn(n,o,"invalid_value",t.message);case"modeMap":{if(!js(e))return qn(n,o,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[i,d]of Object.entries(e)){let c=r?i:Nr(i);Hu(i)&&(r?r.has(i):vk.test(c))?oh(d)?a[c]=Bo(d):qn(n,`${o}.${i}`,"invalid_value",Ck):qn(n,`${o}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":Sk)}return zs(a)?a:void 0}case"object":{if(t.bareMode&&oh(e))return Bo(e);if(!js(e))return qn(n,o,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=d=>o?`${o}.${d}`:d;for(let d of Object.keys(e))(!Hu(d)||!r.includes(d))&&qn(n,a(d),"unknown_key",xk);let i={};for(let d of r){let c=t.children[d],u=aw(e[d],c,a(d),n);if(c.deprecated&&e[d]!==void 0&&qn(n,a(d),"deprecated_key",c.deprecated),u===void 0)continue;let p=c.alias??d,m=i[p];i[p]=js(m)&&js(u)?{...m,...u}:u}return zs(i)?i:void 0}}}function nh(e){let t=[];return{preferences:(e===null?void 0:aw(e,Ak,"",t))??{},issues:t}}function ri(e){if(Array.isArray(e))return e.map(ri);if(!js(e))return e;let t={};for(let[o,n]of Object.entries(e))Hu(o)&&n!==void 0&&(t[o]=ri(n));return t}function iw(e,t){let o=ri(e);for(let[n,r]of Object.entries(t)){if(!Hu(n)||r===void 0)continue;let a=o[n];o[n]=js(a)&&js(r)?iw(a,r):ri(r)}return o}function Mk(e){let t={},o;for(let r of e){let a=nh(r).preferences;o=lw(o,a.artifacts?.display),t=iw(t,a)}let n=t;return n.artifacts&&(o!==void 0?n.artifacts.display=o:delete n.artifacts.display),n}function Tk(e,t){if(t===void 0)return e===void 0?void 0:ri(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...zs(r)?{byMediaType:r}:{}};return zs(a)?a:void 0}function lw(e,t){if(t===void 0)return e===void 0?void 0:ri(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byType,...o.byKind,...t.byType,...t.byKind},a=Tk(o.files,t.files),i={...n?{default:n}:{},...zs(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return zs(i)?i:void 0}function rh(e={},t){let o=Mk(t),n={...e};if(o.showToolCalls!==void 0&&(n.showToolCalls=o.showToolCalls),o.showReasoning!==void 0&&(n.showReasoning=o.showReasoning),o.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...o.toolCallDisplay}),o.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...o.reasoningDisplay}),o.artifacts){let r=e.artifacts??{},a={...r};if(o.artifacts.display!==void 0){let i=lw(r.display,o.artifacts.display);i!==void 0&&(a.display=i)}o.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:o.artifacts.filePreview.enabled}),o.artifacts.layout&&(a.layout={...r.layout,...o.artifacts.layout}),n.artifacts=a}return n}function _l(e){let t=e.preferences;return!t||!zs(t)?e:{...e,features:rh(e.features??{},[t])}}function Ek(e,t){if(!e?.trim())return t;let o=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return o?Math.max(0,Number(o[1])):t}function Pk(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function kk(e,t,o){return o<t?t:Math.min(o,Math.max(t,e))}function Lk(e,t,o,n){let r=e-n-2*t-o;return Math.max(0,r)}function sh(e,t){let n=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function dw(e,t,o,n,r,a,i=200){let d=Ek(r,200),c=Lk(t,o,n,i);c=Math.max(d,c);let u=Pk(a);return u!==null&&(c=Math.min(c,u)),kk(e,d,c)}var{setLoader:Ik,load:Rk,provide:qD,getSync:Hk}=mt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),cw=Ik,uw=Rk;var pw=Hk;var ah=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let o=this.plugins.get(t);o&&(o.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,o)=>(o.priority??0)-(t.priority??0))}getForInstance(t){let o=this.getAll();if(!t||t.length===0)return o;let n=new Set(t.map(a=>a.id));return[...o.filter(a=>!n.has(a.id)),...t].sort((a,i)=>(i.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Nl=new ah;var fw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wk=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),mw=(e,t,o)=>{if(!fw(e)||!fw(t)||Wk.has(o))return t;let n={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete n[r];continue}let a=o?`${o}.${r}`:r;n[r]=mw(e[r],t[r],a)}return n};function Wu(e,t){let o=mw(e,t,"");return $a(o)}var gw=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>o(r,a)),o=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:o,emit:(r,a)=>{e.get(r)?.forEach(i=>{try{i(a)}catch(d){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Bk=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Ok=e=>{let t=e.trim(),o=t.indexOf("{");if(o===-1)return null;let n=0;for(let r=o;r<t.length;r+=1){let a=t[r];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return t.slice(o,r+1)}return null},Fl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Bk(e),o=Ok(t);if(!o)return null;let n=JSON.parse(o);if(!n||typeof n!="object"||!n.action)return null;let{action:r,...a}=n;return{type:String(r),payload:a,raw:n}}catch{return null}},ih=e=>typeof e=="string"?e:e==null?"":String(e),Ks={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ih(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let o=e.payload,n=ih(o.element);if(n&&t.document?.querySelector){let r=t.document.querySelector(n);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:ih(o.text)}}},hw=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ul=e=>{let t=new Set(hw(e.getSessionMetadata().processedActionMessageIds)),o=()=>{t=new Set(hw(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let i=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!i&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let d=i?e.parsers.reduce((u,p)=>u||p?.({text:i,message:a.message})||null,null):null;if(!d)return null;t.add(a.message.id),n();let c={action:d,message:a.message};e.emit("action:detected",c);for(let u of e.handlers)if(u)try{let p=()=>{e.emit("action:resubmit",c)},m=u(d,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let h=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:h,resubmit:m.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:o}};var Dk=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},_k=e=>e.map(t=>({...t,streaming:!1})),Nk=e=>e.map(t=>({...t,status:"complete"})),Bu=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?Dk(o.getItem(e)):null},save:o=>{let n=t();if(n)try{let r={...o,messages:o.messages?_k(o.messages):void 0,artifacts:o.artifacts?Nk(o.artifacts):void 0};n.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=t();if(o)try{o.removeItem(e)}catch(n){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var Fk=e=>{let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},yw=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let o=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(o)).map(n=>n.toString(16).padStart(2,"0")).join("")}catch{}return Fk(e)},Uk=async(e,t)=>{let o=await yw(e);return{storageKey:`${t}visitor:${o}`,leaseKey:`${t}visitor-init-lock:${o}`,lockName:`persona-visitor-init:${await yw(`${e}\0${t}`)}`}};var bw=(e,t,o)=>{let n="",r="",a="",i=!1,d=!1,c=0,u=null,p=null,m=new Set,h=()=>{if(o||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},y=()=>{let C=h();if(!C)return u;try{return C.getItem(n)}catch{return i=!0,u}},x=(C,L)=>{if(d||C===u)return;let N=u;u=C,c+=1;let X={previousToken:N,token:C,source:L,revision:c};for(let V of m)V(X)},M=C=>{d||C.key!==null&&C.key!==n||x(C.key===null?null:C.newValue??null,"external")},S=(async()=>{let C=await Uk(e,t);n=C.storageKey,r=C.leaseKey,a=C.lockName,u=y(),!o&&typeof window<"u"&&window.addEventListener("storage",M)})(),k=C=>new Promise(L=>setTimeout(L,C)),P=()=>{let C=h();if(!C)return null;try{let L=C.getItem(r);if(!L)return null;let N=JSON.parse(L);return typeof N?.expiresAt=="number"&&typeof N?.ownerNonce=="string"?N:null}catch{return null}},H=C=>{let L=h();if(L)try{P()?.ownerNonce===C&&L.removeItem(r)}catch{}},b=C=>new Promise(L=>{let N=setTimeout(X,C);function X(){clearTimeout(N),window.removeEventListener("storage",V),L()}function V(T){(T.key===null||T.key===r)&&X()}window.addEventListener("storage",V)}),w=async C=>{let L=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,N=Date.now()+15e3;for(;Date.now()<N;){let X=h();if(!X)break;let V=Date.now(),T=P();if(T&&T.expiresAt>V&&T.ownerNonce!==L){await b(Math.min(T.expiresAt-V,500));continue}try{X.setItem(r,JSON.stringify({ownerNonce:L,expiresAt:V+1e4}))}catch{i=!0;break}if(await k(20+Math.random()*40),P()?.ownerNonce!==L){await b(500);continue}p=L;try{return await C()}finally{p=null,H(L)}}return C()};return{ready:S,async get(){return await S,x(y(),"external"),u},async set(C){await S;let L=h();if(L)try{L.setItem(n,C)}catch{i=!0}x(C,"local")},async clear(){await S;let C=h();if(C)try{C.removeItem(n)}catch{i=!0}x(null,"local")},revision(){return c},subscribe(C){return m.add(C),()=>{m.delete(C)}},async withFirstInitLock(C){await S;let L=globalThis.navigator?.locks;return L?.request?L.request(a,()=>C()):h()?w(C):C()},matches(C,L,N){return C===e&&L===t&&N===o},destroy(){d=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",M),p&&H(p)}}};var{setLoader:qk,load:Vk}=mt({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),vw=qk,lh=Vk;var dh=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},br=e=>Object.freeze({...e}),xw=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),Cw=e=>e?br(e):null;function Sw(e){let{plugins:t,config:o}=e,n=!1,r=!1,a=!1,i=!1,d=null,c=[],u=()=>{for(let b of c.splice(0))try{b()}catch(w){dh("renderHistoryView cleanup",w)}},p=(b,w)=>{for(let C of t){let L=C[b];if(L)try{let N=L(w);if(N)return N}catch(N){dh(b,N)}}return null},m=()=>({presentation:e.getPresentation(),config:o}),h={header:b=>i?p("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:br(b.identityStatus),pendingAction:Cw(b.pendingAction),copy:br(b.copy),actions:Object.freeze({close:M.close,startNewConversation:M.startNewConversation}),defaultRenderer:b.defaultRenderer})):null,conversation:b=>i?p("renderHistoryConversation",Object.freeze({...m(),conversation:xw(b.conversation),active:b.active,pending:b.pending,open:b.open,requestDelete:b.requestDelete,defaultRenderer:b.defaultRenderer})):null,state:b=>i?p("renderHistoryState",Object.freeze({...m(),state:br(b.state),identityStatus:br(b.identityStatus),copy:br(b.copy),...b.retry?{retry:b.retry}:{},...b.startNewConversation?{startNewConversation:b.startNewConversation}:{},defaultRenderer:b.defaultRenderer})):null},y=t.flatMap(b=>(b.railSections??[]).map(w=>({...w,placement:w.placement??"above-conversations",items:[],render:C=>w.render(Object.freeze({collapsed:C,presentation:e.getPresentation(),actions:M}))}))),x=e.createView({slots:h,renderDom:!1,onModelChange:()=>H(),railSections:y}),M=Object.freeze({...x.operations,close:e.close}),S=()=>(i=!0,x.setDomRenderEnabled(!0),x.element),k=b=>Object.freeze({conversations:Object.freeze(b.conversations.map(xw)),activeConversationId:b.activeConversationId,state:br(b.state),pendingAction:Cw(b.pendingAction),identityStatus:br(b.identityStatus),nextCursor:b.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:o,copy:br(x.copy),actions:M,defaultRenderer:S,requestRender:()=>H(),onCleanup:w=>{c.push(w)}}),P=()=>{i=!1;let b=null;for(let C of t)if(C.renderHistoryView){try{b=C.renderHistoryView(k(x.getModel()))}catch(L){dh("renderHistoryView",L),b=null}if(b)break}let w=!b||b.contains(x.element);return i=w,x.setDomRenderEnabled(w),b??x.element};function H(){if(!(!a||n||r)){r=!0;try{u();let b=P();if(b===d)return;let w=d;d=b,e.onElementChanged(b,w)}finally{r=!1}}}return a=!0,H(),{view:x,get element(){return d??x.element},requestRender:H,dispose:()=>{n=!0,u()}}}var $k=null;function ww(){return $k}var jk=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),zk=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),ch=e=>zk.get(e)??"Conversation history is unavailable right now.";function Kk(e){if(e instanceof ln)return e;if(e instanceof _e){let t=jk.get(e.code)??"unavailable";return new ln(t,ch(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new ln("unavailable",ch("unavailable"))}function Aw(e){let t=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],n={scopes:o},r=d=>{if(!o.includes(d))throw new ln("unsupported_scope",ch("unsupported_scope"))},a=async(d,c)=>{r(d);try{return await c()}catch(u){throw Kk(u)}},i=d=>{let c=!1;return{conversationId:d.session.conversationId??"",conversationRevision:d.session.conversationRevision??"",async commit(){c||(c=!0,d.commit(),await e.onActivationCommitted(d.session))},discard(){c||(c=!0,d.discard())}}};return{capabilities:n,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(d){return t().subscribeHistoryIdentityStatus(d)},subscribeAvailability(d){return t().subscribeHistoryAvailability(d)},async list(d){return a(d.context.scope,async()=>{let c=await t().listConversations({...d.cursor?{cursor:d.cursor}:{},...d.limit!==void 0?{limit:d.limit}:{},...d.targetId?{targetId:d.targetId}:{},scope:d.context.scope});return{items:c.data,nextCursor:c.nextCursor}})},async getPage(d,c){return a(c.context.scope,async()=>{let u=await t().getConversation(d,{...c.cursor?{messageCursor:c.cursor}:{},scope:c.context.scope}),p=hx(u.messages,{...c.beforeCreatedAt?{beforeCreatedAt:c.beforeCreatedAt}:{}});return{summary:u.summary,messages:il([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(d,c){return a(c.context.scope,async()=>i(await t().prepareConversationSession(d)))},async prepareStartNew(d){return a(d.context.scope,async()=>i(await t().prepareNewConversationSession()))},async delete(d,c){await a(c.context.scope,()=>t().deleteConversation(d,{scope:c.context.scope}))},async deleteAll(d){return a(d.context.scope,()=>t().deleteAllConversations({...d.targetId!==void 0?{targetId:d.targetId}:{},scope:d.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var Gk=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],Mw={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function uh(e){if(!e)return Mw;let t={...Mw};for(let o of Gk){let n=e[o];typeof n=="string"&&n.length>0&&(t[o]=n)}return t}var Xk="button:not([disabled])";function Ou(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,o=Math.random().toString(36).slice(2,8),n=`persona-history-confirm-title-${o}`,r=`persona-history-confirm-desc-${o}`,a=Q("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=Q("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),d=Q("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},Q("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:n},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Q("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Q("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},a,i));for(let u of[a,i])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.style.font="inherit";a.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",a.style.background="transparent",a.style.color="inherit",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let c=Q("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},d);return new Promise(u=>{let p=!1,m=y=>{p||(p=!0,c.removeEventListener("keydown",h,!0),c.remove(),t?.focus(),u(y))};function h(y){if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),m(!1);return}if(y.key!=="Tab")return;let x=Array.from(d.querySelectorAll(Xk));if(x.length===0)return;let M=x[0],S=x[x.length-1],k=document.activeElement;y.shiftKey&&(k===M||!d.contains(k))?(y.preventDefault(),S.focus()):!y.shiftKey&&k===S&&(y.preventDefault(),M.focus())}c.addEventListener("keydown",h,!0),c.addEventListener("pointerdown",y=>{y.target===c&&m(!1)}),a.addEventListener("click",()=>m(!1)),i.addEventListener("click",()=>m(!0)),e.host.appendChild(c),a.focus()})}var si=Yt(uc(),1);function Qk(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Yk(e,t){if(!Qk(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:t}}function Du(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e;try{let r=(0,si.parse)(o,si.STR|si.OBJ),a=Yk(r,o);a&&(e=a)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function Tw(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _u(e,t){let{config:o,message:n,onPropsUpdate:r}=t,a=Sn.get(e.component);if(!a){if(Jg.includes(e.component)){Iu().catch(()=>{});let d=R("div","persona-w-full");return d.setAttribute("data-persona-artifact-pending","true"),d}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:n,config:o,updateProps:d=>{r&&r(d)}};try{return a(e.props,i)}catch(d){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,d),null}}function Ew(){let e=Du();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Pw(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function ql(e){let t=Pw(e);if(!t)return!1;try{let o=JSON.parse(t);return typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"}catch{return!1}}function Nu(e){let t=Pw(e);if(!t)return null;try{let o=JSON.parse(t);if(typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"){let n=o;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:t}}}catch{}return null}var Jk=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fu(e){let{onSubmit:t,onDismiss:o,title:n="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,ratingLabels:u=Jk}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,y.appendChild(x);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,y.appendChild(M),h.appendChild(y);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let C=1;C<=5;C++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),L.title=u[C-1],L.dataset.rating=String(C),L.innerHTML=`
|
|
40
|
+
`):""},Xg=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},fk=(e,t)=>{let o=e.toolCall,n=t?.features?.toolCallDisplay,r=n?.collapsedMode??"tool-call",a=o?.success===!1?o.error||"Tool failed":pk(e,n?.previewMaxLines??3),i=o?rx(o):"";if(!o)return{summary:i,previewText:a,isActive:!1};let d=o.status!=="complete",c=t?.toolCall??{},u=i;return r==="tool-name"?u=o.name?.trim()||i:r==="tool-preview"&&a&&(u=a),d&&c.activeTextTemplate?u=Xf(o,c.activeTextTemplate,u):!d&&c.completeTextTemplate&&(u=Xf(o,c.completeTextTemplate,u)),o.success===!1&&(u+=" \xB7 Failed"),{summary:u,previewText:a,isActive:d}},YS=(e,t,o)=>{ku(e,t,{stateSet:ti,previewKind:"tool",iconColor:QS(o?.toolCall??{})})},Qg=(e,t)=>{let o=e.toolCall,n=t?.toolCall??{},r=Au("persona-tool-bubble",e.id);if(n.backgroundColor&&(r.style.backgroundColor=n.backgroundColor),n.borderColor&&(r.style.borderColor=n.borderColor),n.borderWidth&&(r.style.borderWidth=n.borderWidth),n.borderRadius&&(r.style.borderRadius=n.borderRadius),r.style.boxShadow=n.shadow!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!o)return r;let a=t?.features?.toolCallDisplay??{},i=a.expandable!==!1,d=i&&ti.has(e.id),{summary:c,previewText:u,isActive:p}=fk(e,t),m=Mu({expandable:i,expanded:d,bubbleType:"tool"});n.headerBackgroundColor&&(m.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(m.style.paddingLeft=n.headerPaddingX,m.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(m.style.paddingTop=n.headerPaddingY,m.style.paddingBottom=n.headerPaddingY);let h=H("div","persona-flex persona-flex-col persona-text-left"),y=H("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(y.style.color=n.headerTextColor);let C=String(o.startedAt??Date.now()),A=()=>{let P=H("span","");return P.setAttribute("data-tool-elapsed",C),P.textContent=rl(o),P},M=n.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:c,previewText:u,collapsedMode:a.collapsedMode??"tool-call",isActive:p,config:t??{},elapsed:rl(o),createElapsedElement:A});typeof M=="string"&&M.trim()?(y.textContent=M,h.appendChild(y)):M instanceof HTMLElement?h.appendChild(M):(y.textContent=c,h.appendChild(y));let E=a.loadingAnimation??"none",T=n.activeTextTemplate,I=n.completeTextTemplate,b=p?T:I,S=M instanceof HTMLElement,x=(P,O)=>{y.textContent="";let D=o.name?.trim()||"tool",W=Cc(P,D),ee=0;for(let G of W){let ue=G.styles.length>0?(()=>{let ae=H("span",G.styles.map(ye=>`persona-tool-text-${ye}`).join(" "));return y.appendChild(ae),ae})():y;if(G.isDuration&&p)ue.appendChild(A());else{let ae=G.isDuration?rl(o):G.text;O?ee=Za(ue,ae,ee):ue.appendChild(document.createTextNode(ae))}}};if(!S)if(p&&E!=="none"){let P=n.loadingAnimationDuration??2e3;if(y.setAttribute("data-preserve-animation","true"),E==="pulse")y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${P}ms`),b&&x(b,!1);else if(y.classList.add(`persona-tool-loading-${E}`),y.style.setProperty("--persona-tool-anim-duration",`${P}ms`),E==="shimmer-color"&&(n.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),b)x(b,!0);else{let O=y.textContent||c;y.textContent="",Za(y,O,0)}}else b&&x(b,!1);let L=QS(n),N=Tu(m,h,{expandable:i,expanded:d,iconColor:L,metaGap:!0}),X=Eu({bubble:r,previewKind:"tool",expanded:d,isActive:p,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>n.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:u,isActive:p,config:t??{}})});if(!i)return r.append(m,X),r;let V=H("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(V.style.display=d?"":"none",n.contentBackgroundColor&&(V.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(V.style.color=n.contentTextColor),n.contentPaddingX&&(V.style.paddingLeft=n.contentPaddingX,V.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(V.style.paddingTop=n.contentPaddingY,V.style.paddingBottom=n.contentPaddingY),o.name){let P=H("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?P.style.color=n.contentTextColor:n.headerTextColor&&(P.style.color=n.headerTextColor),P.textContent=o.name,V.appendChild(P)}if(o.args!==void 0){let P=H("div","persona-space-y-1"),O=H("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Arguments";let D=H("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",Xg(D,n),D.textContent=bc(o.args),P.append(O,D),V.appendChild(P)}if(o.chunks&&o.chunks.length){let P=H("div","persona-space-y-1"),O=H("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Activity";let D=H("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",Xg(D,n),D.textContent=o.chunks.join(""),P.append(O,D),V.appendChild(P)}if(o.success===!1&&V.appendChild(Q("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let P=H("div","persona-space-y-1"),O=H("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Result";let D=H("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",Xg(D,n),D.textContent=bc(o.result),P.append(O,D),V.appendChild(P)}if(o.status==="complete"&&typeof o.duration=="number"){let P=H("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(P.style.color=n.contentTextColor),P.textContent=`Duration: ${o.duration}ms`,V.appendChild(P)}return Pu({expanded:d,header:m,toggleIcon:N,content:V,collapsedPreview:X,iconColor:L}),r.append(m,X,V),r};var{setLoader:mk,load:gk,provide:WD,getSync:hk}=mt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),JS=mk,ZS=gk;var ew=hk;var{setLoader:yk,load:bk}=mt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),tw=yk,Yg=bk;var Jg=class{constructor(){this.components=new Map;this.options=new Map}register(t,o,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,o),n?this.options.set(t,n):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([o,n])=>{this.register(o,n)})}},Sn=new Jg;var Zg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:vk,load:xk,provide:VD,getSync:Ck}=mt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),oi=null,Lu=new Set,ow=e=>{if(oi)return oi;oi=e,e.initArtifactsUi({componentRegistry:Sn});for(let n of Zg)Sn.has(n)||Sn.register(n,n==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=On();t?e.__provideMarkdownParsers(t):Pa(()=>{let n=On();n&&e.__provideMarkdownParsers(n)}),e.__setIconsExtraLoader(()=>Dc());let o=[...Lu];Lu.clear();for(let n of o)try{n()}catch{}return e},nw=vk,Iu=()=>xk().then(ow);var hr=()=>{if(oi)return oi;let e=Ck();return e?ow(e):null},eh=e=>oi?()=>{}:(Lu.add(e),()=>{Lu.delete(e)});function So(e){return e?.features?.artifacts?.enabled===!0}function rw(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!So(t))return;let o=t.features?.artifacts?.layout,n=o?.paneBorder?.trim(),r=o?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Sk(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var sw=["panel","seamless","detached"];function th(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&sw.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function oh(e){return!e||!So(e)?!1:th(e)==="detached"}function Ol(e,t){if(!So(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Sk(e),rw(e,t);return}let o=t.features?.artifacts?.layout,n=th(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",o?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",o?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",o?.paneMaxWidth??"28rem"),o?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",o.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),o?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",o.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=o?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=o?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[o?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[o?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[o?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[o?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[d,c]of i){let u=d?.trim();u?e.style.setProperty(c,u):e.style.removeProperty(c)}rw(e,t)}function Dl(e,t){for(let d of sw)e.classList.remove(`persona-artifact-appearance-${d}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!So(t))return;let o=t.features?.artifacts?.layout,n=th(t);e.classList.add(`persona-artifact-appearance-${n}`);let r=o?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=o?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let i=o?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function aw(e,t){return!t||!So(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var wk=new Set(["__proto__","prototype","constructor"]),Ak=new Set(["collapsed","card","panel","inline"]),iw=new Set(["markdown","component"]),Mk=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,js=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hu=e=>!wk.has(e),nh=e=>typeof e=="string"&&Ak.has(e),zs=e=>Object.keys(e).length>0;function qn(e,t,o,n){e.push({path:t,code:o,message:n})}var Tk="Ignored because this key is not part of the persisted preference schema.",Ru="Ignored an unsupported value.",Ek="Expected collapsed, panel, or inline.",Pk='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',lw={kind:"mode",message:Ru},ni={kind:"string",message:"Expected a CSS length string."},yr={kind:"boolean"},kk={paneWidth:ni,paneMaxWidth:ni,paneMinWidth:ni,expandedPanelWidth:ni,resizableMinWidth:ni,resizableMaxWidth:ni,expandLauncherPanelWhenOpen:yr,resizable:yr},Lk={kind:"object",message:"Expected a preference object.",children:{showToolCalls:yr,showReasoning:yr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ru},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ru},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ru},expandable:yr,grouped:yr}},reasoningDisplay:{kind:"object",children:{expandable:yr,activePreview:yr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:lw,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:lw,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:iw,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:iw}}},filePreview:{kind:"object",children:{enabled:yr}},layout:{kind:"object",children:kk}}}}};function dw(e,t,o,n){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:qn(n,o,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:qn(n,o,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:qn(n,o,"invalid_value",t.message);case"mode":return nh(e)?Bo(e):qn(n,o,"invalid_value",t.message);case"modeMap":{if(!js(e))return qn(n,o,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[i,d]of Object.entries(e)){let c=r?i:Nr(i);Hu(i)&&(r?r.has(i):Mk.test(c))?nh(d)?a[c]=Bo(d):qn(n,`${o}.${i}`,"invalid_value",Ek):qn(n,`${o}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":Pk)}return zs(a)?a:void 0}case"object":{if(t.bareMode&&nh(e))return Bo(e);if(!js(e))return qn(n,o,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=d=>o?`${o}.${d}`:d;for(let d of Object.keys(e))(!Hu(d)||!r.includes(d))&&qn(n,a(d),"unknown_key",Tk);let i={};for(let d of r){let c=t.children[d],u=dw(e[d],c,a(d),n);if(c.deprecated&&e[d]!==void 0&&qn(n,a(d),"deprecated_key",c.deprecated),u===void 0)continue;let p=c.alias??d,m=i[p];i[p]=js(m)&&js(u)?{...m,...u}:u}return zs(i)?i:void 0}}}function rh(e){let t=[];return{preferences:(e===null?void 0:dw(e,Lk,"",t))??{},issues:t}}function ri(e){if(Array.isArray(e))return e.map(ri);if(!js(e))return e;let t={};for(let[o,n]of Object.entries(e))Hu(o)&&n!==void 0&&(t[o]=ri(n));return t}function cw(e,t){let o=ri(e);for(let[n,r]of Object.entries(t)){if(!Hu(n)||r===void 0)continue;let a=o[n];o[n]=js(a)&&js(r)?cw(a,r):ri(r)}return o}function Ik(e){let t={},o;for(let r of e){let a=rh(r).preferences;o=uw(o,a.artifacts?.display),t=cw(t,a)}let n=t;return n.artifacts&&(o!==void 0?n.artifacts.display=o:delete n.artifacts.display),n}function Rk(e,t){if(t===void 0)return e===void 0?void 0:ri(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...zs(r)?{byMediaType:r}:{}};return zs(a)?a:void 0}function uw(e,t){if(t===void 0)return e===void 0?void 0:ri(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byType,...o.byKind,...t.byType,...t.byKind},a=Rk(o.files,t.files),i={...n?{default:n}:{},...zs(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return zs(i)?i:void 0}function sh(e={},t){let o=Ik(t),n={...e};if(o.showToolCalls!==void 0&&(n.showToolCalls=o.showToolCalls),o.showReasoning!==void 0&&(n.showReasoning=o.showReasoning),o.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...o.toolCallDisplay}),o.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...o.reasoningDisplay}),o.artifacts){let r=e.artifacts??{},a={...r};if(o.artifacts.display!==void 0){let i=uw(r.display,o.artifacts.display);i!==void 0&&(a.display=i)}o.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:o.artifacts.filePreview.enabled}),o.artifacts.layout&&(a.layout={...r.layout,...o.artifacts.layout}),n.artifacts=a}return n}function _l(e){let t=e.preferences;return!t||!zs(t)?e:{...e,features:sh(e.features??{},[t])}}function Hk(e,t){if(!e?.trim())return t;let o=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return o?Math.max(0,Number(o[1])):t}function Wk(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Bk(e,t,o){return o<t?t:Math.min(o,Math.max(t,e))}function Ok(e,t,o,n){let r=e-n-2*t-o;return Math.max(0,r)}function ah(e,t){let n=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function pw(e,t,o,n,r,a,i=200){let d=Hk(r,200),c=Ok(t,o,n,i);c=Math.max(d,c);let u=Wk(a);return u!==null&&(c=Math.min(c,u)),Bk(e,d,c)}var{setLoader:Dk,load:_k,provide:QD,getSync:Nk}=mt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),fw=Dk,mw=_k;var gw=Nk;var ih=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let o=this.plugins.get(t);o&&(o.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,o)=>(o.priority??0)-(t.priority??0))}getForInstance(t){let o=this.getAll();if(!t||t.length===0)return o;let n=new Set(t.map(a=>a.id));return[...o.filter(a=>!n.has(a.id)),...t].sort((a,i)=>(i.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Nl=new ih;var hw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fk=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),yw=(e,t,o)=>{if(!hw(e)||!hw(t)||Fk.has(o))return t;let n={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete n[r];continue}let a=o?`${o}.${r}`:r;n[r]=yw(e[r],t[r],a)}return n};function Wu(e,t){let o=yw(e,t,"");return $a(o)}var bw=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>o(r,a)),o=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:o,emit:(r,a)=>{e.get(r)?.forEach(i=>{try{i(a)}catch(d){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Uk=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},qk=e=>{let t=e.trim(),o=t.indexOf("{");if(o===-1)return null;let n=0;for(let r=o;r<t.length;r+=1){let a=t[r];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return t.slice(o,r+1)}return null},Fl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Uk(e),o=qk(t);if(!o)return null;let n=JSON.parse(o);if(!n||typeof n!="object"||!n.action)return null;let{action:r,...a}=n;return{type:String(r),payload:a,raw:n}}catch{return null}},lh=e=>typeof e=="string"?e:e==null?"":String(e),Ks={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:lh(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let o=e.payload,n=lh(o.element);if(n&&t.document?.querySelector){let r=t.document.querySelector(n);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:lh(o.text)}}},vw=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ul=e=>{let t=new Set(vw(e.getSessionMetadata().processedActionMessageIds)),o=()=>{t=new Set(vw(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let i=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!i&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let d=i?e.parsers.reduce((u,p)=>u||p?.({text:i,message:a.message})||null,null):null;if(!d)return null;t.add(a.message.id),n();let c={action:d,message:a.message};e.emit("action:detected",c);for(let u of e.handlers)if(u)try{let p=()=>{e.emit("action:resubmit",c)},m=u(d,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let h=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:h,resubmit:m.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:o}};var Vk=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},$k=e=>e.map(t=>({...t,streaming:!1})),jk=e=>e.map(t=>({...t,status:"complete"})),Bu=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?Vk(o.getItem(e)):null},save:o=>{let n=t();if(n)try{let r={...o,messages:o.messages?$k(o.messages):void 0,artifacts:o.artifacts?jk(o.artifacts):void 0};n.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=t();if(o)try{o.removeItem(e)}catch(n){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var zk=e=>{let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},xw=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let o=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(o)).map(n=>n.toString(16).padStart(2,"0")).join("")}catch{}return zk(e)},Kk=async(e,t)=>{let o=await xw(e);return{storageKey:`${t}visitor:${o}`,leaseKey:`${t}visitor-init-lock:${o}`,lockName:`persona-visitor-init:${await xw(`${e}\0${t}`)}`}};var Cw=(e,t,o)=>{let n="",r="",a="",i=!1,d=!1,c=0,u=null,p=null,m=new Set,h=()=>{if(o||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},y=()=>{let x=h();if(!x)return u;try{return x.getItem(n)}catch{return i=!0,u}},C=(x,L)=>{if(d||x===u)return;let N=u;u=x,c+=1;let X={previousToken:N,token:x,source:L,revision:c};for(let V of m)V(X)},A=x=>{d||x.key!==null&&x.key!==n||C(x.key===null?null:x.newValue??null,"external")},M=(async()=>{let x=await Kk(e,t);n=x.storageKey,r=x.leaseKey,a=x.lockName,u=y(),!o&&typeof window<"u"&&window.addEventListener("storage",A)})(),E=x=>new Promise(L=>setTimeout(L,x)),T=()=>{let x=h();if(!x)return null;try{let L=x.getItem(r);if(!L)return null;let N=JSON.parse(L);return typeof N?.expiresAt=="number"&&typeof N?.ownerNonce=="string"?N:null}catch{return null}},I=x=>{let L=h();if(L)try{T()?.ownerNonce===x&&L.removeItem(r)}catch{}},b=x=>new Promise(L=>{let N=setTimeout(X,x);function X(){clearTimeout(N),window.removeEventListener("storage",V),L()}function V(P){(P.key===null||P.key===r)&&X()}window.addEventListener("storage",V)}),S=async x=>{let L=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,N=Date.now()+15e3;for(;Date.now()<N;){let X=h();if(!X)break;let V=Date.now(),P=T();if(P&&P.expiresAt>V&&P.ownerNonce!==L){await b(Math.min(P.expiresAt-V,500));continue}try{X.setItem(r,JSON.stringify({ownerNonce:L,expiresAt:V+1e4}))}catch{i=!0;break}if(await E(20+Math.random()*40),T()?.ownerNonce!==L){await b(500);continue}p=L;try{return await x()}finally{p=null,I(L)}}return x()};return{ready:M,async get(){return await M,C(y(),"external"),u},async set(x){await M;let L=h();if(L)try{L.setItem(n,x)}catch{i=!0}C(x,"local")},async clear(){await M;let x=h();if(x)try{x.removeItem(n)}catch{i=!0}C(null,"local")},revision(){return c},subscribe(x){return m.add(x),()=>{m.delete(x)}},async withFirstInitLock(x){await M;let L=globalThis.navigator?.locks;return L?.request?L.request(a,()=>x()):h()?S(x):x()},matches(x,L,N){return x===e&&L===t&&N===o},destroy(){d=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",A),p&&I(p)}}};var{setLoader:Gk,load:Xk}=mt({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),Sw=Gk,dh=Xk;var ch=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},br=e=>Object.freeze({...e}),ww=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),Aw=e=>e?br(e):null;function Mw(e){let{plugins:t,config:o}=e,n=!1,r=!1,a=!1,i=!1,d=null,c=[],u=()=>{for(let b of c.splice(0))try{b()}catch(S){ch("renderHistoryView cleanup",S)}},p=(b,S)=>{for(let x of t){let L=x[b];if(L)try{let N=L(S);if(N)return N}catch(N){ch(b,N)}}return null},m=()=>({presentation:e.getPresentation(),config:o}),h={header:b=>i?p("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:br(b.identityStatus),pendingAction:Aw(b.pendingAction),copy:br(b.copy),actions:Object.freeze({close:A.close,startNewConversation:A.startNewConversation}),defaultRenderer:b.defaultRenderer})):null,conversation:b=>i?p("renderHistoryConversation",Object.freeze({...m(),conversation:ww(b.conversation),active:b.active,pending:b.pending,open:b.open,requestDelete:b.requestDelete,defaultRenderer:b.defaultRenderer})):null,state:b=>i?p("renderHistoryState",Object.freeze({...m(),state:br(b.state),identityStatus:br(b.identityStatus),copy:br(b.copy),...b.retry?{retry:b.retry}:{},...b.startNewConversation?{startNewConversation:b.startNewConversation}:{},defaultRenderer:b.defaultRenderer})):null},y=t.flatMap(b=>(b.railSections??[]).map(S=>({...S,placement:S.placement??"above-conversations",items:[],render:x=>S.render(Object.freeze({collapsed:x,presentation:e.getPresentation(),actions:A}))}))),C=e.createView({slots:h,renderDom:!1,onModelChange:()=>I(),railSections:y}),A=Object.freeze({...C.operations,close:e.close}),M=()=>(i=!0,C.setDomRenderEnabled(!0),C.element),E=b=>Object.freeze({conversations:Object.freeze(b.conversations.map(ww)),activeConversationId:b.activeConversationId,state:br(b.state),pendingAction:Aw(b.pendingAction),identityStatus:br(b.identityStatus),nextCursor:b.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:o,copy:br(C.copy),actions:A,defaultRenderer:M,requestRender:()=>I(),onCleanup:S=>{c.push(S)}}),T=()=>{i=!1;let b=null;for(let x of t)if(x.renderHistoryView){try{b=x.renderHistoryView(E(C.getModel()))}catch(L){ch("renderHistoryView",L),b=null}if(b)break}let S=!b||b.contains(C.element);return i=S,C.setDomRenderEnabled(S),b??C.element};function I(){if(!(!a||n||r)){r=!0;try{u();let b=T();if(b===d)return;let S=d;d=b,e.onElementChanged(b,S)}finally{r=!1}}}return a=!0,I(),{view:C,get element(){return d??C.element},requestRender:I,dispose:()=>{n=!0,u()}}}var Qk=null;function Tw(){return Qk}var Yk=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),Jk=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),uh=e=>Jk.get(e)??"Conversation history is unavailable right now.";function Zk(e){if(e instanceof ln)return e;if(e instanceof _e){let t=Yk.get(e.code)??"unavailable";return new ln(t,uh(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new ln("unavailable",uh("unavailable"))}function Ew(e){let t=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],n={scopes:o},r=d=>{if(!o.includes(d))throw new ln("unsupported_scope",uh("unsupported_scope"))},a=async(d,c)=>{r(d);try{return await c()}catch(u){throw Zk(u)}},i=d=>{let c=!1;return{conversationId:d.session.conversationId??"",conversationRevision:d.session.conversationRevision??"",async commit(){c||(c=!0,d.commit(),await e.onActivationCommitted(d.session))},discard(){c||(c=!0,d.discard())}}};return{capabilities:n,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(d){return t().subscribeHistoryIdentityStatus(d)},subscribeAvailability(d){return t().subscribeHistoryAvailability(d)},async list(d){return a(d.context.scope,async()=>{let c=await t().listConversations({...d.cursor?{cursor:d.cursor}:{},...d.limit!==void 0?{limit:d.limit}:{},...d.targetId?{targetId:d.targetId}:{},scope:d.context.scope});return{items:c.data,nextCursor:c.nextCursor}})},async getPage(d,c){return a(c.context.scope,async()=>{let u=await t().getConversation(d,{...c.cursor?{messageCursor:c.cursor}:{},scope:c.context.scope}),p=yx(u.messages,{...c.beforeCreatedAt?{beforeCreatedAt:c.beforeCreatedAt}:{}});return{summary:u.summary,messages:il([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(d,c){return a(c.context.scope,async()=>i(await t().prepareConversationSession(d)))},async prepareStartNew(d){return a(d.context.scope,async()=>i(await t().prepareNewConversationSession()))},async delete(d,c){await a(c.context.scope,()=>t().deleteConversation(d,{scope:c.context.scope}))},async deleteAll(d){return a(d.context.scope,()=>t().deleteAllConversations({...d.targetId!==void 0?{targetId:d.targetId}:{},scope:d.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var eL=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],Pw={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function ph(e){if(!e)return Pw;let t={...Pw};for(let o of eL){let n=e[o];typeof n=="string"&&n.length>0&&(t[o]=n)}return t}var tL="button:not([disabled])";function Ou(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,o=Math.random().toString(36).slice(2,8),n=`persona-history-confirm-title-${o}`,r=`persona-history-confirm-desc-${o}`,a=Q("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=Q("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),d=Q("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},Q("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:n},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Q("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Q("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},a,i));for(let u of[a,i])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.style.font="inherit";a.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",a.style.background="transparent",a.style.color="inherit",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let c=Q("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},d);return new Promise(u=>{let p=!1,m=y=>{p||(p=!0,c.removeEventListener("keydown",h,!0),c.remove(),t?.focus(),u(y))};function h(y){if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),m(!1);return}if(y.key!=="Tab")return;let C=Array.from(d.querySelectorAll(tL));if(C.length===0)return;let A=C[0],M=C[C.length-1],E=document.activeElement;y.shiftKey&&(E===A||!d.contains(E))?(y.preventDefault(),M.focus()):!y.shiftKey&&E===M&&(y.preventDefault(),A.focus())}c.addEventListener("keydown",h,!0),c.addEventListener("pointerdown",y=>{y.target===c&&m(!1)}),a.addEventListener("click",()=>m(!1)),i.addEventListener("click",()=>m(!0)),e.host.appendChild(c),a.focus()})}var si=Yt(uc(),1);function oL(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function nL(e,t){if(!oL(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:t}}function Du(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e;try{let r=(0,si.parse)(o,si.STR|si.OBJ),a=nL(r,o);a&&(e=a)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function kw(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _u(e,t){let{config:o,message:n,onPropsUpdate:r}=t,a=Sn.get(e.component);if(!a){if(Zg.includes(e.component)){Iu().catch(()=>{});let d=H("div","persona-w-full");return d.setAttribute("data-persona-artifact-pending","true"),d}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:n,config:o,updateProps:d=>{r&&r(d)}};try{return a(e.props,i)}catch(d){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,d),null}}function Lw(){let e=Du();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Iw(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function ql(e){let t=Iw(e);if(!t)return!1;try{let o=JSON.parse(t);return typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"}catch{return!1}}function Nu(e){let t=Iw(e);if(!t)return null;try{let o=JSON.parse(t);if(typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"){let n=o;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:t}}}catch{}return null}var rL=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fu(e){let{onSubmit:t,onDismiss:o,title:n="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,ratingLabels:u=rL}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=n,y.appendChild(C);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=r,y.appendChild(A),h.appendChild(y);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let x=1;x<=5;x++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${u[x-1]}`),L.title=u[x-1],L.dataset.rating=String(x),L.innerHTML=`
|
|
41
41
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
42
42
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
43
43
|
</svg>
|
|
44
|
-
`,L.addEventListener("click",()=>{m=C,k.forEach((N,X)=>{let V=X<C;N.classList.toggle("selected",V),N.setAttribute("aria-checked",X===C-1?"true":"false")})}),k.push(L),S.appendChild(L)}h.appendChild(S);let P=null;if(c){let C=document.createElement("div");C.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=a,P.rows=3,P.setAttribute("aria-label","Additional comments"),C.appendChild(P),h.appendChild(C)}let H=document.createElement("div");H.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=d,b.addEventListener("click",()=>{o?.(),p.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=i,w.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let C=P?.value.trim()||void 0;await t(m,C),p.remove()}catch(C){w.disabled=!1,w.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),H.appendChild(b),H.appendChild(w),h.appendChild(H),p.appendChild(h),p}function Uu(e){let{onSubmit:t,onDismiss:o,title:n="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,lowLabel:u="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let h=null,y=document.createElement("div");y.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=n,x.appendChild(M);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,x.appendChild(S),y.appendChild(x);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=u;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=p,P.appendChild(H),P.appendChild(b);let w=document.createElement("div");w.className="persona-feedback-numbers";let C=[];for(let T=0;T<=10;T++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${T} out of 10`),O.textContent=String(T),O.dataset.rating=String(T),T<=6?O.classList.add("persona-feedback-detractor"):T<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{h=T,C.forEach((D,W)=>{D.classList.toggle("selected",W===T),D.setAttribute("aria-checked",W===T?"true":"false")})}),C.push(O),w.appendChild(O)}k.appendChild(P),k.appendChild(w),y.appendChild(k);let L=null;if(c){let T=document.createElement("div");T.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=a,L.rows=3,L.setAttribute("aria-label","Additional comments"),T.appendChild(L),y.appendChild(T)}let N=document.createElement("div");N.className="persona-feedback-actions";let X=document.createElement("button");X.type="button",X.className="persona-feedback-btn persona-feedback-btn-skip",X.textContent=d,X.addEventListener("click",()=>{o?.(),m.remove()});let V=document.createElement("button");return V.type="button",V.className="persona-feedback-btn persona-feedback-btn-submit",V.textContent=i,V.addEventListener("click",async()=>{if(h===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}V.disabled=!0,V.textContent="Submitting...";try{let T=L?.value.trim()||void 0;await t(h,T),m.remove()}catch(T){V.disabled=!1,V.textContent=i,console.error("[NPS Feedback] Failed to submit:",T)}}),N.appendChild(X),N.appendChild(V),y.appendChild(N),m.appendChild(y),m}var ai="persona-chat-history",tL=30*1e3,oL=641,ii="data-persona-composer-reason",nL={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function rL(e){if(!e)return[];let t=[],o=Array.from(e.items??[]);for(let n of o){if(n.kind!=="file"||!n.type.startsWith("image/"))continue;let r=n.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=nL[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith("image/")&&t.push(n);return t}function qu(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function sL(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function aL(e){try{let t=e==="local"?localStorage:sessionStorage,o="__persist_test__";return t.setItem(o,"1"),t.removeItem(o),t}catch{return null}}var ph=e=>!e||typeof e!="object"?{}:{...e},kw=e=>e.map(t=>({...t,streaming:!1})),Lw=(e,t,o)=>{let n=e?.markdown?Yi(e.markdown):null,r=ic(e?.sanitize);e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,i=d=>{let c=d.text??"",u=d.message.rawContent??null;if(t){let h=t.process({text:c,raw:u??c,message:d.message,streaming:d.streaming});h!==null&&(c=h.text,h.persist||(d.message.__skipPersist=!0),h.resubmit&&!d.streaming&&o&&o())}let p=On()!==null,m;if(e?.postprocessMessage){let h=e.postprocessMessage({...d,text:c,raw:u??d.text??""});m=r?r(h):h}else if(n){let h=d.streaming?wv(c):c,y=n(h);m=r&&p?r(y):y}else m=dr(c);return m};return d=>{try{return i(d)}catch(c){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),dr(d.text??"")}}};function Iw(e){let t=R("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let o=e?.iconName??"upload",n=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,i=le(o,n,r,a);if(i&&t.appendChild(i),e?.label){let d=R("span","persona-drop-overlay-label");d.textContent=e.label,t.appendChild(d)}return t}var iL=(e,t)=>{let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];o[n]=a?{...a,...r}:r}return o},lL=e=>e.reduce((t,o)=>({blocks:[...t.blocks,...o.blocks],contentParts:[...t.contentParts,...o.contentParts],context:iL(t.context,o.context)}),{blocks:[],contentParts:[],context:{}}),Vu=(e,t,o)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=$a(t),r=()=>{Xx({delayMs:n.tooltip?.delayMs??200,skipDelayMs:n.tooltip?.skipDelayMs??300})};r();let a=n.features;n=_l(n);let i=Nl.getForInstance(n.plugins),d=QC(e),c=[],u=!1,p=jS(()=>n),m=null,h=null,y=null,x=!1,M=null,S=s=>{m=s,s.initApprovalUi({webMcpToolTitle:lc});let l=s.createBuiltInApprovalPlugin();h=l.plugin,y=l.teardown},k=()=>{if(m)return m;let s=YS();return s?(S(s),s):(QS().then(l=>{x||m||(S(l),M?.())}).catch(()=>{}),null)},P=!1,H=!1,b=null,w=(s,l,f,g)=>{if(!s.querySelector("[data-tv-form]"))return;let v=pw();if(v){v.enhanceWithForms(s,l,f,g);return}uw().then(()=>{P||H||!b||(H=!0,b())}).catch(()=>{})};n.components&&Sn.registerAll(n.components);let C=gw(),N=n.persistState===!1?null:n.storageAdapter??Bu(),X=!!n.clientToken&&typeof n.reconnectStream!="function",V={},T=null,O,D=new Promise(s=>{O=s}),W,ee=!1,G=s=>{if(n.onStateLoaded)try{let l=n.onStateLoaded(s);if(l&&typeof l=="object"&&"state"in l){let{state:f,open:g}=l;return g&&(ee=!0),f}return l}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}return s};if(N?.load)try{let s=N.load();if(s&&typeof s.then=="function")T=s.then(l=>G(l??{messages:[],metadata:{}}));else{let f=G(s??{messages:[],metadata:{}});f.metadata&&(V=ph(f.metadata)),f.messages?.length&&(n={...n,initialMessages:f.messages}),f.artifacts?.length&&(n={...n,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),W=f.draft}}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",s)}else if(n.onStateLoaded)try{let s=G({messages:[],metadata:{}});s.messages?.length&&(n={...n,initialMessages:s.messages})}catch(s){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",s)}T||O();let ue=()=>V,ae=s=>{V=s({...V})??{},la()},ye=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Fl],Re=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ks.message,Ks.messageAndClick],be=Ul({parsers:ye,handlers:Re,getSessionMetadata:ue,updateSessionMetadata:ae,emit:C.emit,documentRef:typeof document<"u"?document:null});be.syncFromMetadata();let pe=n.launcher?.enabled??!0,yt=n.launcher?.autoExpand??!1,Pe=n.autoFocusInput??!1,q=yt,Ue=pe,Je=n.layout?.header?.layout,so=!1,Le=()=>Qr(n),qe=()=>pe||Le(),ve=Le()?!1:pe?yt:!0,po=!1,dn=null,Vn=()=>{po=!0,dn&&clearTimeout(dn),dn=setTimeout(()=>{po&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),po=!1)},1e4)},wt=Lw(n,be,Vn),$n=n.features?.showReasoning??!0,z=n.features?.showToolCalls??!0,E=n.features?.showEventStreamToggle??!1,F=n.features?.scrollToBottom??{},K=n.features?.scrollBehavior??{},Y=()=>(typeof n.persistState=="object"?n.persistState?.keyPrefix:void 0)??"persona-",ge=`${Y()}event-stream`,Me=null,Ee=n.features?.eventStream?.maxEvents??2e3,We=null,st=null,Ke=null,Ve=!1,gt=null,zt=!1,It=null,ao=0,wo=(s,l)=>{We?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:s,timestamp:Date.now(),payload:JSON.stringify(l)})},Ku=(s,l)=>{st?.processEvent(s,l),We?wo(s,l):Ke&&(Ke.length>=Ee&&Ke.shift(),Ke.push({type:s,payload:l}))},$l=()=>{We||!E||(Ke??(Ke=[]),Qg().then(s=>{if(Ve||We||!E)return;Me=new s.EventStreamStore(ge),We=new s.EventStreamBuffer(Ee,Me),st=st??new s.ThroughputTracker,Me.open().then(()=>We?.restore()).catch(f=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let l=Ke??[];Ke=null;for(let f of l)st?.processEvent(f.type,f.payload),wo(f.type,f.payload)}).catch(()=>{}))};E&&$l();let At=!1,Wt=null,Gu=()=>{},jn=()=>{},Th=()=>{},Eh=()=>{},Xu=()=>{},Zw=()=>zt||At&&Wt==="panel",Gs={onCopy:s=>{C.emit("message:copy",s),I?.isClientTokenMode()&&I.submitMessageFeedback(s.id,"copy").catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",l)}),n.messageActions?.onCopy?.(s)},onFeedback:s=>{C.emit("message:feedback",s),I?.isClientTokenMode()&&I.submitMessageFeedback(s.messageId,s.type).catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",l)}),n.messageActions?.onFeedback?.(s)}},Xs=n.statusIndicator??{},Ph=s=>s==="idle"?Xs.idleText??qt.idle:s==="connecting"?Xs.connectingText??qt.connecting:s==="connected"?Xs.connectedText??qt.connected:s==="error"?Xs.errorText??qt.error:s==="paused"?Xs.pausedText??qt.paused:s==="resuming"?Xs.resumingText??qt.resuming:qt[s];function jl(s,l,f,g){if(!s.hasAttribute(ii))if(g==="idle"&&f.idleLink){s.textContent="";let v=document.createElement("a");v.href=f.idleLink,v.target="_blank",v.rel="noopener noreferrer",v.textContent=l,v.style.color="inherit",v.style.textDecoration="none",s.appendChild(v)}else s.textContent=l}let _o=$S({config:n,showClose:qe()}),{wrapper:Ge,panel:Ce,pillRoot:Kt}=_o.shell,Oe=_o.panelElements,{container:de,body:oe,messagesWrapper:Te,starterSuggestions:Qu,transcriptSuggestions:li,suggestions:vr,textarea:ie,sendButton:we,composerForm:cn,statusText:at,welcomeHost:Ao,welcomeIconHolder:eA,greetingHost:No,introKicker:tA,introTitle:oA,introSubtitle:nA,closeButton:Ne,iconHolder:Mt,headerTitle:xr,headerSubtitle:Jr,header:Ae,footer:ke,actionsRow:rA}=Oe,Yu=Oe.leftActions,zl=Oe.rightActions,wn=Oe.sendButtonWrapper,kh=Oe.setSendButtonMode,ne=Oe.micButton,Fo=Oe.micButtonWrapper,St=Oe.attachmentButton,Mo=Oe.attachmentButtonWrapper,ht=Oe.attachmentInput,To=Oe.attachmentPreviewsContainer;de.classList.add("persona-relative"),oe.classList.add("persona-relative");let sA=12,di=()=>F.label??"",aA=()=>F.iconName??"arrow-down",iA=()=>F.enabled!==!1,Uo=()=>K.mode??"anchor-top",Cr=()=>Uo()==="follow"||Uo()==="anchor-top"&&vi,ci=()=>K.anchorTopOffset??16,lA=()=>K.restorePosition??"bottom",Lh=()=>K.pauseOnInteraction===!0,Ih=()=>K.showActivityWhilePinned!==!1,Rh=()=>K.announce===!0,Ju=()=>K.scrollbar??"on-scroll",Bt=R("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Bt.type="button",Bt.style.display="none",Bt.setAttribute("data-persona-scroll-to-bottom","true");let ui=R("span","persona-flex persona-items-center"),Zu=R("span",""),Zr=R("span","");Zr.setAttribute("data-persona-scroll-to-bottom-count",""),Zr.style.display="none",Bt.append(ui,Zu,Zr),de.appendChild(Bt);let Qo=R("div","persona-stream-anchor-spacer");Qo.setAttribute("aria-hidden","true"),Qo.setAttribute("data-persona-anchor-spacer",""),Qo.style.flexShrink="0",Qo.style.pointerEvents="none",Qo.style.height="0px",Qo.style.display="none",oe.appendChild(Qo);let zn=R("div","persona-sr-only");zn.setAttribute("aria-live","polite"),zn.setAttribute("aria-atomic","true"),zn.setAttribute("role","status"),zn.setAttribute("data-persona-live-region",""),Object.assign(zn.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),de.appendChild(zn);let pi=null,Kl=null,Gl=s=>{!Rh()||!s||(Kl=s,pi===null&&(pi=setTimeout(()=>{pi=null,Kl&&Rh()&&(zn.textContent=Kl),Kl=null},400)))},Xl="empty",Ql=0,ep=()=>Ql||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,es=()=>{let l=ke.style.display==="none"?0:ke.offsetHeight;Bt.style.bottom=`${l+ep()+sA}px`};es();let tp=()=>{ea||(ke.style.marginBottom=Ql>0?`${Ql}px`:"")},Yl=()=>{let s=mg(n,Le()),l=Cn(n),g=ke.style.display==="none"?0:ke.offsetHeight,v=l.anchor==="center"&&Xl==="empty"?Al(l.anchorComposerTop)??Al("44%"):null,A=v===null||Le()?0:KC({columnHeight:de.clientHeight,footerHeight:g,fraction:v});e.style.setProperty("--persona-composer-overlay-height",`${g}px`),e.style.setProperty("--persona-composer-lift",`${s==="overlay"?A:0}px`),Ql=s==="block"?A:0,tp(),es()},Hh=()=>{let s=!!di();Bt.setAttribute("aria-label",di()||"Jump to latest"),Bt.title=di(),Bt.setAttribute("data-persona-scroll-to-bottom-has-label",s?"true":"false"),ui.innerHTML="";let l=le(aA(),"14px","currentColor",2);l?(ui.appendChild(l),ui.style.display=""):ui.style.display="none",Zu.textContent=di(),Zu.style.display=s?"":"none"};Hh();let Ze=null,Rt=null,he=Vx(),dA=s=>{try{de.dispatchEvent(new CustomEvent("persona:composer:state",{detail:s,bubbles:!0,composed:!0}))}catch{}};he.subscribe(dA);let An=()=>{he.setText(ie?.value??"")},ts=()=>{he.setMentionRefs(Rt?.getMentionRefs()??[])},cA=s=>({id:s.id,name:s.file.name,mimeType:s.file.type,size:s.file.size,status:s.status,progress:s.progress,error:s.error}),Wh=s=>{let l=Object.freeze(s.map(cA));he.setAttachments(l);try{n.attachments?.onChange?.(l)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Pp()};he.setSelectedModelId(n.composer?.selectedModelId);let fi=()=>n.composer?.modes??[],Qs=()=>hC(fi(),n.composer?.modeGroups);{let s=ou(n.composer?.defaultActiveModeIds??[],fi());s.length&&he.setActiveModeIds(s)}function Bh(s){if(he.getState().selectedModelId!==s){he.setSelectedModelId(s),Sr?.repaint();try{n.composer?.onModelChange?.(s)}catch(l){console.error("[AgentWidget] composer.onModelChange failed:",l)}}}function Jl(s){he.setActiveModeIds(s),Kn?.render(s,Qs()),Ys.forEach(l=>l.repaint()),Tn?.resolve(),wd(),un()}function op(s){Jl(yC(he.getState().activeModeIds,s,fi(),n.composer?.modeGroups))}let Sr=null,np=null,Kn=null,Ys=new Map,wr=null;function Mn(s){he.setQuote(s),wr?.render(he.getState().quote),un(),Ey()}let Oh=!1;function rp(){let s=n.composer?.streamingSubmitBehavior??"block";return s!=="interrupt"?s:n.clientToken?"interrupt":(!Oh&&n.debug===!0&&(Oh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Ar=null;function Js(s){he.setPendingSubmission(s),Ar?.render(he.getState().pendingSubmission),un()}let uA=s=>{let l=Ys.get(s);if(l)return l;let f=xC({groupId:s,getGroup:()=>n.composer?.modeGroups?.find(g=>g.id===s),getModes:()=>fi().filter(g=>g.groupId===s),getActiveIds:()=>he.getState().activeModeIds,onSelect:g=>op(g)});return Ys.set(s,f),f},pA=()=>{let s=[],l=he.getState().activeModeIds,f=new Set;if(fi().forEach((g,v)=>{if(tu(g.groupId,n.composer?.modeGroups)){let A=g.groupId;if(f.has(A))return;f.add(A);let _=uA(A);_.action.order=ag(v),_.action.label=n.composer?.modeGroups?.find($=>$.id===A)?.label??A,s.push(_.action);return}s.push({id:mC(g.id),kind:"button",placement:"start",order:ag(v),presentation:g.presentation??"auto",label:g.label,shortLabel:g.shortLabel,iconName:g.iconName,pressed:l.includes(g.id),onSelect:()=>op(g.id)})}),n.composer?.models?.length&&!i.some(g=>g.renderComposer)){let g=n.composer?.modelPicker?.presentation??"native";(!Sr||np!==g)&&(np=g,Sr=pC({getModels:()=>n.composer?.models??[],getSelectedModelId:()=>he.getState().selectedModelId,onSelect:v=>Bh(v),presentation:g,getSuffix:()=>n.composer?.modelPicker?.suffix})),s.push(Sr.action)}return s},sp=null,Dh=i.find(s=>s.renderHeader);if(Dh?.renderHeader){let s=Dh.renderHeader({config:n,defaultRenderer:()=>{let l=gr({config:n,showClose:qe()});return Fs(de,l,n),l.header},onClose:()=>pt(!1,"user")});if(s){let l=Ae;l&&(l.replaceWith(s),Ae=s,_o.header.element=s)}}let _h=()=>{gt&&(oe.style.display="none",ke.parentNode?.insertBefore(gt.element,ke),gt.update())},ap=()=>{if(!We){$l();return}if(zt=!0,gt?_h():Qg().then(l=>{gt||!zt||!We||(gt=l.createEventStreamView({buffer:We,getFullHistory:()=>We.getAllFromStore(),onClose:()=>Zs(),config:n,plugins:i,getThroughput:()=>st?.getMetric()??{status:"idle"},renderIconByName:le}),_h())}).catch(()=>{Zs()}),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${xo.actionIconColor}`;let l=n.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&tt.classList.add(f))}let s=()=>{if(!zt)return;let l=Date.now();l-ao>=200&&(gt?.update(),ao=l),It=requestAnimationFrame(s)};ao=0,It=requestAnimationFrame(s),$t(),C.emit("eventStream:opened",{timestamp:Date.now()})},Zs=()=>{if(zt){if(zt=!1,gt&>.element.remove(),oe.style.display="",tt){tt.style.boxShadow="";let s=n.features?.eventStream?.classNames?.toggleButtonActive;s&&s.split(/\s+/).forEach(l=>l&&tt.classList.remove(l))}It!==null&&(cancelAnimationFrame(It),It=null),$t(),C.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(E){let s=n.features?.eventStream?.classNames,l="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"+(s?.toggleButton?" "+s.toggleButton:"");tt=R("button",l),tt.style.width="28px",tt.style.height="28px",tt.style.color=xo.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let f=Ut(_a,"18px","currentColor",1.5);f&&tt.appendChild(f);let g=Oe.clearChatButtonWrapper,v=Oe.closeButtonWrapper,A=g||v;A&&A.parentNode===Ae?Ae.insertBefore(tt,A):Ae.appendChild(tt),tt.addEventListener("click",()=>{zt?Zs():ap()})}let Nh=s=>{let l=n.attachments;if(!l?.enabled)return;let f=s.querySelector("[data-persona-composer-attachment-previews]")??s.querySelector(".persona-attachment-previews");if(!f){f=R("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let v=s.querySelector("[data-persona-composer-form]");v?.parentNode?v.parentNode.insertBefore(f,v):s.insertBefore(f,s.firstChild)}if(!(s.querySelector("[data-persona-composer-attachment-input]")??s.querySelector('input[type="file"]'))){let v=R("input");v.type="file",v.setAttribute("data-persona-composer-attachment-input",""),v.accept=(l.allowedTypes??mr).join(","),v.multiple=(l.maxFiles??4)>1,v.style.display="none",v.setAttribute("aria-label",l.buttonTooltipText??"Attach files"),s.appendChild(v)}},ea=!1,Fh=s=>{let l=i.find(v=>v.renderComposer);if(!l?.renderComposer)return null;let f=n.composer,g=u?I.isStreaming():!1;return l.renderComposer({config:n,defaultRenderer:s,requestRender:()=>Zb(),storage:p(l.id),onSubmit:v=>{!I||I.isStreaming()||Qd(v.trim(),{consumeDraft:!1})},streaming:g,disabled:g,openAttachmentPicker:()=>{Ln()||ht?.click()},models:f?.models,selectedModelId:he.getState().selectedModelId??f?.selectedModelId,onModelChange:v=>Bh(v),onVoiceToggle:n.voiceRecognition?.enabled===!0?()=>{sp?.()}:void 0})},Uh=Fh(()=>Vs({config:n}).footer);Uh&&(_o.replaceComposer(Uh),ke=_o.composer.footer,ea=!0);let ot=null,fA=s=>{cn=s.form,ie=s.input,wn=s.sendButton?s.sendButton.parentElement:null,s.sendButton&&(we=s.sendButton),s.micButton&&(ne=s.micButton,Fo=s.micButton.parentElement),s.found.status&&(at=s.found.status),s.found.suggestions&&(vr=s.found.suggestions),s.attachmentButton&&(St=s.attachmentButton,Mo=s.attachmentButton.parentElement),ht=s.attachmentInput??null,To=s.attachmentPreviews??null,s.found.actionsRow&&(rA=s.found.actionsRow),Yu=s.found.actionsStart,zl=s.found.actionsEnd};function ip(){let s=ie;if(!s)return;let l=n.composer?.inputAttributes,f=!l?.ariaLabel&&!(s instanceof HTMLTextAreaElement)?s.getAttribute("aria-label"):null;zc(s,l),f&&s.setAttribute("aria-label",f),jc(s,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:xl(s)}),eC(s,$c(n.composer?.maxLines,Le()?5:3))}let qh=s=>{ot=jx(s,{debug:n.debug===!0}),ot&&fA(ot),ip()};Nh(ke),qh(ke),An();let mi=Gr(n,Le());mi&&(Te.style.maxWidth=mi,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",No.style.maxWidth=mi,No.style.marginLeft="auto",No.style.marginRight="auto",No.style.width="100%",Qu.style.maxWidth=mi,li.style.maxWidth=mi,li.style.marginLeft="auto",li.style.marginRight="auto",li.style.width="100%");let Vh=()=>{let s=Gr(n,Le());if(!(!s||Le()))for(let l of[cn,vr,To,at])l&&(l.style.maxWidth=s,l.style.marginLeft="auto",l.style.marginRight="auto",l.style.width="100%")};Vh();let $h=()=>{!n.attachments?.enabled||!ht||!To||(Ze?Ze.remountPreviews(To):(Ze=Os.fromConfig(n.attachments,Wh),Ze.setPreviewsContainer(To)),ot?.addListener(ht,"change",s=>{let l=s.target;Ze?.handleFileSelect(l.files),l.value=""}),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(Iw(n.attachments.dropOverlay)))};$h();let mA=()=>Rt?.prefetch(),jh=()=>{if(!n.contextMentions?.enabled||!ie)return;let s=ot?.header??null,l=s?sg(s):void 0;if(Rt=qC({config:n,textarea:ie,anchor:cn??ie,getMessages:()=>I.getMessages(),liveRegionHost:de,chipRow:l}),Rt&&!l){let f=ie;f.parentElement?.insertBefore(Rt.contextRow,f)}};jh();let Tn=null,gA={getState:()=>he.getState(),getValue:()=>ie?.value??"",setValue:s=>{ie&&(ie.value=s,ie.dispatchEvent(new Event("input",{bubbles:!0})),An())},submit:()=>{LC(ot?.form??null)},openAttachmentPicker:()=>{Ln()||ht?.click()},toggleVoice:()=>{sp?.()},requestRender:()=>Tn?.resolve()},hA=()=>{let s=[];return(Rt?.affordanceButtons??[]).forEach((f,g)=>{s.push({id:`core:mention-${g}`,placement:"start",order:Fn.mention+g,element:f,managed:!0})}),Mo&&s.push({id:"core:attachment",placement:"start",order:Fn.attachment,element:Mo}),Fo&&s.push({id:"core:mic",placement:"end",order:Fn.mic,element:Fo}),wn&&s.push({id:"core:send",placement:"end",order:Fn.send,element:wn}),s},zh=()=>{Tn?.destroy(),Tn=dC({getBindings:()=>ot,collect:()=>({builtIns:hA(),configActions:[...pA(),...n.composer?.actions??[]],plugins:i,contributionContext:{config:n,getState:()=>he.getState(),requestRender:()=>Tn?.resolve()},debug:n.debug===!0}),actionContext:gA,getState:()=>he.getState(),getOverflow:()=>n.composer?.actionOverflow,reportError:(s,l)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${l.actionId}" failed:`,s)}}),Tn.resolve()};zh();let lp=()=>{if(Kn?.destroy(),Kn=null,!Qs().length)return;let s=ot?.header;s&&(Kn=fC({row:sg(s),onRemove:l=>op(l),initialIds:he.getState().activeModeIds}),Kn.render(he.getState().activeModeIds,Qs()))};lp();let Kh=()=>{wr?.destroy(),wr=null,Ar?.destroy(),Ar=null;let s=ot?.header;s&&(wr=CC({onDismiss:()=>Mn(void 0)}),s.appendChild(wr.element),wr.render(he.getState().quote),rp()==="defer-one"&&(Ar=SC({onEdit:()=>$M(),onRemove:()=>Js(void 0)}),s.appendChild(Ar.element),Ar.render(he.getState().pendingSubmission)))};Kh();let dp=PC(),yA=()=>{let s=ot?.header?.querySelector(rg);if(s)return s.childElementCount>0;let l=he.getState();return l.mentionRefs.length>0||ou(l.activeModeIds,Qs()).length>0},Gh=()=>!1;function un(){let s=he.getState(),l=dp.observe(kC(ie),s.text);ke.toggleAttribute("data-persona-composer-compact",EC({text:s.text,wrapped:l,hasAttachments:s.attachments.length>0,hasChips:yA(),hasQuote:s.quote!==void 0,hasPendingSubmission:s.pendingSubmission!==void 0,dictationActive:Gh()}))}function Xh(){n.composer?.layout==="single-row"&&!Le()?ke.setAttribute("data-persona-composer-layout","single-row"):ke.removeAttribute("data-persona-composer-layout")}Xh(),he.subscribe(()=>{Tn?.sync(),Pp(),Cd(),un(),Ey()}),Cd();let Qh=!1,bA=s=>{if(Qh||n.debug!==!0)return;let l=["messages","composer"].filter(f=>s[f]);l.length&&(Qh=!0,console.warn(`[persona] layout.slots.${l.join(" and layout.slots.")} ${l.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let s=n.layout?.slots??{};bA(s);let l=g=>{switch(g){case"body-top":return oe.querySelector("[data-persona-intro-card]");case"messages":return Te;case"footer-top":return vr;case"composer":return cn;case"footer-bottom":return at;default:return null}},f=(g,v)=>{switch(g){case"header-left":case"header-center":case"header-right":if(g==="header-left")Ae.insertBefore(v,Ae.firstChild);else if(g==="header-right")Ae.appendChild(v);else{let A=Ae.querySelector(".persona-flex-col");A?A.parentNode?.insertBefore(v,A.nextSibling):Ae.appendChild(v)}break;case"body-top":{let A=oe.querySelector("[data-persona-intro-card]");A?A.replaceWith(v):oe.insertBefore(v,oe.firstChild);break}case"body-bottom":oe.appendChild(v);break;case"footer-top":vr.replaceWith(v);break;case"footer-bottom":at.replaceWith(v);break;default:break}};for(let[g,v]of Object.entries(s))if(v)try{let A=v({config:n,defaultContent:()=>l(g)});A&&f(g,A)}catch(A){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${g}":`,A)}})();let Yh=s=>{let f=s.target.closest('button[data-expand-header="true"]');if(!f)return;let g=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let A=f.getAttribute("data-bubble-type");if(A==="reasoning")ei.has(v)?ei.delete(v):ei.add(v),zS(v,g);else if(A==="tool")ti.has(v)?ti.delete(v):ti.add(v),GS(v,g,n);else if(A==="approval"&&m){let $=((n.approval!==!1?n.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",U=m.approvalDetailsExpansionState.get(v)??$;m.approvalDetailsExpansionState.set(v,!U),m.updateApprovalDetailsUI(v,g,n)}Ot.delete(v)};Te.addEventListener("pointerdown",s=>{s.target.closest('button[data-expand-header="true"]')&&(s.preventDefault(),Yh(s))}),Te.addEventListener("keydown",s=>{let l=s.target;(s.key==="Enter"||s.key===" ")&&l.closest('button[data-expand-header="true"]')&&(s.preventDefault(),Yh(s))}),Te.addEventListener("copy",s=>{let{clipboardData:l}=s;if(!l)return;let f=Te.getRootNode(),g=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!g||g.isCollapsed)return;let v=g.toString(),A=JC(v);!A||A===v||(l.setData("text/plain",A),s.preventDefault())});let cp=new Map,Jh=null,Zh="idle",vA={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},xA=(s,l)=>{let{icon:f,label:g}=vA[l];s.setAttribute("aria-label",g),s.title=g,s.setAttribute("aria-pressed",l==="idle"?"false":"true"),s.classList.toggle("persona-message-action-active",l!=="idle"),s.classList.toggle("persona-message-action-loading",l==="loading");let v=le(f,14,"currentColor",2);v&&(s.innerHTML="",s.appendChild(v))},ey=()=>{Te.querySelectorAll('[data-action="read-aloud"]').forEach(l=>{let g=l.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;xA(l,g&&g===Jh?Zh:"idle")})};Te.addEventListener("click",s=>{let f=s.target.closest(".persona-message-action-btn[data-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest("[data-actions-for]");if(!g)return;let v=g.getAttribute("data-actions-for");if(!v)return;let A=f.getAttribute("data-action");if(A==="copy"){let $=I.getMessages().find(U=>U.id===v);if($&&Gs.onCopy){let U=$.content||"";navigator.clipboard.writeText(U).then(()=>{f.classList.add("persona-message-action-success");let j=Ut(Na,14,"currentColor",2);j&&(f.innerHTML="",f.appendChild(j)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let J=Ut(Fa,14,"currentColor",2);J&&(f.innerHTML="",f.appendChild(J))},2e3)}).catch(j=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",j)}),Gs.onCopy($)}}else if(A==="read-aloud")I.toggleReadAloud(v);else if(A==="upvote"||A==="downvote"){let $=(cp.get(v)??null)===A,U=A==="upvote"?"thumbs-up":"thumbs-down";if($){cp.delete(v),f.classList.remove("persona-message-action-active");let j=le(U,14,"currentColor",2);j&&(f.innerHTML="",f.appendChild(j))}else{let j=A==="upvote"?"downvote":"upvote",J=g.querySelector(`[data-action="${j}"]`);if(J){J.classList.remove("persona-message-action-active");let ft=le(j==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ft&&(J.innerHTML="",J.appendChild(ft))}cp.set(v,A),f.classList.add("persona-message-action-active");let re=le(U,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(re)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Ye=I.getMessages().find(ct=>ct.id===v);Ye&&Gs.onFeedback&&Gs.onFeedback({type:A,messageId:Ye.id,message:Ye})}}else if(A==="regenerate")Zl?.regenerate(v);else if(A==="edit")Zl?.edit(v);else if(A==="quote")Zl?.quote(v);else if(A?.startsWith(xu)){let _=A.slice(xu.length),$=n.messageActions?.custom?.find(j=>j.id===_),U=I.getMessages().find(j=>j.id===v);if(!$||!U)return;try{$.onSelect(U)}catch(j){console.error(`[AgentWidget] messageActions.custom "${_}" onSelect failed:`,j)}}});let Zl=null;Te.addEventListener("click",s=>{let f=s.target.closest("button[data-approval-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest(".persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let A=f.getAttribute("data-approval-action");if(!A)return;let _=A==="approve"?"approved":"denied",U=I.getMessages().find(J=>J.id===v);if(!U?.approval)return;let j=g.querySelector("[data-approval-buttons]");j&&j.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),U.approval.toolType==="webmcp"?I.resolveWebMcpApproval(v,_):I.resolveApproval(U.approval,_)});let $e=null,ty=!1,gi=null,os=()=>{},hi="none",ed=null,Yo={artifacts:[],selectedId:null},Gn=!1,pn=!1,yi=!1,ta=!1,oy=()=>ta||Yo.artifacts.some(s=>Dn(n.features?.artifacts,s)==="panel"),td=()=>Yo.artifacts.length>0&&!Gn&&oy(),dt={current:null},up=(s,l)=>{let f=I.getArtifactById(l),g=f?.markdown,v=f?.title||"artifact",A=f?.file,_=f?.artifactType??"markdown";if(!g){let j=s.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(j){let re=I.getMessages().find(ce=>ce.id===j);if(re?.rawContent)try{let ce=JSON.parse(re.rawContent);g=ce?.props?.markdown,v=ce?.props?.title||v,ce?.props?.file&&typeof ce.props.file=="object"&&(A=ce.props.file),!f&&typeof ce?.props?.artifactType=="string"&&(_=ce.props.artifactType)}catch{}}}return{markdown:g,title:v,file:A,artifactType:_}};Te.addEventListener("click",s=>{let f=s.target.closest("[data-download-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-download-artifact");if(!g||n.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:g})===!0)return;let{markdown:A,title:_,file:$}=up(f,g);if(!A)return;let U=hr();U&&U.triggerArtifactDownload(U.downloadInfoFor({title:_,markdown:A,file:$}))}),Te.addEventListener("click",s=>{let f=s.target.closest("[data-artifact-custom-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-artifact-custom-action");if(!g)return;let v=f.closest("[data-artifact-inline]"),A=v?null:f.closest("[data-open-artifact]"),_=v?v.getAttribute("data-artifact-inline"):A?.getAttribute("data-open-artifact")??null,U=(v?n.features?.artifacts?.inlineActions:n.features?.artifacts?.cardActions)?.find(ct=>ct.id===g);if(!U)return;let{markdown:j,title:J,file:re,artifactType:ce}=up(f,_??""),Ye={artifactId:_,title:J,artifactType:ce,markdown:j,file:re};try{Promise.resolve(U.onClick(Ye)).catch(()=>{})}catch{}}),Te.addEventListener("click",s=>{let f=s.target.closest("[data-copy-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-copy-artifact");if(!g)return;let v=I.getArtifactById(g),A=hr();if(!A)return;let _="";if(v)_=A.artifactCopyText(v);else{let{markdown:$,file:U,artifactType:j}=up(f,g);j==="markdown"&&(_=A.artifactCopyText({id:g,artifactType:"markdown",status:"complete",markdown:$??"",...U?{file:U}:{}}))}_&&navigator.clipboard.writeText(_).then(()=>{let $=Ut(Na,16,"currentColor",2);$&&(f.replaceChildren($),setTimeout(()=>{let U=Ut(Fa,16,"currentColor",2);U&&f.replaceChildren(U)},1500))}).catch(()=>{})}),Te.addEventListener("click",s=>{let f=s.target.closest("[data-expand-artifact-inline]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-expand-artifact-inline");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(Gn=!1,ta=!0,pn=!0,yi=!0,I.selectArtifact(g),fn())}),Te.addEventListener("click",s=>{let l=s.target;if(l.closest("[data-download-artifact]")||l.closest("[data-artifact-custom-action]"))return;let f=l.closest("[data-open-artifact]");if(!f)return;let g=f.getAttribute("data-open-artifact");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(s.preventDefault(),s.stopPropagation(),Gn=!1,ta=!0,I.selectArtifact(g),fn())}),Te.addEventListener("keydown",s=>{if(s.key!=="Enter"&&s.key!==" ")return;let l=s.target;!l.hasAttribute("data-open-artifact")&&!l.hasAttribute("data-expand-artifact-inline")||(s.preventDefault(),l.click())});let oa=Oe.composerOverlay,na=(s,l,f)=>{let g=l.trim();if(!g||!dt.current)return;let v=s.getAttribute("data-tool-call-id")??"",A=f.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:v,answer:g,answers:f.structured,values:f.values??(f.source==="multi"?g.split(", "):[g]),isFreeText:A,source:f.source},bubbles:!0,composed:!0})),Vr(oa,v);let _=dt.current.getMessages().find($=>$.toolCall?.id===v);_?.agentMetadata?.awaitingLocalTool?dt.current.resolveAskUserQuestion(_,f.structured??g):dt.current.sendMessage(g)},ns=s=>{let l=dt.current;if(!l)return;let f=s.getAttribute("data-tool-call-id")??"",g=l.getMessages().find(v=>v.toolCall?.id===f);g&&l.persistAskUserQuestionProgress(g,{answers:fc(s,g),currentIndex:sn(s)})},ny=s=>Object.entries(s).map(([l,f])=>`${l}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),pp=s=>{if(n.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let l=sn(s),f=Ia(s);if(l>=f-1)return;let g=dt.current?.getMessages().find(v=>v.toolCall?.id===s.getAttribute("data-tool-call-id"));g&&(mc(s,g,n,l+1),ns(s))};oa.addEventListener("click",s=>{let f=s.target.closest("[data-ask-user-action]");if(!f)return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;let v=f.getAttribute("data-ask-user-action");if(s.preventDefault(),s.stopPropagation(),v==="dismiss"){let A=g.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:A},bubbles:!0,composed:!0})),Vr(oa,A);let _=dt.current?.getMessages().find($=>$.toolCall?.id===A);_?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(_),dt.current?.resolveAskUserQuestion(_,"(dismissed)"));return}if(v==="pick"){let A=f.getAttribute("data-option-label");if(!A)return;let _=g.getAttribute("data-multi-select")==="true",$=qr(g);if($&&_){let U=Ls(g)[sn(g)],j=new Set(Array.isArray(U)?U:[]);j.has(A)?j.delete(A):j.add(A),$r(g,Array.from(j)),ns(g);return}if($){$r(g,A),ns(g),pp(g);return}if(_){let U=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",U?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!U);let j=g.querySelector('[data-ask-user-action="submit-multi"]');j&&(j.disabled=Vf(g).length===0);return}na(g,A,{source:"pick",values:[A]});return}if(v==="submit-multi"){let A=Vf(g);if(A.length===0)return;na(g,A.join(", "),{source:"multi",values:A});return}if(v==="open-free-text"){let A=g.querySelector('[data-ask-free-text-row="true"]');A&&(A.classList.remove("persona-hidden"),A.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(v==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(v==="submit-free-text"){let _=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!_.trim())return;if(qr(g)){$r(g,_.trim()),ns(g),pp(g);return}na(g,_,{source:"free-text"});return}if(v==="next"||v==="back"){if(!dt.current)return;let A=g.getAttribute("data-tool-call-id")??"",_=dt.current.getMessages().find(re=>re.toolCall?.id===A);if(!_)return;let U=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(U){let re=Ls(g)[sn(g)];(typeof re!="string"||re!==U)&&$r(g,U)}let j=v==="next"?1:-1,J=sn(g)+j;mc(g,_,n,J),ns(g);return}if(v==="submit-all"){if(!dt.current)return;let A=g.getAttribute("data-tool-call-id")??"",_=dt.current.getMessages().find(re=>re.toolCall?.id===A);if(!_)return;let U=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";U&&$r(g,U);let j=fc(g,_);dt.current.persistAskUserQuestionProgress(_,{answers:j,currentIndex:sn(g)});let J=ny(j);na(g,J||"(submitted)",{source:"submit-all",structured:j});return}if(v==="skip"){if(!dt.current)return;let A=g.getAttribute("data-tool-call-id")??"",_=dt.current.getMessages().find(ce=>ce.toolCall?.id===A);if(!_)return;let $=qr(g),U=sn(g),j=Ia(g),J=U>=j-1;if(!$){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:A},bubbles:!0,composed:!0})),Vr(oa,A),_.agentMetadata?.awaitingLocalTool&&(dt.current.markAskUserQuestionResolved(_),dt.current.resolveAskUserQuestion(_,"(dismissed)"));return}$r(g,"");let re=g.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),J){let ce=fc(g,_),Ye=ny(ce);na(g,Ye||"(skipped)",{source:"submit-all",structured:ce});return}mc(g,_,n,U+1),ns(g);return}}),oa.addEventListener("keydown",s=>{if(s.key!=="Enter")return;let f=s.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;s.preventDefault();let v=f.value;if(v.trim()){if(qr(g)){$r(g,v.trim()),ns(g),pp(g);return}na(g,v,{source:"free-text"})}});let ry=s=>{if(!/^[1-9]$/.test(s.key)||s.metaKey||s.ctrlKey||s.altKey)return;let l=s.target;if(l?.tagName==="INPUT"||l?.tagName==="TEXTAREA"||l?.isContentEditable)return;let f=oa.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let g=Number(s.key),A=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[g-1];A&&(s.preventDefault(),A.click())};document.addEventListener("keydown",ry);let En=null,bt=null,bi=null,od=null,nd=()=>{},sy=!1,rd="",sd="";function fp(){od?.(),od=null}let CA=()=>{let s=ha&&ws?.isConnected?ws:null,l=s?s.getBoundingClientRect().width:0;return l<=0?200:l+360},ay=()=>{if(!En||!bt)return;let s=e.classList.contains("persona-artifact-welded-split"),l=e.ownerDocument.defaultView??window,f=l.innerWidth<=640;if(!s||e.classList.contains("persona-artifact-narrow-host")||f){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let g=En.firstElementChild;if(!g||g===bt)return;let v=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${v}px`,bt.style.zIndex="5";let A=sh(En,l),_=g.offsetWidth+A/2-v/2;bt.style.left=`${Math.max(0,_)}px`},ad=()=>{},SA=()=>{let s=e.ownerDocument.defaultView??window,l=n.launcher?.mobileFullscreen??!0,f=n.launcher?.mobileBreakpoint??640;return!l||s.innerWidth>f?!1:pe||Ct(n)},id=()=>!So(n)||!td()||e.classList.contains("persona-artifact-narrow-host")||SA()||(e.ownerDocument.defaultView??window).innerWidth<oL?"none":th(n)?"detached":"welded",fn=()=>{if(!$e||!So(n))return;Ol(e,n),Dl(e,n),ad();let s=n.features?.artifacts?.layout?.narrowHostMaxWidth??520,l=Ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",l>0&&l<=s);let f=td();$e.setVisible(f),$e.update(Yo),Gn?($e.setMobileOpen(!1),$e.element.classList.add("persona-hidden"),$e.backdrop?.classList.add("persona-hidden"),pn=!1,yi=!1):Yo.artifacts.length>0&&oy()?($e.element.classList.remove("persona-hidden"),$e.setMobileOpen(!0)):($e.setMobileOpen(!1),$e.element.classList.add("persona-hidden"),$e.backdrop?.classList.add("persona-hidden"),pn=!1,yi=!1);let g=n.features?.artifacts?.layout?.showExpandToggle===!0;if($e.setExpandToggleVisible(g),$e.setCopyButtonVisible(n.features?.artifacts?.layout?.showCopyButton===!0),$e.setRefreshButtonVisible(typeof n.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),$e.setCustomActions(n.features?.artifacts?.toolbarActions??[]),$e.setTabFade(n.features?.artifacts?.layout?.tabFade),$e.setRenderTabBar(n.features?.artifacts?.renderTabBar),!g&&!yi&&(pn=!1),pn!==sy){let A=$e.element;pn?(rd=A.style.width,sd=A.style.maxWidth,A.style.removeProperty("width"),A.style.removeProperty("max-width")):(rd&&(A.style.width=rd),sd&&(A.style.maxWidth=sd),rd="",sd=""),sy=pn}e.classList.toggle("persona-artifact-expanded",pn),$e.setExpanded(pn);let v=id();v!==hi&&(hi=v,os()),nd()};if(So(n)){Ce.style.position="relative";let s=R("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),l=R("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");s.appendChild(de),En=l,l.appendChild(s),Ce.appendChild(l);let f=v=>{ty||$e||($e=v.createArtifactPane(n,{onSelect:A=>dt.current?.selectArtifact(A),onDismiss:()=>{Gn=!0,fn()},onToggleExpand:()=>{let A=!pn,_=Yo.selectedId??Yo.artifacts[Yo.artifacts.length-1]?.id??null;n.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:_,expanded:A})!==!0&&(pn=A,A||(yi=!1),fn())}}),$e.element.classList.add("persona-hidden"),l.appendChild($e.element),$e.backdrop&&Ce.appendChild($e.backdrop),nd(),fn())},g=hr();g?f(g):(Zg(()=>{let v=hr();v&&f(v)}),Iu().catch(()=>{})),nd=()=>{if(!En||!$e)return;if(!(n.features?.artifacts?.layout?.resizable===!0)){bi?.(),bi=null,fp(),bt&&(bt.remove(),bt=null),$e.element.style.removeProperty("width"),$e.element.style.removeProperty("maxWidth");return}if(!bt){let A=R("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");A.setAttribute("role","separator"),A.setAttribute("aria-orientation","vertical"),A.setAttribute("aria-label","Resize artifacts panel"),A.tabIndex=0;let _=e.ownerDocument,$=_.defaultView??window,U=j=>{if(!$e||j.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||$.innerWidth<=640)return;j.preventDefault(),fp();let J=j.clientX,re=$e.element.getBoundingClientRect().width,ce=n.features?.artifacts?.layout,Ye=ft=>{let Gt=En.getBoundingClientRect().width,_t=e.classList.contains("persona-artifact-welded-split"),Pt=sh(En,$),io=_t?0:A.getBoundingClientRect().width||6,et=re-(ft.clientX-J),lo=dw(et,Gt,Pt,io,ce?.resizableMinWidth,ce?.resizableMaxWidth,CA());$e.element.style.width=`${lo}px`,$e.element.style.maxWidth="none",ay()},ct=()=>{_.removeEventListener("pointermove",Ye),_.removeEventListener("pointerup",ct),_.removeEventListener("pointercancel",ct),od=null;try{A.releasePointerCapture(j.pointerId)}catch{}};od=ct,_.addEventListener("pointermove",Ye),_.addEventListener("pointerup",ct),_.addEventListener("pointercancel",ct);try{A.setPointerCapture(j.pointerId)}catch{}};A.addEventListener("pointerdown",U),bt=A,En.insertBefore(A,$e.element),bi=()=>{A.removeEventListener("pointerdown",U)}}if(bt){let A=td();bt.classList.toggle("persona-hidden",!A),ay()}},ad=()=>{if(!pe||!$e||(n.launcher?.sidebarMode??!1)||Ct(n)&&Do(n).reveal==="emerge")return;let A=e.ownerDocument.defaultView??window,_=n.launcher?.mobileFullscreen??!0,$=n.launcher?.mobileBreakpoint??640;if(_&&A.innerWidth<=$||!nw(n,pe))return;let U=n.launcher?.width??n.launcherWidth??Ko,j=n.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";td()?(Ce.style.width=j,Ce.style.maxWidth=j):(Ce.style.width=U,Ce.style.maxWidth=U)},typeof ResizeObserver<"u"&&(gi=new ResizeObserver(()=>{fn()}),gi.observe(Ce))}else Ce.appendChild(de);Le()&&Kt&&(Oe.peekBanner&&Kt.appendChild(Oe.peekBanner),Kt.appendChild(ke)),e.appendChild(Ge),Kt&&e.appendChild(Kt);let mp=()=>{if(Le()){Ce.style.width="100%",Ce.style.maxWidth="100%";let De=n.launcher?.composerBar??{},xe=Ge.dataset.state==="expanded",uo=De.expandedSize??"anchored";if(!(xe&&uo!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let Io=n.theme?.components?.panel,Ro=Kr(n),lt=(Ht,Ho)=>Ht==null||Ht===""?Ho:vo(Ro,Ht)??Ht,ut="1px solid var(--persona-border)",Be="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",lr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=lt(Io?.border,ut),de.style.borderRadius=lt(Io?.borderRadius,lr),de.style.boxShadow=lt(Io?.shadow,Be),de.style.overflow="hidden";return}let s=Ct(n),l=n.launcher?.sidebarMode??!1,f=s||l||(n.launcher?.fullHeight??!1),g=n.launcher?.enabled===!1,v=n.launcher?.detachedPanel===!0,A=n.theme?.components?.panel,_=Kr(n),$=(De,xe)=>De==null||De===""?xe:vo(_,De)??De,U=e.ownerDocument.defaultView??window,j=n.launcher?.mobileFullscreen??!0,J=n.launcher?.mobileBreakpoint??640,re=U.innerWidth<=J,ce=j&&re&&pe,Ye=s&&j&&re,ct=n.launcher?.position??"bottom-left",ft=ct==="bottom-left"||ct==="top-left",Gt=n.launcher?.zIndex??ro,_t="var(--persona-panel-border, 1px solid var(--persona-border))",Pt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",et=v&&!ce&&!Ye;et?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let lo=et?_t:l||ce?"none":_t,Wn=et?Pt:ce?"none":l?ft?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":g?"none":Pt;s&&!ce&&!et&&(Wn="none",lo="none");let ir=et?io:l||ce?"0":io,hn=$(A?.border,lo),zi=$(A?.shadow,Wn),ks=$(A?.borderRadius,ir),yn=id(),eo=yn==="detached",bn=yn==="welded";e.classList.toggle("persona-artifact-detached-split",eo),e.classList.toggle("persona-artifact-welded-split",bn);let Ea="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",Se=(n.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&So(n)&&th(n)&&g&&!s;e.classList.toggle("persona-artifact-chat-flush",Se);let se=eo||Se?"none":zi,kt=eo?_t:bn?"none":hn,Nt=eo?io:ks;Se&&(kt="none",Nt="0");let to=A?.borderRadius!=null&&A.borderRadius!=="",Ft=Se&&!to?"0":ks,jt=oe.scrollTop;e.style.cssText="",Ge.style.cssText="",Ce.style.cssText="",de.style.cssText="",oe.style.cssText="",ea||(ke.style.cssText=""),zt&&(oe.style.display="none"),(f||g)&&(e.style.minWidth="0");let Lt=()=>{if(jt<=0)return;(oe.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(oe.scrollTop===jt)return;let xe=oe.scrollHeight-oe.clientHeight;xe<=0||(oe.scrollTop=Math.min(jt,xe))})};if(ce){Ge.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ge.style.cssText=`
|
|
44
|
+
`,L.addEventListener("click",()=>{m=x,E.forEach((N,X)=>{let V=X<x;N.classList.toggle("selected",V),N.setAttribute("aria-checked",X===x-1?"true":"false")})}),E.push(L),M.appendChild(L)}h.appendChild(M);let T=null;if(c){let x=document.createElement("div");x.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=a,T.rows=3,T.setAttribute("aria-label","Additional comments"),x.appendChild(T),h.appendChild(x)}let I=document.createElement("div");I.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=d,b.addEventListener("click",()=>{o?.(),p.remove()});let S=document.createElement("button");return S.type="button",S.className="persona-feedback-btn persona-feedback-btn-submit",S.textContent=i,S.addEventListener("click",async()=>{if(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}S.disabled=!0,S.textContent="Submitting...";try{let x=T?.value.trim()||void 0;await t(m,x),p.remove()}catch(x){S.disabled=!1,S.textContent=i,console.error("[CSAT Feedback] Failed to submit:",x)}}),I.appendChild(b),I.appendChild(S),h.appendChild(I),p.appendChild(h),p}function Uu(e){let{onSubmit:t,onDismiss:o,title:n="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,lowLabel:u="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let h=null,y=document.createElement("div");y.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=n,C.appendChild(A);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,C.appendChild(M),y.appendChild(C);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=u;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=p,T.appendChild(I),T.appendChild(b);let S=document.createElement("div");S.className="persona-feedback-numbers";let x=[];for(let P=0;P<=10;P++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${P} out of 10`),O.textContent=String(P),O.dataset.rating=String(P),P<=6?O.classList.add("persona-feedback-detractor"):P<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{h=P,x.forEach((D,W)=>{D.classList.toggle("selected",W===P),D.setAttribute("aria-checked",W===P?"true":"false")})}),x.push(O),S.appendChild(O)}E.appendChild(T),E.appendChild(S),y.appendChild(E);let L=null;if(c){let P=document.createElement("div");P.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=a,L.rows=3,L.setAttribute("aria-label","Additional comments"),P.appendChild(L),y.appendChild(P)}let N=document.createElement("div");N.className="persona-feedback-actions";let X=document.createElement("button");X.type="button",X.className="persona-feedback-btn persona-feedback-btn-skip",X.textContent=d,X.addEventListener("click",()=>{o?.(),m.remove()});let V=document.createElement("button");return V.type="button",V.className="persona-feedback-btn persona-feedback-btn-submit",V.textContent=i,V.addEventListener("click",async()=>{if(h===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}V.disabled=!0,V.textContent="Submitting...";try{let P=L?.value.trim()||void 0;await t(h,P),m.remove()}catch(P){V.disabled=!1,V.textContent=i,console.error("[NPS Feedback] Failed to submit:",P)}}),N.appendChild(X),N.appendChild(V),y.appendChild(N),m.appendChild(y),m}var ai="persona-chat-history",iL=30*1e3,lL=641,ii="data-persona-composer-reason",dL={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function cL(e){if(!e)return[];let t=[],o=Array.from(e.items??[]);for(let n of o){if(n.kind!=="file"||!n.type.startsWith("image/"))continue;let r=n.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=dL[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith("image/")&&t.push(n);return t}function qu(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function uL(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function pL(e){try{let t=e==="local"?localStorage:sessionStorage,o="__persist_test__";return t.setItem(o,"1"),t.removeItem(o),t}catch{return null}}var fh=e=>!e||typeof e!="object"?{}:{...e},Rw=e=>e.map(t=>({...t,streaming:!1})),Hw=(e,t,o)=>{let n=e?.markdown?Yi(e.markdown):null,r=ic(e?.sanitize);e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,i=d=>{let c=d.text??"",u=d.message.rawContent??null;if(t){let h=t.process({text:c,raw:u??c,message:d.message,streaming:d.streaming});h!==null&&(c=h.text,h.persist||(d.message.__skipPersist=!0),h.resubmit&&!d.streaming&&o&&o())}let p=On()!==null,m;if(e?.postprocessMessage){let h=e.postprocessMessage({...d,text:c,raw:u??d.text??""});m=r?r(h):h}else if(n){let h=d.streaming?Av(c):c,y=n(h);m=r&&p?r(y):y}else m=dr(c);return m};return d=>{try{return i(d)}catch(c){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),dr(d.text??"")}}};function Ww(e){let t=H("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let o=e?.iconName??"upload",n=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,i=le(o,n,r,a);if(i&&t.appendChild(i),e?.label){let d=H("span","persona-drop-overlay-label");d.textContent=e.label,t.appendChild(d)}return t}var fL=(e,t)=>{let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];o[n]=a?{...a,...r}:r}return o},mL=e=>e.reduce((t,o)=>({blocks:[...t.blocks,...o.blocks],contentParts:[...t.contentParts,...o.contentParts],context:fL(t.context,o.context)}),{blocks:[],contentParts:[],context:{}}),Vu=(e,t,o)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=$a(t),r=()=>{Jx({delayMs:n.tooltip?.delayMs??200,skipDelayMs:n.tooltip?.skipDelayMs??300})};r();let a=n.features;n=_l(n);let i=Nl.getForInstance(n.plugins),d=ZC(e),c=[],u=!1,p=GS(()=>n),m=null,h=null,y=null,C=!1,A=null,M=s=>{m=s,s.initApprovalUi({webMcpToolTitle:lc});let l=s.createBuiltInApprovalPlugin();h=l.plugin,y=l.teardown},E=()=>{if(m)return m;let s=ew();return s?(M(s),s):(ZS().then(l=>{C||m||(M(l),A?.())}).catch(()=>{}),null)},T=!1,I=!1,b=null,S=(s,l,f,g)=>{if(!s.querySelector("[data-tv-form]"))return;let v=gw();if(v){v.enhanceWithForms(s,l,f,g);return}mw().then(()=>{T||I||!b||(I=!0,b())}).catch(()=>{})};n.components&&Sn.registerAll(n.components);let x=bw(),N=n.persistState===!1?null:n.storageAdapter??Bu(),X=!!n.clientToken&&typeof n.reconnectStream!="function",V={},P=null,O,D=new Promise(s=>{O=s}),W,ee=!1,G=s=>{if(n.onStateLoaded)try{let l=n.onStateLoaded(s);if(l&&typeof l=="object"&&"state"in l){let{state:f,open:g}=l;return g&&(ee=!0),f}return l}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}return s};if(N?.load)try{let s=N.load();if(s&&typeof s.then=="function")P=s.then(l=>G(l??{messages:[],metadata:{}}));else{let f=G(s??{messages:[],metadata:{}});f.metadata&&(V=fh(f.metadata)),f.messages?.length&&(n={...n,initialMessages:f.messages}),f.artifacts?.length&&(n={...n,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),W=f.draft}}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",s)}else if(n.onStateLoaded)try{let s=G({messages:[],metadata:{}});s.messages?.length&&(n={...n,initialMessages:s.messages})}catch(s){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",s)}P||O();let ue=()=>V,ae=s=>{V=s({...V})??{},la()},ye=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Fl],Re=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ks.message,Ks.messageAndClick],be=Ul({parsers:ye,handlers:Re,getSessionMetadata:ue,updateSessionMetadata:ae,emit:x.emit,documentRef:typeof document<"u"?document:null});be.syncFromMetadata();let pe=n.launcher?.enabled??!0,yt=n.launcher?.autoExpand??!1,Pe=n.autoFocusInput??!1,q=yt,Ue=pe,Je=n.layout?.header?.layout,so=!1,Le=()=>Qr(n),qe=()=>pe||Le(),ve=Le()?!1:pe?yt:!0,po=!1,dn=null,Vn=()=>{po=!0,dn&&clearTimeout(dn),dn=setTimeout(()=>{po&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),po=!1)},1e4)},wt=Hw(n,be,Vn),$n=n.features?.showReasoning??!0,z=n.features?.showToolCalls??!0,k=n.features?.showEventStreamToggle??!1,F=n.features?.scrollToBottom??{},K=n.features?.scrollBehavior??{},Y=()=>(typeof n.persistState=="object"?n.persistState?.keyPrefix:void 0)??"persona-",ge=`${Y()}event-stream`,Me=null,Ee=n.features?.eventStream?.maxEvents??2e3,We=null,st=null,Ke=null,Ve=!1,gt=null,zt=!1,It=null,ao=0,wo=(s,l)=>{We?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:s,timestamp:Date.now(),payload:JSON.stringify(l)})},Ku=(s,l)=>{st?.processEvent(s,l),We?wo(s,l):Ke&&(Ke.length>=Ee&&Ke.shift(),Ke.push({type:s,payload:l}))},$l=()=>{We||!k||(Ke??(Ke=[]),Yg().then(s=>{if(Ve||We||!k)return;Me=new s.EventStreamStore(ge),We=new s.EventStreamBuffer(Ee,Me),st=st??new s.ThroughputTracker,Me.open().then(()=>We?.restore()).catch(f=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let l=Ke??[];Ke=null;for(let f of l)st?.processEvent(f.type,f.payload),wo(f.type,f.payload)}).catch(()=>{}))};k&&$l();let At=!1,Wt=null,Gu=()=>{},jn=()=>{},Eh=()=>{},Ph=()=>{},Xu=()=>{},oA=()=>zt||At&&Wt==="panel",Gs={onCopy:s=>{x.emit("message:copy",s),R?.isClientTokenMode()&&R.submitMessageFeedback(s.id,"copy").catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",l)}),n.messageActions?.onCopy?.(s)},onFeedback:s=>{x.emit("message:feedback",s),R?.isClientTokenMode()&&R.submitMessageFeedback(s.messageId,s.type).catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",l)}),n.messageActions?.onFeedback?.(s)}},Xs=n.statusIndicator??{},kh=s=>s==="idle"?Xs.idleText??qt.idle:s==="connecting"?Xs.connectingText??qt.connecting:s==="connected"?Xs.connectedText??qt.connected:s==="error"?Xs.errorText??qt.error:s==="paused"?Xs.pausedText??qt.paused:s==="resuming"?Xs.resumingText??qt.resuming:qt[s];function jl(s,l,f,g){if(!s.hasAttribute(ii))if(g==="idle"&&f.idleLink){s.textContent="";let v=document.createElement("a");v.href=f.idleLink,v.target="_blank",v.rel="noopener noreferrer",v.textContent=l,v.style.color="inherit",v.style.textDecoration="none",s.appendChild(v)}else s.textContent=l}let _o=KS({config:n,showClose:qe()}),{wrapper:Ge,panel:Ce,pillRoot:Kt}=_o.shell,Oe=_o.panelElements,{container:de,body:oe,messagesWrapper:Te,starterSuggestions:Qu,transcriptSuggestions:li,suggestions:vr,textarea:ie,sendButton:we,composerForm:cn,statusText:at,welcomeHost:Ao,welcomeIconHolder:nA,greetingHost:No,introKicker:rA,introTitle:sA,introSubtitle:aA,closeButton:Ne,iconHolder:Mt,headerTitle:xr,headerSubtitle:Jr,header:Ae,footer:ke,actionsRow:iA}=Oe,Yu=Oe.leftActions,zl=Oe.rightActions,wn=Oe.sendButtonWrapper,Lh=Oe.setSendButtonMode,ne=Oe.micButton,Fo=Oe.micButtonWrapper,St=Oe.attachmentButton,Mo=Oe.attachmentButtonWrapper,ht=Oe.attachmentInput,To=Oe.attachmentPreviewsContainer;de.classList.add("persona-relative"),oe.classList.add("persona-relative");let lA=12,di=()=>F.label??"",dA=()=>F.iconName??"arrow-down",cA=()=>F.enabled!==!1,Uo=()=>K.mode??"anchor-top",Cr=()=>Uo()==="follow"||Uo()==="anchor-top"&&vi,ci=()=>K.anchorTopOffset??16,uA=()=>K.restorePosition??"bottom",Ih=()=>K.pauseOnInteraction===!0,Rh=()=>K.showActivityWhilePinned!==!1,Hh=()=>K.announce===!0,Ju=()=>K.scrollbar??"on-scroll",Bt=H("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Bt.type="button",Bt.style.display="none",Bt.setAttribute("data-persona-scroll-to-bottom","true");let ui=H("span","persona-flex persona-items-center"),Zu=H("span",""),Zr=H("span","");Zr.setAttribute("data-persona-scroll-to-bottom-count",""),Zr.style.display="none",Bt.append(ui,Zu,Zr),de.appendChild(Bt);let Qo=H("div","persona-stream-anchor-spacer");Qo.setAttribute("aria-hidden","true"),Qo.setAttribute("data-persona-anchor-spacer",""),Qo.style.flexShrink="0",Qo.style.pointerEvents="none",Qo.style.height="0px",Qo.style.display="none",oe.appendChild(Qo);let zn=H("div","persona-sr-only");zn.setAttribute("aria-live","polite"),zn.setAttribute("aria-atomic","true"),zn.setAttribute("role","status"),zn.setAttribute("data-persona-live-region",""),Object.assign(zn.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),de.appendChild(zn);let pi=null,Kl=null,Gl=s=>{!Hh()||!s||(Kl=s,pi===null&&(pi=setTimeout(()=>{pi=null,Kl&&Hh()&&(zn.textContent=Kl),Kl=null},400)))},Xl="empty",Ql=0,ep=()=>Ql||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,es=()=>{let l=ke.style.display==="none"?0:ke.offsetHeight;Bt.style.bottom=`${l+ep()+lA}px`};es();let tp=()=>{ea||(ke.style.marginBottom=Ql>0?`${Ql}px`:"")},Yl=()=>{let s=gg(n,Le()),l=Cn(n),g=ke.style.display==="none"?0:ke.offsetHeight,v=l.anchor==="center"&&Xl==="empty"?Al(l.anchorComposerTop)??Al("44%"):null,w=v===null||Le()?0:QC({columnHeight:de.clientHeight,footerHeight:g,fraction:v});e.style.setProperty("--persona-composer-overlay-height",`${g}px`),e.style.setProperty("--persona-composer-lift",`${s==="overlay"?w:0}px`),Ql=s==="block"?w:0,tp(),es()},Wh=()=>{let s=!!di();Bt.setAttribute("aria-label",di()||"Jump to latest"),Bt.title=di(),Bt.setAttribute("data-persona-scroll-to-bottom-has-label",s?"true":"false"),ui.innerHTML="";let l=le(dA(),"14px","currentColor",2);l?(ui.appendChild(l),ui.style.display=""):ui.style.display="none",Zu.textContent=di(),Zu.style.display=s?"":"none"};Wh();let Ze=null,Rt=null,he=zx(),pA=s=>{try{de.dispatchEvent(new CustomEvent("persona:composer:state",{detail:s,bubbles:!0,composed:!0}))}catch{}};he.subscribe(pA);let An=()=>{he.setText(ie?.value??"")},ts=()=>{he.setMentionRefs(Rt?.getMentionRefs()??[])},fA=s=>({id:s.id,name:s.file.name,mimeType:s.file.type,size:s.file.size,status:s.status,progress:s.progress,error:s.error}),Bh=s=>{let l=Object.freeze(s.map(fA));he.setAttachments(l);try{n.attachments?.onChange?.(l)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Pp()};he.setSelectedModelId(n.composer?.selectedModelId);let fi=()=>n.composer?.modes??[],Qs=()=>vC(fi(),n.composer?.modeGroups);{let s=ou(n.composer?.defaultActiveModeIds??[],fi());s.length&&he.setActiveModeIds(s)}function Oh(s){if(he.getState().selectedModelId!==s){he.setSelectedModelId(s),Sr?.repaint();try{n.composer?.onModelChange?.(s)}catch(l){console.error("[AgentWidget] composer.onModelChange failed:",l)}}}function Jl(s){he.setActiveModeIds(s),Kn?.render(s,Qs()),Ys.forEach(l=>l.repaint()),Tn?.resolve(),wd(),un()}function op(s){Jl(xC(he.getState().activeModeIds,s,fi(),n.composer?.modeGroups))}let Sr=null,np=null,Kn=null,Ys=new Map,wr=null;function Mn(s){he.setQuote(s),wr?.render(he.getState().quote),un(),Py()}let Dh=!1;function rp(){let s=n.composer?.streamingSubmitBehavior??"block";return s!=="interrupt"?s:n.clientToken?"interrupt":(!Dh&&n.debug===!0&&(Dh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Ar=null;function Js(s){he.setPendingSubmission(s),Ar?.render(he.getState().pendingSubmission),un()}let mA=s=>{let l=Ys.get(s);if(l)return l;let f=wC({groupId:s,getGroup:()=>n.composer?.modeGroups?.find(g=>g.id===s),getModes:()=>fi().filter(g=>g.groupId===s),getActiveIds:()=>he.getState().activeModeIds,onSelect:g=>op(g)});return Ys.set(s,f),f},gA=()=>{let s=[],l=he.getState().activeModeIds,f=new Set;if(fi().forEach((g,v)=>{if(tu(g.groupId,n.composer?.modeGroups)){let w=g.groupId;if(f.has(w))return;f.add(w);let _=mA(w);_.action.order=ig(v),_.action.label=n.composer?.modeGroups?.find($=>$.id===w)?.label??w,s.push(_.action);return}s.push({id:yC(g.id),kind:"button",placement:"start",order:ig(v),presentation:g.presentation??"auto",label:g.label,shortLabel:g.shortLabel,iconName:g.iconName,pressed:l.includes(g.id),onSelect:()=>op(g.id)})}),n.composer?.models?.length&&!i.some(g=>g.renderComposer)){let g=n.composer?.modelPicker?.presentation??"native";(!Sr||np!==g)&&(np=g,Sr=gC({getModels:()=>n.composer?.models??[],getSelectedModelId:()=>he.getState().selectedModelId,onSelect:v=>Oh(v),presentation:g,getSuffix:()=>n.composer?.modelPicker?.suffix})),s.push(Sr.action)}return s},sp=null,_h=i.find(s=>s.renderHeader);if(_h?.renderHeader){let s=_h.renderHeader({config:n,defaultRenderer:()=>{let l=gr({config:n,showClose:qe()});return Fs(de,l,n),l.header},onClose:()=>pt(!1,"user")});if(s){let l=Ae;l&&(l.replaceWith(s),Ae=s,_o.header.element=s)}}let Nh=()=>{gt&&(oe.style.display="none",ke.parentNode?.insertBefore(gt.element,ke),gt.update())},ap=()=>{if(!We){$l();return}if(zt=!0,gt?Nh():Yg().then(l=>{gt||!zt||!We||(gt=l.createEventStreamView({buffer:We,getFullHistory:()=>We.getAllFromStore(),onClose:()=>Zs(),config:n,plugins:i,getThroughput:()=>st?.getMetric()??{status:"idle"},renderIconByName:le}),Nh())}).catch(()=>{Zs()}),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${xo.actionIconColor}`;let l=n.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&tt.classList.add(f))}let s=()=>{if(!zt)return;let l=Date.now();l-ao>=200&&(gt?.update(),ao=l),It=requestAnimationFrame(s)};ao=0,It=requestAnimationFrame(s),$t(),x.emit("eventStream:opened",{timestamp:Date.now()})},Zs=()=>{if(zt){if(zt=!1,gt&>.element.remove(),oe.style.display="",tt){tt.style.boxShadow="";let s=n.features?.eventStream?.classNames?.toggleButtonActive;s&&s.split(/\s+/).forEach(l=>l&&tt.classList.remove(l))}It!==null&&(cancelAnimationFrame(It),It=null),$t(),x.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(k){let s=n.features?.eventStream?.classNames,l="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"+(s?.toggleButton?" "+s.toggleButton:"");tt=H("button",l),tt.style.width="28px",tt.style.height="28px",tt.style.color=xo.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let f=Ut(_a,"18px","currentColor",1.5);f&&tt.appendChild(f);let g=Oe.clearChatButtonWrapper,v=Oe.closeButtonWrapper,w=g||v;w&&w.parentNode===Ae?Ae.insertBefore(tt,w):Ae.appendChild(tt),tt.addEventListener("click",()=>{zt?Zs():ap()})}let Fh=s=>{let l=n.attachments;if(!l?.enabled)return;let f=s.querySelector("[data-persona-composer-attachment-previews]")??s.querySelector(".persona-attachment-previews");if(!f){f=H("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let v=s.querySelector("[data-persona-composer-form]");v?.parentNode?v.parentNode.insertBefore(f,v):s.insertBefore(f,s.firstChild)}if(!(s.querySelector("[data-persona-composer-attachment-input]")??s.querySelector('input[type="file"]'))){let v=H("input");v.type="file",v.setAttribute("data-persona-composer-attachment-input",""),v.accept=(l.allowedTypes??mr).join(","),v.multiple=(l.maxFiles??4)>1,v.style.display="none",v.setAttribute("aria-label",l.buttonTooltipText??"Attach files"),s.appendChild(v)}},ea=!1,Uh=s=>{let l=i.find(v=>v.renderComposer);if(!l?.renderComposer)return null;let f=n.composer,g=u?R.isStreaming():!1;return l.renderComposer({config:n,defaultRenderer:s,requestRender:()=>ev(),storage:p(l.id),onSubmit:v=>{!R||R.isStreaming()||Qd(v.trim(),{consumeDraft:!1})},streaming:g,disabled:g,openAttachmentPicker:()=>{Ln()||ht?.click()},models:f?.models,selectedModelId:he.getState().selectedModelId??f?.selectedModelId,onModelChange:v=>Oh(v),onVoiceToggle:n.voiceRecognition?.enabled===!0?()=>{sp?.()}:void 0})},qh=Uh(()=>Vs({config:n}).footer);qh&&(_o.replaceComposer(qh),ke=_o.composer.footer,ea=!0);let ot=null,hA=s=>{cn=s.form,ie=s.input,wn=s.sendButton?s.sendButton.parentElement:null,s.sendButton&&(we=s.sendButton),s.micButton&&(ne=s.micButton,Fo=s.micButton.parentElement),s.found.status&&(at=s.found.status),s.found.suggestions&&(vr=s.found.suggestions),s.attachmentButton&&(St=s.attachmentButton,Mo=s.attachmentButton.parentElement),ht=s.attachmentInput??null,To=s.attachmentPreviews??null,s.found.actionsRow&&(iA=s.found.actionsRow),Yu=s.found.actionsStart,zl=s.found.actionsEnd};function ip(){let s=ie;if(!s)return;let l=n.composer?.inputAttributes,f=!l?.ariaLabel&&!(s instanceof HTMLTextAreaElement)?s.getAttribute("aria-label"):null;zc(s,l),f&&s.setAttribute("aria-label",f),jc(s,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:xl(s)}),nC(s,$c(n.composer?.maxLines,Le()?5:3))}let Vh=s=>{ot=Gx(s,{debug:n.debug===!0}),ot&&hA(ot),ip()};Fh(ke),Vh(ke),An();let mi=Gr(n,Le());mi&&(Te.style.maxWidth=mi,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",No.style.maxWidth=mi,No.style.marginLeft="auto",No.style.marginRight="auto",No.style.width="100%",Qu.style.maxWidth=mi,li.style.maxWidth=mi,li.style.marginLeft="auto",li.style.marginRight="auto",li.style.width="100%");let $h=()=>{let s=Gr(n,Le());if(!(!s||Le()))for(let l of[cn,vr,To,at])l&&(l.style.maxWidth=s,l.style.marginLeft="auto",l.style.marginRight="auto",l.style.width="100%")};$h();let jh=()=>{!n.attachments?.enabled||!ht||!To||(Ze?Ze.remountPreviews(To):(Ze=Os.fromConfig(n.attachments,Bh),Ze.setPreviewsContainer(To)),ot?.addListener(ht,"change",s=>{let l=s.target;Ze?.handleFileSelect(l.files),l.value=""}),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(Ww(n.attachments.dropOverlay)))};jh();let yA=()=>Rt?.prefetch(),zh=()=>{if(!n.contextMentions?.enabled||!ie)return;let s=ot?.header??null,l=s?ag(s):void 0;if(Rt=jC({config:n,textarea:ie,anchor:cn??ie,getMessages:()=>R.getMessages(),liveRegionHost:de,chipRow:l}),Rt&&!l){let f=ie;f.parentElement?.insertBefore(Rt.contextRow,f)}};zh();let Tn=null,bA={getState:()=>he.getState(),getValue:()=>ie?.value??"",setValue:s=>{ie&&(ie.value=s,ie.dispatchEvent(new Event("input",{bubbles:!0})),An())},submit:()=>{HC(ot?.form??null)},openAttachmentPicker:()=>{Ln()||ht?.click()},toggleVoice:()=>{sp?.()},requestRender:()=>Tn?.resolve()},vA=()=>{let s=[];return(Rt?.affordanceButtons??[]).forEach((f,g)=>{s.push({id:`core:mention-${g}`,placement:"start",order:Fn.mention+g,element:f,managed:!0})}),Mo&&s.push({id:"core:attachment",placement:"start",order:Fn.attachment,element:Mo}),Fo&&s.push({id:"core:mic",placement:"end",order:Fn.mic,element:Fo}),wn&&s.push({id:"core:send",placement:"end",order:Fn.send,element:wn}),s},Kh=()=>{Tn?.destroy(),Tn=pC({getBindings:()=>ot,collect:()=>({builtIns:vA(),configActions:[...gA(),...n.composer?.actions??[]],plugins:i,contributionContext:{config:n,getState:()=>he.getState(),requestRender:()=>Tn?.resolve()},debug:n.debug===!0}),actionContext:bA,getState:()=>he.getState(),getOverflow:()=>n.composer?.actionOverflow,reportError:(s,l)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${l.actionId}" failed:`,s)}}),Tn.resolve()};Kh();let lp=()=>{if(Kn?.destroy(),Kn=null,!Qs().length)return;let s=ot?.header;s&&(Kn=hC({row:ag(s),onRemove:l=>op(l),initialIds:he.getState().activeModeIds}),Kn.render(he.getState().activeModeIds,Qs()))};lp();let Gh=()=>{wr?.destroy(),wr=null,Ar?.destroy(),Ar=null;let s=ot?.header;s&&(wr=AC({onDismiss:()=>Mn(void 0)}),s.appendChild(wr.element),wr.render(he.getState().quote),rp()==="defer-one"&&(Ar=MC({onEdit:()=>KM(),onRemove:()=>Js(void 0)}),s.appendChild(Ar.element),Ar.render(he.getState().pendingSubmission)))};Gh();let dp=IC(),xA=()=>{let s=ot?.header?.querySelector(sg);if(s)return s.childElementCount>0;let l=he.getState();return l.mentionRefs.length>0||ou(l.activeModeIds,Qs()).length>0},Xh=()=>!1;function un(){let s=he.getState(),l=dp.observe(RC(ie),s.text);ke.toggleAttribute("data-persona-composer-compact",LC({text:s.text,wrapped:l,hasAttachments:s.attachments.length>0,hasChips:xA(),hasQuote:s.quote!==void 0,hasPendingSubmission:s.pendingSubmission!==void 0,dictationActive:Xh()}))}function Qh(){n.composer?.layout==="single-row"&&!Le()?ke.setAttribute("data-persona-composer-layout","single-row"):ke.removeAttribute("data-persona-composer-layout")}Qh(),he.subscribe(()=>{Tn?.sync(),Pp(),Cd(),un(),Py()}),Cd();let Yh=!1,CA=s=>{if(Yh||n.debug!==!0)return;let l=["messages","composer"].filter(f=>s[f]);l.length&&(Yh=!0,console.warn(`[persona] layout.slots.${l.join(" and layout.slots.")} ${l.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let s=n.layout?.slots??{};CA(s);let l=g=>{switch(g){case"body-top":return oe.querySelector("[data-persona-intro-card]");case"messages":return Te;case"footer-top":return vr;case"composer":return cn;case"footer-bottom":return at;default:return null}},f=(g,v)=>{switch(g){case"header-left":case"header-center":case"header-right":if(g==="header-left")Ae.insertBefore(v,Ae.firstChild);else if(g==="header-right")Ae.appendChild(v);else{let w=Ae.querySelector(".persona-flex-col");w?w.parentNode?.insertBefore(v,w.nextSibling):Ae.appendChild(v)}break;case"body-top":{let w=oe.querySelector("[data-persona-intro-card]");w?w.replaceWith(v):oe.insertBefore(v,oe.firstChild);break}case"body-bottom":oe.appendChild(v);break;case"footer-top":vr.replaceWith(v);break;case"footer-bottom":at.replaceWith(v);break;default:break}};for(let[g,v]of Object.entries(s))if(v)try{let w=v({config:n,defaultContent:()=>l(g)});w&&f(g,w)}catch(w){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${g}":`,w)}})();let Jh=s=>{let f=s.target.closest('button[data-expand-header="true"]');if(!f)return;let g=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let w=f.getAttribute("data-bubble-type");if(w==="reasoning")ei.has(v)?ei.delete(v):ei.add(v),XS(v,g);else if(w==="tool")ti.has(v)?ti.delete(v):ti.add(v),YS(v,g,n);else if(w==="approval"&&m){let $=((n.approval!==!1?n.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",U=m.approvalDetailsExpansionState.get(v)??$;m.approvalDetailsExpansionState.set(v,!U),m.updateApprovalDetailsUI(v,g,n)}Ot.delete(v)};Te.addEventListener("pointerdown",s=>{s.target.closest('button[data-expand-header="true"]')&&(s.preventDefault(),Jh(s))}),Te.addEventListener("keydown",s=>{let l=s.target;(s.key==="Enter"||s.key===" ")&&l.closest('button[data-expand-header="true"]')&&(s.preventDefault(),Jh(s))}),Te.addEventListener("copy",s=>{let{clipboardData:l}=s;if(!l)return;let f=Te.getRootNode(),g=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!g||g.isCollapsed)return;let v=g.toString(),w=tS(v);!w||w===v||(l.setData("text/plain",w),s.preventDefault())});let cp=new Map,Zh=null,ey="idle",SA={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},wA=(s,l)=>{let{icon:f,label:g}=SA[l];s.setAttribute("aria-label",g),s.title=g,s.setAttribute("aria-pressed",l==="idle"?"false":"true"),s.classList.toggle("persona-message-action-active",l!=="idle"),s.classList.toggle("persona-message-action-loading",l==="loading");let v=le(f,14,"currentColor",2);v&&(s.innerHTML="",s.appendChild(v))},ty=()=>{Te.querySelectorAll('[data-action="read-aloud"]').forEach(l=>{let g=l.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;wA(l,g&&g===Zh?ey:"idle")})};Te.addEventListener("click",s=>{let f=s.target.closest(".persona-message-action-btn[data-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest("[data-actions-for]");if(!g)return;let v=g.getAttribute("data-actions-for");if(!v)return;let w=f.getAttribute("data-action");if(w==="copy"){let $=R.getMessages().find(U=>U.id===v);if($&&Gs.onCopy){let U=$.content||"";navigator.clipboard.writeText(U).then(()=>{f.classList.add("persona-message-action-success");let j=Ut(Na,14,"currentColor",2);j&&(f.innerHTML="",f.appendChild(j)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let J=Ut(Fa,14,"currentColor",2);J&&(f.innerHTML="",f.appendChild(J))},2e3)}).catch(j=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",j)}),Gs.onCopy($)}}else if(w==="read-aloud")R.toggleReadAloud(v);else if(w==="upvote"||w==="downvote"){let $=(cp.get(v)??null)===w,U=w==="upvote"?"thumbs-up":"thumbs-down";if($){cp.delete(v),f.classList.remove("persona-message-action-active");let j=le(U,14,"currentColor",2);j&&(f.innerHTML="",f.appendChild(j))}else{let j=w==="upvote"?"downvote":"upvote",J=g.querySelector(`[data-action="${j}"]`);if(J){J.classList.remove("persona-message-action-active");let ft=le(j==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ft&&(J.innerHTML="",J.appendChild(ft))}cp.set(v,w),f.classList.add("persona-message-action-active");let re=le(U,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(re)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Ye=R.getMessages().find(ct=>ct.id===v);Ye&&Gs.onFeedback&&Gs.onFeedback({type:w,messageId:Ye.id,message:Ye})}}else if(w==="regenerate")Zl?.regenerate(v);else if(w==="edit")Zl?.edit(v);else if(w==="quote")Zl?.quote(v);else if(w?.startsWith(xu)){let _=w.slice(xu.length),$=n.messageActions?.custom?.find(j=>j.id===_),U=R.getMessages().find(j=>j.id===v);if(!$||!U)return;try{$.onSelect(U)}catch(j){console.error(`[AgentWidget] messageActions.custom "${_}" onSelect failed:`,j)}}});let Zl=null;Te.addEventListener("click",s=>{let f=s.target.closest("button[data-approval-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest(".persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let w=f.getAttribute("data-approval-action");if(!w)return;let _=w==="approve"?"approved":"denied",U=R.getMessages().find(J=>J.id===v);if(!U?.approval)return;let j=g.querySelector("[data-approval-buttons]");j&&j.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),U.approval.toolType==="webmcp"?R.resolveWebMcpApproval(v,_):R.resolveApproval(U.approval,_)});let $e=null,oy=!1,gi=null,os=()=>{},hi="none",ed=null,Yo={artifacts:[],selectedId:null},Gn=!1,pn=!1,yi=!1,ta=!1,ny=()=>ta||Yo.artifacts.some(s=>Dn(n.features?.artifacts,s)==="panel"),td=()=>Yo.artifacts.length>0&&!Gn&&ny(),dt={current:null},up=(s,l)=>{let f=R.getArtifactById(l),g=f?.markdown,v=f?.title||"artifact",w=f?.file,_=f?.artifactType??"markdown";if(!g){let j=s.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(j){let re=R.getMessages().find(ce=>ce.id===j);if(re?.rawContent)try{let ce=JSON.parse(re.rawContent);g=ce?.props?.markdown,v=ce?.props?.title||v,ce?.props?.file&&typeof ce.props.file=="object"&&(w=ce.props.file),!f&&typeof ce?.props?.artifactType=="string"&&(_=ce.props.artifactType)}catch{}}}return{markdown:g,title:v,file:w,artifactType:_}};Te.addEventListener("click",s=>{let f=s.target.closest("[data-download-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-download-artifact");if(!g||n.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:g})===!0)return;let{markdown:w,title:_,file:$}=up(f,g);if(!w)return;let U=hr();U&&U.triggerArtifactDownload(U.downloadInfoFor({title:_,markdown:w,file:$}))}),Te.addEventListener("click",s=>{let f=s.target.closest("[data-artifact-custom-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-artifact-custom-action");if(!g)return;let v=f.closest("[data-artifact-inline]"),w=v?null:f.closest("[data-open-artifact]"),_=v?v.getAttribute("data-artifact-inline"):w?.getAttribute("data-open-artifact")??null,U=(v?n.features?.artifacts?.inlineActions:n.features?.artifacts?.cardActions)?.find(ct=>ct.id===g);if(!U)return;let{markdown:j,title:J,file:re,artifactType:ce}=up(f,_??""),Ye={artifactId:_,title:J,artifactType:ce,markdown:j,file:re};try{Promise.resolve(U.onClick(Ye)).catch(()=>{})}catch{}}),Te.addEventListener("click",s=>{let f=s.target.closest("[data-copy-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-copy-artifact");if(!g)return;let v=R.getArtifactById(g),w=hr();if(!w)return;let _="";if(v)_=w.artifactCopyText(v);else{let{markdown:$,file:U,artifactType:j}=up(f,g);j==="markdown"&&(_=w.artifactCopyText({id:g,artifactType:"markdown",status:"complete",markdown:$??"",...U?{file:U}:{}}))}_&&navigator.clipboard.writeText(_).then(()=>{let $=Ut(Na,16,"currentColor",2);$&&(f.replaceChildren($),setTimeout(()=>{let U=Ut(Fa,16,"currentColor",2);U&&f.replaceChildren(U)},1500))}).catch(()=>{})}),Te.addEventListener("click",s=>{let f=s.target.closest("[data-expand-artifact-inline]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-expand-artifact-inline");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(Gn=!1,ta=!0,pn=!0,yi=!0,R.selectArtifact(g),fn())}),Te.addEventListener("click",s=>{let l=s.target;if(l.closest("[data-download-artifact]")||l.closest("[data-artifact-custom-action]"))return;let f=l.closest("[data-open-artifact]");if(!f)return;let g=f.getAttribute("data-open-artifact");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(s.preventDefault(),s.stopPropagation(),Gn=!1,ta=!0,R.selectArtifact(g),fn())}),Te.addEventListener("keydown",s=>{if(s.key!=="Enter"&&s.key!==" ")return;let l=s.target;!l.hasAttribute("data-open-artifact")&&!l.hasAttribute("data-expand-artifact-inline")||(s.preventDefault(),l.click())});let oa=Oe.composerOverlay,na=(s,l,f)=>{let g=l.trim();if(!g||!dt.current)return;let v=s.getAttribute("data-tool-call-id")??"",w=f.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:v,answer:g,answers:f.structured,values:f.values??(f.source==="multi"?g.split(", "):[g]),isFreeText:w,source:f.source},bubbles:!0,composed:!0})),Vr(oa,v);let _=dt.current.getMessages().find($=>$.toolCall?.id===v);_?.agentMetadata?.awaitingLocalTool?dt.current.resolveAskUserQuestion(_,f.structured??g):dt.current.sendMessage(g)},ns=s=>{let l=dt.current;if(!l)return;let f=s.getAttribute("data-tool-call-id")??"",g=l.getMessages().find(v=>v.toolCall?.id===f);g&&l.persistAskUserQuestionProgress(g,{answers:fc(s,g),currentIndex:sn(s)})},ry=s=>Object.entries(s).map(([l,f])=>`${l}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),pp=s=>{if(n.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let l=sn(s),f=Ia(s);if(l>=f-1)return;let g=dt.current?.getMessages().find(v=>v.toolCall?.id===s.getAttribute("data-tool-call-id"));g&&(mc(s,g,n,l+1),ns(s))};oa.addEventListener("click",s=>{let f=s.target.closest("[data-ask-user-action]");if(!f)return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;let v=f.getAttribute("data-ask-user-action");if(s.preventDefault(),s.stopPropagation(),v==="dismiss"){let w=g.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),Vr(oa,w);let _=dt.current?.getMessages().find($=>$.toolCall?.id===w);_?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(_),dt.current?.resolveAskUserQuestion(_,"(dismissed)"));return}if(v==="pick"){let w=f.getAttribute("data-option-label");if(!w)return;let _=g.getAttribute("data-multi-select")==="true",$=qr(g);if($&&_){let U=Ls(g)[sn(g)],j=new Set(Array.isArray(U)?U:[]);j.has(w)?j.delete(w):j.add(w),$r(g,Array.from(j)),ns(g);return}if($){$r(g,w),ns(g),pp(g);return}if(_){let U=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",U?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!U);let j=g.querySelector('[data-ask-user-action="submit-multi"]');j&&(j.disabled=Vf(g).length===0);return}na(g,w,{source:"pick",values:[w]});return}if(v==="submit-multi"){let w=Vf(g);if(w.length===0)return;na(g,w.join(", "),{source:"multi",values:w});return}if(v==="open-free-text"){let w=g.querySelector('[data-ask-free-text-row="true"]');w&&(w.classList.remove("persona-hidden"),w.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(v==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(v==="submit-free-text"){let _=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!_.trim())return;if(qr(g)){$r(g,_.trim()),ns(g),pp(g);return}na(g,_,{source:"free-text"});return}if(v==="next"||v==="back"){if(!dt.current)return;let w=g.getAttribute("data-tool-call-id")??"",_=dt.current.getMessages().find(re=>re.toolCall?.id===w);if(!_)return;let U=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(U){let re=Ls(g)[sn(g)];(typeof re!="string"||re!==U)&&$r(g,U)}let j=v==="next"?1:-1,J=sn(g)+j;mc(g,_,n,J),ns(g);return}if(v==="submit-all"){if(!dt.current)return;let w=g.getAttribute("data-tool-call-id")??"",_=dt.current.getMessages().find(re=>re.toolCall?.id===w);if(!_)return;let U=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";U&&$r(g,U);let j=fc(g,_);dt.current.persistAskUserQuestionProgress(_,{answers:j,currentIndex:sn(g)});let J=ry(j);na(g,J||"(submitted)",{source:"submit-all",structured:j});return}if(v==="skip"){if(!dt.current)return;let w=g.getAttribute("data-tool-call-id")??"",_=dt.current.getMessages().find(ce=>ce.toolCall?.id===w);if(!_)return;let $=qr(g),U=sn(g),j=Ia(g),J=U>=j-1;if(!$){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),Vr(oa,w),_.agentMetadata?.awaitingLocalTool&&(dt.current.markAskUserQuestionResolved(_),dt.current.resolveAskUserQuestion(_,"(dismissed)"));return}$r(g,"");let re=g.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),J){let ce=fc(g,_),Ye=ry(ce);na(g,Ye||"(skipped)",{source:"submit-all",structured:ce});return}mc(g,_,n,U+1),ns(g);return}}),oa.addEventListener("keydown",s=>{if(s.key!=="Enter")return;let f=s.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;s.preventDefault();let v=f.value;if(v.trim()){if(qr(g)){$r(g,v.trim()),ns(g),pp(g);return}na(g,v,{source:"free-text"})}});let sy=s=>{if(!/^[1-9]$/.test(s.key)||s.metaKey||s.ctrlKey||s.altKey)return;let l=s.target;if(l?.tagName==="INPUT"||l?.tagName==="TEXTAREA"||l?.isContentEditable)return;let f=oa.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let g=Number(s.key),w=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[g-1];w&&(s.preventDefault(),w.click())};document.addEventListener("keydown",sy);let En=null,bt=null,bi=null,od=null,nd=()=>{},ay=!1,rd="",sd="";function fp(){od?.(),od=null}let AA=()=>{let s=ha&&ws?.isConnected?ws:null,l=s?s.getBoundingClientRect().width:0;return l<=0?200:l+360},iy=()=>{if(!En||!bt)return;let s=e.classList.contains("persona-artifact-welded-split"),l=e.ownerDocument.defaultView??window,f=l.innerWidth<=640;if(!s||e.classList.contains("persona-artifact-narrow-host")||f){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let g=En.firstElementChild;if(!g||g===bt)return;let v=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${v}px`,bt.style.zIndex="5";let w=ah(En,l),_=g.offsetWidth+w/2-v/2;bt.style.left=`${Math.max(0,_)}px`},ad=()=>{},MA=()=>{let s=e.ownerDocument.defaultView??window,l=n.launcher?.mobileFullscreen??!0,f=n.launcher?.mobileBreakpoint??640;return!l||s.innerWidth>f?!1:pe||Ct(n)},id=()=>!So(n)||!td()||e.classList.contains("persona-artifact-narrow-host")||MA()||(e.ownerDocument.defaultView??window).innerWidth<lL?"none":oh(n)?"detached":"welded",fn=()=>{if(!$e||!So(n))return;Ol(e,n),Dl(e,n),ad();let s=n.features?.artifacts?.layout?.narrowHostMaxWidth??520,l=Ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",l>0&&l<=s);let f=td();$e.setVisible(f),$e.update(Yo),Gn?($e.setMobileOpen(!1),$e.element.classList.add("persona-hidden"),$e.backdrop?.classList.add("persona-hidden"),pn=!1,yi=!1):Yo.artifacts.length>0&&ny()?($e.element.classList.remove("persona-hidden"),$e.setMobileOpen(!0)):($e.setMobileOpen(!1),$e.element.classList.add("persona-hidden"),$e.backdrop?.classList.add("persona-hidden"),pn=!1,yi=!1);let g=n.features?.artifacts?.layout?.showExpandToggle===!0;if($e.setExpandToggleVisible(g),$e.setCopyButtonVisible(n.features?.artifacts?.layout?.showCopyButton===!0),$e.setRefreshButtonVisible(typeof n.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),$e.setCustomActions(n.features?.artifacts?.toolbarActions??[]),$e.setTabFade(n.features?.artifacts?.layout?.tabFade),$e.setRenderTabBar(n.features?.artifacts?.renderTabBar),!g&&!yi&&(pn=!1),pn!==ay){let w=$e.element;pn?(rd=w.style.width,sd=w.style.maxWidth,w.style.removeProperty("width"),w.style.removeProperty("max-width")):(rd&&(w.style.width=rd),sd&&(w.style.maxWidth=sd),rd="",sd=""),ay=pn}e.classList.toggle("persona-artifact-expanded",pn),$e.setExpanded(pn);let v=id();v!==hi&&(hi=v,os()),nd()};if(So(n)){Ce.style.position="relative";let s=H("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),l=H("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");s.appendChild(de),En=l,l.appendChild(s),Ce.appendChild(l);let f=v=>{oy||$e||($e=v.createArtifactPane(n,{onSelect:w=>dt.current?.selectArtifact(w),onDismiss:()=>{Gn=!0,fn()},onToggleExpand:()=>{let w=!pn,_=Yo.selectedId??Yo.artifacts[Yo.artifacts.length-1]?.id??null;n.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:_,expanded:w})!==!0&&(pn=w,w||(yi=!1),fn())}}),$e.element.classList.add("persona-hidden"),l.appendChild($e.element),$e.backdrop&&Ce.appendChild($e.backdrop),nd(),fn())},g=hr();g?f(g):(eh(()=>{let v=hr();v&&f(v)}),Iu().catch(()=>{})),nd=()=>{if(!En||!$e)return;if(!(n.features?.artifacts?.layout?.resizable===!0)){bi?.(),bi=null,fp(),bt&&(bt.remove(),bt=null),$e.element.style.removeProperty("width"),$e.element.style.removeProperty("maxWidth");return}if(!bt){let w=H("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");w.setAttribute("role","separator"),w.setAttribute("aria-orientation","vertical"),w.setAttribute("aria-label","Resize artifacts panel"),w.tabIndex=0;let _=e.ownerDocument,$=_.defaultView??window,U=j=>{if(!$e||j.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||$.innerWidth<=640)return;j.preventDefault(),fp();let J=j.clientX,re=$e.element.getBoundingClientRect().width,ce=n.features?.artifacts?.layout,Ye=ft=>{let Gt=En.getBoundingClientRect().width,_t=e.classList.contains("persona-artifact-welded-split"),Pt=ah(En,$),io=_t?0:w.getBoundingClientRect().width||6,et=re-(ft.clientX-J),lo=pw(et,Gt,Pt,io,ce?.resizableMinWidth,ce?.resizableMaxWidth,AA());$e.element.style.width=`${lo}px`,$e.element.style.maxWidth="none",iy()},ct=()=>{_.removeEventListener("pointermove",Ye),_.removeEventListener("pointerup",ct),_.removeEventListener("pointercancel",ct),od=null;try{w.releasePointerCapture(j.pointerId)}catch{}};od=ct,_.addEventListener("pointermove",Ye),_.addEventListener("pointerup",ct),_.addEventListener("pointercancel",ct);try{w.setPointerCapture(j.pointerId)}catch{}};w.addEventListener("pointerdown",U),bt=w,En.insertBefore(w,$e.element),bi=()=>{w.removeEventListener("pointerdown",U)}}if(bt){let w=td();bt.classList.toggle("persona-hidden",!w),iy()}},ad=()=>{if(!pe||!$e||(n.launcher?.sidebarMode??!1)||Ct(n)&&Do(n).reveal==="emerge")return;let w=e.ownerDocument.defaultView??window,_=n.launcher?.mobileFullscreen??!0,$=n.launcher?.mobileBreakpoint??640;if(_&&w.innerWidth<=$||!aw(n,pe))return;let U=n.launcher?.width??n.launcherWidth??Ko,j=n.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";td()?(Ce.style.width=j,Ce.style.maxWidth=j):(Ce.style.width=U,Ce.style.maxWidth=U)},typeof ResizeObserver<"u"&&(gi=new ResizeObserver(()=>{fn()}),gi.observe(Ce))}else Ce.appendChild(de);Le()&&Kt&&(Oe.peekBanner&&Kt.appendChild(Oe.peekBanner),Kt.appendChild(ke)),e.appendChild(Ge),Kt&&e.appendChild(Kt);let mp=()=>{if(Le()){Ce.style.width="100%",Ce.style.maxWidth="100%";let De=n.launcher?.composerBar??{},xe=Ge.dataset.state==="expanded",uo=De.expandedSize??"anchored";if(!(xe&&uo!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let Io=n.theme?.components?.panel,Ro=Kr(n),lt=(Ht,Ho)=>Ht==null||Ht===""?Ho:vo(Ro,Ht)??Ht,ut="1px solid var(--persona-border)",Be="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",lr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=lt(Io?.border,ut),de.style.borderRadius=lt(Io?.borderRadius,lr),de.style.boxShadow=lt(Io?.shadow,Be),de.style.overflow="hidden";return}let s=Ct(n),l=n.launcher?.sidebarMode??!1,f=s||l||(n.launcher?.fullHeight??!1),g=n.launcher?.enabled===!1,v=n.launcher?.detachedPanel===!0,w=n.theme?.components?.panel,_=Kr(n),$=(De,xe)=>De==null||De===""?xe:vo(_,De)??De,U=e.ownerDocument.defaultView??window,j=n.launcher?.mobileFullscreen??!0,J=n.launcher?.mobileBreakpoint??640,re=U.innerWidth<=J,ce=j&&re&&pe,Ye=s&&j&&re,ct=n.launcher?.position??"bottom-left",ft=ct==="bottom-left"||ct==="top-left",Gt=n.launcher?.zIndex??ro,_t="var(--persona-panel-border, 1px solid var(--persona-border))",Pt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",et=v&&!ce&&!Ye;et?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let lo=et?_t:l||ce?"none":_t,Wn=et?Pt:ce?"none":l?ft?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":g?"none":Pt;s&&!ce&&!et&&(Wn="none",lo="none");let ir=et?io:l||ce?"0":io,hn=$(w?.border,lo),zi=$(w?.shadow,Wn),ks=$(w?.borderRadius,ir),yn=id(),eo=yn==="detached",bn=yn==="welded";e.classList.toggle("persona-artifact-detached-split",eo),e.classList.toggle("persona-artifact-welded-split",bn);let Ea="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",Se=(n.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&So(n)&&oh(n)&&g&&!s;e.classList.toggle("persona-artifact-chat-flush",Se);let se=eo||Se?"none":zi,kt=eo?_t:bn?"none":hn,Nt=eo?io:ks;Se&&(kt="none",Nt="0");let to=w?.borderRadius!=null&&w.borderRadius!=="",Ft=Se&&!to?"0":ks,jt=oe.scrollTop;e.style.cssText="",Ge.style.cssText="",Ce.style.cssText="",de.style.cssText="",oe.style.cssText="",ea||(ke.style.cssText=""),zt&&(oe.style.display="none"),(f||g)&&(e.style.minWidth="0");let Lt=()=>{if(jt<=0)return;(oe.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(oe.scrollTop===jt)return;let xe=oe.scrollHeight-oe.clientHeight;xe<=0||(oe.scrollTop=Math.min(jt,xe))})};if(ce){Ge.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ge.style.cssText=`
|
|
45
45
|
position: fixed !important;
|
|
46
46
|
inset: 0 !important;
|
|
47
47
|
width: 100% !important;
|
|
@@ -77,7 +77,7 @@ _Details: ${o.message}_`:n}var sm=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
77
77
|
overflow: hidden !important;
|
|
78
78
|
border-radius: 0 !important;
|
|
79
79
|
border: none !important;
|
|
80
|
-
`,oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",ke.style.flexShrink="0",tp(),so=!0,Lt();return}let Ie=n?.launcher?.width??n?.launcherWidth??Ko;if(!l&&!s)g&&f?(Ce.style.width="100%",Ce.style.maxWidth="100%"):(Ce.style.width=Ie,Ce.style.maxWidth=Ie);else if(s)if(Do(n).reveal==="emerge"&&!v){let xe=Do(n).width;Ce.style.width=xe,Ce.style.maxWidth=xe}else Ce.style.width="100%",Ce.style.maxWidth="100%";if(ad(),Ce.style.boxShadow=se,Ce.style.borderRadius=Ft,eo?Ce.style.border="none":bn&&(Ce.style.border=hn),de.style.border=kt,de.style.borderRadius=Nt,de.style.boxShadow=eo&&!Se?Ea:"",Se&&(de.style.background="transparent",oe.style.background="transparent",ke.style.background="transparent",ke.style.borderTop="none"),bn){let De=n.features?.artifacts?.layout;ed=De?.unifiedSplitOuterRadius?.trim()||De?.paneBorderRadius?.trim()||ks}else ed=null;if(s&&!ce&&!et&&!eo&&!bn&&
|
|
80
|
+
`,oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",ke.style.flexShrink="0",tp(),so=!0,Lt();return}let Ie=n?.launcher?.width??n?.launcherWidth??Ko;if(!l&&!s)g&&f?(Ce.style.width="100%",Ce.style.maxWidth="100%"):(Ce.style.width=Ie,Ce.style.maxWidth=Ie);else if(s)if(Do(n).reveal==="emerge"&&!v){let xe=Do(n).width;Ce.style.width=xe,Ce.style.maxWidth=xe}else Ce.style.width="100%",Ce.style.maxWidth="100%";if(ad(),Ce.style.boxShadow=se,Ce.style.borderRadius=Ft,eo?Ce.style.border="none":bn&&(Ce.style.border=hn),de.style.border=kt,de.style.borderRadius=Nt,de.style.boxShadow=eo&&!Se?Ea:"",Se&&(de.style.background="transparent",oe.style.background="transparent",ke.style.background="transparent",ke.style.borderTop="none"),bn){let De=n.features?.artifacts?.layout;ed=De?.unifiedSplitOuterRadius?.trim()||De?.paneBorderRadius?.trim()||ks}else ed=null;if(s&&!ce&&!et&&!eo&&!bn&&w?.border===void 0&&(de.style.border="none",Do(n).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.style.borderRight="1px solid var(--persona-border)"),s&&!ce&&bn&&w?.border===void 0&&(Do(n).side==="right"?Ce.style.borderLeft="1px solid var(--persona-border)":Ce.style.borderRight="1px solid var(--persona-border)"),f&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",g&&(e.style.width="100%"),Ge.style.display="flex",Ge.style.flexDirection="column",Ge.style.flex="1 1 0%",Ge.style.minHeight="0",Ge.style.maxHeight="100%",Ge.style.height="100%",g&&(Ge.style.overflow="hidden"),Ce.style.display="flex",Ce.style.flexDirection="column",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.maxHeight="100%",Ce.style.height="100%",eo||(Ce.style.overflow="hidden"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.overflow="hidden",oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",ke.style.flexShrink="0"),g&&(et||eo||Se)&&!s&&(Se||(Ge.style.padding="var(--persona-panel-inset)"),Ge.style.background="var(--persona-panel-canvas-bg)"),Ge.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!l&&!g&&!s&&(Xo[ct]??Xo["bottom-right"]).split(" ").forEach(xe=>Ge.classList.add(xe)),l){let De=n.launcher?.sidebarWidth??"420px";v?Ge.style.cssText=`
|
|
81
81
|
position: fixed !important;
|
|
82
82
|
top: var(--persona-panel-inset) !important;
|
|
83
83
|
bottom: var(--persona-panel-inset) !important;
|
|
@@ -135,9 +135,9 @@ _Details: ${o.message}_`:n}var sm=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
135
135
|
border-top: none !important;
|
|
136
136
|
padding: 8px 16px 12px 16px !important;
|
|
137
137
|
${Se?"background: transparent !important;":""}
|
|
138
|
-
`)}if(!g&&!s){let De="max-height: -moz-available !important; max-height: stretch !important;",xe=l?"":"padding-top: 1.25em !important;",uo=l?"":`z-index: ${n.launcher?.zIndex??ro} !important;`;Ge.style.cssText+=De+xe+uo}tp(),Lt()},gp=()=>{e.style.setProperty("--persona-content-max-width",Gr(n,Le()))},iy=!1,ly=()=>{let s=mg(n,Le());Le()&&n.composer?.placement&&n.debug===!0&&!iy&&(iy=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let l=Cn(n);e.setAttribute("data-persona-composer-placement",s),e.setAttribute("data-persona-conversation-state",Xl),e.setAttribute("data-persona-welcome-anchor",l.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",l.composerGap??lu),Yl()},dy=()=>{if(Le())return;let s=Ct(n),l=n.launcher?.sidebarMode??!1;if(s||l||(n.launcher?.fullHeight??!1)||!pe)return;let g=e.ownerDocument.defaultView??window,v=n.launcher?.mobileFullscreen??!0,A=n.launcher?.mobileBreakpoint??640;if(v&&g.innerWidth<=A)return;let _=g.innerHeight,$=64,U=n.launcher?.heightOffset??0,j=Math.max(200,_-$),J=Math.min(640,j);Ce.style.height=`${Math.max(200,J-U)}px`};mp(),Ds(e,n),Ol(e,n),Dl(e,n),gp(),ly(),os=()=>{mp(),dy(),Ds(e,n),Ol(e,n),Dl(e,n),gp(),ly(),ed?e.style.setProperty("--persona-artifact-welded-outer-radius",ed):e.style.removeProperty("--persona-artifact-welded-outer-radius"),jn(),Gu()};let fe=[];fe.push(()=>{ty=!0}),fe.push(()=>{c.forEach(s=>s()),d.destroy()}),fe.push(()=>{document.removeEventListener("keydown",ry)}),fe.push(()=>{pi!==null&&clearTimeout(pi)});let Pn=null,kn=null;fe.push(()=>{Pn?.(),Pn=null,kn?.(),kn=null}),gi&&fe.push(()=>{gi?.disconnect(),gi=null}),fe.push(()=>{bi?.(),bi=null,fp(),bt&&(bt.remove(),bt=null),$e?.element.style.removeProperty("width"),$e?.element.style.removeProperty("maxWidth"),$e?.destroy()}),E&&fe.push(()=>{Ve=!0,Ke=null,It!==null&&(cancelAnimationFrame(It),It=null),gt?.destroy(),gt=null,We?.destroy(),We=null,Me=null});let rs=null,cy=()=>{rs&&(rs(),rs=null),n.colorScheme==="auto"&&(rs=za(()=>{Ds(e,n)}))};cy(),fe.push(()=>{rs&&(rs(),rs=null)}),fe.push(()=>{x=!0,y?.()}),fe.push(()=>{P=!0});let uy=!1;fe.push(()=>{uy=!0});let hp=(s,l)=>{let f=Pl(s,l);return f||!fS.includes(s)?f:(hS().then(g=>{if(uy)return;Ka(g.wipe),Ka(g.glyphCycle);let v=Pl(s,l);v&&Il(v,e)}).catch(()=>{}),null)},ld=n.features?.streamAnimation;if(ld?.type&&ld.type!=="none"){let s=hp(ld.type,ld.plugins);s&&Il(s,e),fe.push(()=>mS(e))}let Xn=Wl(vr),py=Wl(Qu),fy=Wl(li),ss=[Xn,py,fy];fe.push(()=>{ss.forEach(s=>s.destroy())});let as=null,I,is=null,my=!1,gy=0,hy=null,yy=s=>s.reduce((l,f)=>f.role==="user"?l+1:l,0),by=s=>{for(let l=s.length-1;l>=0;l--)if(Is(s[l]))return s[l].id??null;return null},vy=!1,wA=()=>{vy||n.debug!==!0||(vy=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},xy=!1,Cy=!1,Sy=(s,l)=>{xy||n.debug!==!0||!l.enabled||l.expose||my||Cy&&(I.isStreaming()||s.some(Is)||(xy=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},ra=s=>{if(!I)return;let l=s??I.getMessages(),f=j=>{j.render([],I,ie,l)},g=j=>{ss.forEach(J=>{J!==j&&f(J)})};is&&(yy(l)>gy||by(l)!==hy)&&(is=null);let v=jr(n);Sy(l,v);let A=v.enabled?hc(l):null,_=is??A,$=is?"host":"agent";if(_){let j=n.suggestions?.followUps,J=j?.placement??(j?"auto":"composer"),ce=(J==="auto"?Le()?"composer":"after-message":J)==="after-message"?fy:Xn;g(ce),ce.render(_,I,ie,l,n.suggestionChipsConfig,{source:$,surface:"followUp",variant:j?.variant??"chip",behavior:j?.behavior??"send",overflow:j?.overflow??"wrap",maxItems:j?.maxItems??4,config:n,plugins:i,submitPrompt:Xd});return}if(l.some(j=>j.role==="user")){ss.forEach(f);return}let U=n.suggestions?.starters;if(U){let j=Yr(Cn(n),l),J=U.placement??"auto",re=J==="auto"?j?"welcome":"composer":J;if(re==="welcome"&&!j){wA(),ss.forEach(f);return}let ce=re==="welcome"?py:Xn;g(ce),ce.render(U.items??n.suggestionChips,I,ie,l,n.suggestionChipsConfig,{surface:"starter",variant:U.variant??"card",behavior:U.behavior??"send",overflow:U.overflow??"wrap",maxItems:U.maxItems??4,config:n,plugins:i,submitPrompt:Xd});return}g(Xn),Xn.render(n.suggestionChips,I,ie,l,n.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:n,plugins:i,submitPrompt:Xd})},wy=()=>{is&&(is=null,ra())},AA=s=>{let l=Array.isArray(s)?[...s]:[];if(!l.length){wy();return}let f=I?I.getMessages():[];is=l,my=!0,gy=yy(f),hy=by(f),ra(f)},qo=!1,Ot=tS(),sa=new Map,ls=new Map,Mr=new Map,ds=null,Tr=null;function cs(){if(!ds)return;let s=ds;ds=null,Tr?.destroy(),Tr=null,Ot.delete(s),de.querySelector(`#wrapper-${s}`)?.removeAttribute("data-preserve-runtime"),I&&Jo(Te,I.getMessages(),wt)}let us=0,MA=On()!==null,Vo=aS(),$o=0,Er=null,Eo=!1,dd=!1,Pr=0,Vt=null,ps=null,yp=!1,aa=!1,fs=null,vi=!0,cd=!1,ia=null,ud=!1,ms=()=>{ud=!0,kA()},bp=null,TA=4,Qn=24,EA=80,PA=1e3,Yn=null,Ay=()=>{e.setAttribute("data-persona-scrollbar",Ju()),Ju()!=="on-scroll"&&(Yn!==null&&clearTimeout(Yn),Yn=null,oe.removeAttribute("data-persona-scrollbar-visible"))},kA=()=>{Ju()==="on-scroll"&&(oe.setAttribute("data-persona-scrollbar-visible",""),Yn!==null&&clearTimeout(Yn),Yn=setTimeout(()=>{Yn=null,_s(oe,Qn)&&oe.removeAttribute("data-persona-scrollbar-visible")},PA))};Ay(),fe.push(()=>{Yn!==null&&clearTimeout(Yn)});let vp=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Gh=()=>je.active,un();let My=n.voiceRecognition?.autoResume??!1,Jn=s=>{C.emit("voice:state",{active:je.active,source:s,timestamp:Date.now()})},mn=()=>{ae(s=>({...s,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},LA=()=>{if(n.voiceRecognition?.enabled===!1)return;let s=ph(V.voiceState),l=!!s.active,f=Number(s.timestamp??0);je.manuallyDeactivated=!!s.manuallyDeactivated,l&&Date.now()-f<tL&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,Wo(n.voiceRecognition?.provider)?I.toggleVoice().then(()=>{je.active=I.isVoiceActive(),Jn("restore"),I.isVoiceActive()&&Ma()}):Jd("restore"))},1e3)},IA=()=>I?kw(I.getMessages()).filter(s=>!s.__skipPersist):[],pd=null,Ty=(s,l)=>{typeof console<"u"&&console.error(s,l)},fd=(s,l)=>{let f=()=>{try{let _=s();return!_||typeof _.then!="function"?null:Promise.resolve(_).catch($=>{Ty(l,$)})}catch(_){return Ty(l,_),null}},g=pd,v=g?g.then(()=>f()??void 0):f();if(!v)return;let A=v.finally(()=>{pd===A&&(pd=null)});pd=A};function la(s){if(!N?.save)return;let l=s?kw(s):I?IA():[],f=X&&I?.getResumableHandle();f&&(V={...V,durableResume:{executionId:f.executionId,after:f.lastEventId}});let g={messages:l,metadata:V,artifacts:Yo.artifacts,selectedArtifactId:Yo.selectedId,...gs?{draft:gs}:{}};fd(()=>N.save(g),"[AgentWidget] Failed to persist state:")}let gs,md=()=>!N?.save||n.persistState===!1?!1:typeof n.persistState=="object"?n.persistState.persist?.draft!==!1:!0,xi=TC({write:()=>{if(!md())return;let s=he.getState(),l=AC({text:s.text,mentionRefs:s.mentionRefs,contentSegments:hf(),selectedModelId:s.selectedModelId,activeModeIds:s.activeModeIds,quote:s.quote});JSON.stringify(l)!==JSON.stringify(gs)&&(gs=l,la())}});function Ey(){md()&&xi.schedule()}function xp(){xi.flush()}function Py(s){if(!md())return;let l=MC(s,{mentionSourceIds:(n.contextMentions?.sources??[]).map(f=>f.id),modelIds:(n.composer?.models??[]).map(f=>f.id),modes:n.composer?.modes??[]});l&&(gs=s,ie&&!ie.value&&(ie.value=l.text,ie.dispatchEvent(new Event("input",{bubbles:!0})),An()),l.selectedModelId&&(he.setSelectedModelId(l.selectedModelId),Sr?.repaint()),Jl(l.activeModeIds??[]),l.quote&&Mn(l.quote),xi.cancel())}function gd(){xi.cancel(),gs&&(gs=void 0,md()&&la())}let da=null,ky=()=>Ge.querySelector("#persona-scroll-container")||oe,ca=()=>{da!==null&&(cancelAnimationFrame(da),da=null),Eo=!1},Ly=()=>{Er!==null&&(cancelAnimationFrame(Er),Er=null),dd=!1,ca()},RA=()=>qo&&Sp()&&(Uo()!=="anchor-top"||Ih()),Cp=()=>{let s=di()||"Jump to latest",l=RA();Bt.toggleAttribute("data-persona-scroll-to-bottom-streaming",l),Pr>0?(Zr.textContent=String(Pr),Zr.style.display="",Bt.setAttribute("aria-label",`${s} (${Pr} new)`)):(Zr.textContent="",Zr.style.display="none",Bt.setAttribute("aria-label",l?`${s} (response streaming below)`:s))},Iy=()=>{Pr!==0&&(Pr=0,Cp())},HA=()=>{let s=Vt?.spacerHeight??0;return s<=0?_s(oe,Qn):vd(s)-oe.scrollTop-oe.clientHeight<=Qn},Sp=()=>Cr()?!Vo.isFollowing():!HA(),wp=()=>!!I&&I.getMessages().length>0,$t=()=>{if(!iA()||Zw()){Bt.parentNode&&Bt.remove(),Bt.style.display="none";return}Bt.parentNode!==de&&de.appendChild(Bt),es();let l=Un(oe)>0&&Sp()&&wp();l?Cp():Iy(),Bt.style.display=l?"":"none"},Ci=()=>{Vo.pause()&&(Ly(),$t())},Po=()=>{Vo.resume(),Iy(),$t()},kr=(s=!1)=>{Cr()&&wp()&&Vo.isFollowing()&&(!s&&!qo||(Er!==null&&(cancelAnimationFrame(Er),Er=null),dd=!0,Er=requestAnimationFrame(()=>{Er=null,dd=!1,Vo.isFollowing()&&WA(ky(),s?220:140)})))},Ry=(s,l,f,g=()=>!0)=>{let v=s.scrollTop,A=l(),_=A-v;if(ca(),Math.abs(_)<1){Eo=!0,s.scrollTop=A,$o=s.scrollTop,Eo=!1;return}let $=performance.now();Eo=!0;let U=J=>1-Math.pow(1-J,3),j=J=>{if(!g()){ca();return}let re=l();re!==A&&(A=re,_=A-v);let ce=J-$,Ye=Math.min(ce/f,1),ct=U(Ye),ft=v+_*ct;s.scrollTop=ft,$o=s.scrollTop,Ye<1?da=requestAnimationFrame(j):(s.scrollTop=A,$o=s.scrollTop,da=null,Eo=!1)};da=requestAnimationFrame(j)},WA=(s,l=500)=>{let f=Un(s)-s.scrollTop;if(Math.abs(f)<1){$o=s.scrollTop;return}if(Math.abs(f)>=EA){ca(),Eo=!0,s.scrollTop=Un(s),$o=s.scrollTop,Eo=!1;return}Ry(s,()=>Un(s),l,()=>Vo.isFollowing())},hd=()=>{if(!wp()){$t();return}let s=ky();Eo=!0,s.scrollTop=Un(s),$o=s.scrollTop,Eo=!1,$t()},hs=s=>{let l=0,f=s;for(;f&&f!==oe;)l+=f.offsetTop,f=f.offsetParent;return l},BA=()=>{let s=oe.getRootNode();return(typeof s.getSelection=="function"?s.getSelection():null)??oe.ownerDocument.getSelection()},yd=()=>dS(BA(),oe),Ap=()=>{if(lA()!=="last-user-turn")return!1;let s=I?.getMessages()??[];if(s.length<2)return!1;let l=[...s].reverse().find(A=>A.role==="user");if(!l)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l.id):l.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),g=oe.querySelector(`[data-message-id="${f}"]`);if(!g)return!1;let v=Math.min(Math.max(0,hs(g)-ci()),Un(oe));return Eo=!0,oe.scrollTop=v,$o=oe.scrollTop,Eo=!1,Uo()==="follow"&&!_s(oe,Qn)&&Vo.pause(),$t(),!0},bd=s=>{let l=Math.max(0,Math.round(s));Qo.style.height=`${l}px`,Qo.style.display=l>0?"":"none",Vt&&(Vt.spacerHeight=Math.max(0,s))},vd=s=>{let l=parseFloat(getComputedStyle(oe).paddingBottom)||0,f=0;for(let v of Array.from(oe.children)){if(v===Qo||v.offsetHeight===0)continue;let A=hs(v)+v.offsetHeight;A>f&&(f=A)}let g=oe.scrollHeight-s;return f>0?Math.min(f+l,g):g},OA=()=>{if(!Vt||Vt.spacerHeight<=0)return;let s=vd(Vt.spacerHeight),l=Math.max(0,Math.round(oe.scrollTop)+oe.clientHeight-s+Qn);l<Vt.spacerHeight&&(bd(l),$t())},gn=()=>{ps!==null&&(cancelAnimationFrame(ps),ps=null),ca(),Vt=null,Qo.style.height="0px",Qo.style.display="none"},Hy=s=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Mp=s=>oe.querySelector(`[data-message-id="${Hy(s)}"]`),Wy=s=>{ps!==null&&cancelAnimationFrame(ps),ps=requestAnimationFrame(()=>{ps=null;let l=Hy(s),f=oe.querySelector(`[data-message-id="${l}"]`);if(!f)return;let g=hs(f),v=Vt?.spacerHeight??0,A=vd(v),{targetScrollTop:_,spacerHeight:$}=yg({anchorOffsetTop:g,topOffset:ci(),viewportHeight:oe.clientHeight,contentHeight:A,slack:Qn});Vt={initialSpacerHeight:$,contentHeightAtAnchor:A,spacerHeight:$},bd($),Ry(oe,()=>f.isConnected?Math.max(0,hs(f)-ci()):_,220)})},ko=()=>{if(Uo()!=="anchor-top"||!Vt||!ia)return;let s=Mp(ia);if(!s)return;ca();let l=Vt.spacerHeight,f=vd(l),{targetScrollTop:g,spacerHeight:v}=yg({anchorOffsetTop:hs(s),topOffset:ci(),viewportHeight:oe.clientHeight,contentHeight:f,slack:Qn});Vt={initialSpacerHeight:v,contentHeightAtAnchor:f,spacerHeight:v},bd(v),Eo=!0,oe.scrollTop=g,$o=oe.scrollTop,Eo=!1,$t()},DA=()=>{if(Cr()){if(!Vo.isFollowing()||_s(oe,1))return;kr(!qo);return}if(Vt&&Vt.initialSpacerHeight>0){let s=oe.scrollHeight-Vt.spacerHeight,l=cS({initialSpacerHeight:Vt.initialSpacerHeight,contentHeightAtAnchor:Vt.contentHeightAtAnchor,currentContentHeight:s});l!==Vt.spacerHeight&&bd(l)}$t()},_A=s=>{let l=Uo();l==="follow"?(Po(),kr(!0)):l==="anchor-top"&&(vi=!1,cd=!0,ud=!1,ia=s,Wy(s))},NA=()=>{if(Uo()==="anchor-top"){if(cd){vi=!1;return}vi=!0,gn(),Po(),kr(!0)}},FA=96,UA=s=>{if(fs===null)return!0;let l=Mp(fs),f=Mp(s);if(!l||!f)return!0;let g=hs(f)-hs(l);return ci()+g>oe.clientHeight-FA},qA=s=>{if(Uo()!=="anchor-top"||!cd||ud||yd())return;let l=fs===null;for(let f of s){if(!l){f.id===fs&&(l=!0);continue}if(sS(f)){if(f.id===ia||!UA(f.id))return;ia=f.id,Wy(f.id);return}}},VA=s=>{let l=new Map;s.forEach(f=>{let g=vp.get(f.id);l.set(f.id,{streaming:f.streaming,role:f.role}),!g&&f.role==="assistant"&&(C.emit("assistant:message",f),!aa&&(Uo()!=="anchor-top"||Ih())&&Sp()&&(Pr+=1,Cp(),$t(),Gl(Pr===1?"1 new message below.":`${Pr} new messages below.`))),f.role==="assistant"&&g?.streaming&&f.streaming===!1&&C.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(g?f.approval.status!=="pending"&&C.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):C.emit("approval:requested",{approval:f.approval,message:f}))}),vp.clear(),l.forEach((f,g)=>{vp.set(g,f)})},Si=(s,l)=>{let f=l==="user"?"user":"assistant",g=n.layout?.messages?.[f],v=g?.width??"content",A=g?.maxWidth??(v==="full"?"100%":void 0);s.classList.add("persona-message-row"),s.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),s.classList.add(`persona-message-row-${l}`,`persona-message-width-${v}`),s.classList.toggle("persona-justify-end",l==="user"),s.setAttribute("data-message-role",l),s.setAttribute("data-message-width",v),A?s.style.setProperty("--persona-message-row-max-width",A):s.style.removeProperty("--persona-message-row-max-width")},Zn=(s,l)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${s}`,f.setAttribute("data-wrapper-id",s),Si(f,l),f},$A=(s,l,f)=>{let g=document.createElement("div"),A=(()=>{let B=i.find(Fe=>Fe.renderLoadingIndicator);if(B?.renderLoadingIndicator)return B.renderLoadingIndicator;if(n.loadingIndicator?.render)return n.loadingIndicator.render})(),_=(B,Fe)=>Fe==null?!1:typeof Fe=="string"?(B.textContent=Fe,!0):(B.appendChild(Fe),!0),$=new Set,U=new Map,j=new Set,J=i.some(B=>B.renderAskUserQuestion),re=[],ce=[],Ye=n.enableComponentStreaming!==!1,ct=n.approval!==!1,ft=[],Gt=n.messageActions,_t=Gt?.showRegenerate===!0&&Gt.enabled!==!1&&dt.current?.isStreaming()!==!0?kx(l):null,Pt=Gt?.showEdit===!0&&Gt.enabled!==!1,io=Gt?.showQuote===!0&&Gt.enabled!==!1,et=null,lo=n.features?.reasoningDisplay?.completedVisibility,Wn=B=>lo==="removed"?!0:lo==="removed-when-short"?ox(B,n.features?.reasoningDisplay?.shortThinkThreshold):!1,ir=n.features?.toolCallDisplay?.completedVisibility==="removed",hn=B=>B.variant==="reasoning"&&B.reasoning?.status==="complete"?Wn(B.reasoning):ir&&B.variant==="tool"&&B.toolCall?.status==="complete";if(l.forEach(B=>{if(hn(B))return;if($.add(B.id),U.set(B.id,B.role),ds===B.id&&Tr){let xe=Zn(B.id,B.role);xe.setAttribute("data-persona-message-edit-stub","true"),xe.setAttribute("data-preserve-runtime","true"),g.appendChild(xe),et={messageId:B.id,element:Tr.element};return}let Fe=J&&cr(B),Se=ct&&B.variant==="approval"&&!!B.approval,se=!Fe&&B.role==="assistant"&&!B.variant&&Ye&&ql(B);!Se&&Mr.has(B.id)&&(s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),Mr.delete(B.id)),!se&&ls.has(B.id)&&(s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),ls.delete(B.id));let kt=cr(B)?`:${B.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${B.agentMetadata?.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Nt={canRegenerate:_t===B.id,canEdit:Pt&&Zf(B),canQuote:io&&!B.variant&&(B.content?.trim().length??0)>0},to=`${Nt.canRegenerate?"r":""}${Nt.canEdit?"e":""}${Nt.canQuote?"q":""}`,Ft=eS(B,us)+kt+`:${to}`,jt=Fe||Se||se?null:oS(Ot,B.id,Ft);if(jt){g.appendChild(jt.cloneNode(!0)),cr(B)&&B.toolCall?.id&&B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(j.add(B.toolCall.id),Ra(B,n,Oe.composerOverlay));return}let Lt=null,co=i.find(xe=>!!(B.variant==="reasoning"&&xe.renderReasoning||B.variant==="tool"&&xe.renderToolCall||!B.variant&&xe.renderMessage)),Ie=n.layout?.messages;if(cr(B)&&B.agentMetadata?.askUserQuestionAnswered===!0){sa.delete(B.id),s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime");return}if(Is(B)&&jr(n).enabled)return;if(cr(B)&&n.features?.askUserQuestion?.enabled!==!1){let xe=i.find(uo=>typeof uo.renderAskUserQuestion=="function");if(xe&&dt.current){let uo=sa.get(B.id),Or=uo!==Ft,Io=null;if(Or){let{payload:ut,complete:Be}=ur(B),lr=B.id,Ht=()=>dt.current?.getMessages().find(Ho=>Ho.id===lr);Io=xe.renderAskUserQuestion({message:B,payload:ut,complete:Be,resolve:Ho=>{let Ki=Ht();Ki&&dt.current?.resolveAskUserQuestion(Ki,Ho)},dismiss:()=>{let Ho=Ht();Ho?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(Ho),dt.current?.resolveAskUserQuestion(Ho,"(dismissed)"))},config:n})}let Ro=uo!=null;if(Or&&Io===null&&!Ro){B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(j.add(B.toolCall.id),Ra(B,n,Oe.composerOverlay));return}let lt=Zn(B.id,B.role);lt.setAttribute("data-ask-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),g.appendChild(lt),re.push({messageId:B.id,fingerprint:Ft,bubble:Io});return}else{B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(j.add(B.toolCall.id),Ra(B,n,Oe.composerOverlay));return}}else if(Se){let xe=k();if(!xe){g.appendChild(Zn(B.id,B.role));return}let uo=i.find(lt=>typeof lt.renderApproval=="function")??h,Io=Mr.get(B.id)!==Ft,Ro=null;if(Io&&uo?.renderApproval){let lt=B.id,ut=(Be,lr)=>{let Ht=dt.current?.getMessages().find(Ho=>Ho.id===lt);Ht?.approval&&(Ht.approval.toolType==="webmcp"?dt.current?.resolveWebMcpApproval(Ht.id,Be):dt.current?.resolveApproval(Ht.approval,Be,lr))};Ro=uo.renderApproval({message:B,defaultRenderer:()=>xe.createApprovalBubble(B,n),config:n,approve:Be=>ut("approved",Be),deny:Be=>ut("denied",Be)})}if(Io&&Ro===null)s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),Mr.delete(B.id),Lt=xe.createApprovalBubble(B,n);else{let lt=Zn(B.id,B.role);lt.setAttribute("data-approval-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),g.appendChild(lt),ft.push({messageId:B.id,fingerprint:Ft,bubble:Ro});return}}else if(co)if(B.variant==="reasoning"&&B.reasoning&&co.renderReasoning){if(!$n)return;Lt=co.renderReasoning({message:B,defaultRenderer:()=>Kg(B,n),config:n})}else if(B.variant==="tool"&&B.toolCall&&co.renderToolCall){if(!z)return;Lt=co.renderToolCall({message:B,defaultRenderer:()=>Xg(B,n),config:n})}else co.renderMessage&&(Lt=co.renderMessage({message:B,defaultRenderer:()=>{let xe=Ya(B,f,Ie,n.messageActions,Gs,{loadingIndicatorRenderer:A,widgetConfig:n,actionEligibility:Nt});return B.role!=="user"&&w(xe,B,n,I),xe},config:n}));if(!Lt&&se){let xe=Nu(B);if(xe){let uo=ls.get(B.id),Or=uo!==Ft,Io=n.wrapComponentDirectiveInBubble!==!1&&Sn.getOptions(xe.component)?.bubbleChrome!==!1,Ro=null;if(Or){let lt=_u(xe,{config:n,message:B,transform:f});if(lt&&xe.component==="PersonaArtifactInline"){let ut=lt.hasAttribute("data-artifact-inline")?lt:lt.querySelector("[data-artifact-inline]"),Be=ut?.getAttribute("data-artifact-inline")??"",lr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Be):Be,Ht=Be?s.querySelector(`#wrapper-${B.id}`)?.querySelector(`[data-artifact-inline="${lr}"]`)??null:null;ut&&Ht&&Ht!==ut&&hr()?.hasLiveInlineArtifactBlock(Ht)&&(ut===lt?lt=Ht:ut.replaceWith(Ht))}if(lt)if(Io){let ut=document.createElement("div");if(ut.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ut.id=`bubble-${B.id}`,ut.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let Be=document.createElement("div");Be.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Be.innerHTML=f({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),ut.appendChild(Be)}ut.appendChild(lt),Ro=ut}else{let ut=document.createElement("div");if(ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ut.id=`bubble-${B.id}`,ut.setAttribute("data-message-id",B.id),ut.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let Be=document.createElement("div");Be.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Be.innerHTML=f({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),ut.appendChild(Be)}ut.appendChild(lt),Ro=ut}}if(Ro||uo!=null){let lt=Zn(B.id,B.role);lt.setAttribute("data-component-directive-stub","true"),lt.setAttribute("data-preserve-runtime","true"),g.appendChild(lt),ce.push({messageId:B.id,fingerprint:Ft,bubble:Ro});return}}}if(!Lt)if(B.variant==="reasoning"&&B.reasoning){if(!$n)return;Lt=Kg(B,n)}else if(B.variant==="tool"&&B.toolCall){if(!z)return;Lt=Xg(B,n)}else if(B.variant==="approval"&&B.approval){if(n.approval===!1)return;let xe=k();if(!xe)return;Lt=xe.createApprovalBubble(B,n)}else{let xe=n.layout?.messages;xe?.renderUserMessage&&B.role==="user"?Lt=xe.renderUserMessage({message:B,config:n,streaming:!!B.streaming}):xe?.renderAssistantMessage&&B.role==="assistant"?Lt=xe.renderAssistantMessage({message:B,config:n,streaming:!!B.streaming}):Lt=Ya(B,f,xe,n.messageActions,Gs,{loadingIndicatorRenderer:A,widgetConfig:n,actionEligibility:Nt}),B.role!=="user"&&Lt&&w(Lt,B,n,I)}let De=Zn(B.id,B.role);De.appendChild(Lt),nS(Ot,B.id,Ft,De),g.appendChild(De)}),Oe.composerOverlay&&Oe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let Se=Fe.getAttribute("data-persona-ask-sheet-for");Se&&!j.has(Se)&&Vr(Oe.composerOverlay,Se)}),n.features?.toolCallDisplay?.grouped){let B=[],Fe=[],Se=n.features.toolCallDisplay.groupedMode==="summary";l.forEach(se=>{if(se.variant==="tool"&&se.toolCall&&z){if(ir&&se.toolCall.status==="complete")return;Fe.push(se);return}se.variant==="reasoning"&&(!$n||se.reasoning?.status==="complete"&&Wn(se.reasoning))||((Fe.length>1||Se&&Fe.length>0)&&B.push(Fe),Fe=[])}),(Fe.length>1||Se&&Fe.length>0)&&B.push(Fe),B.forEach(se=>{let kt=se.map(Ie=>Array.from(g.children).find(De=>De instanceof HTMLElement&&De.getAttribute("data-wrapper-id")===Ie.id)).filter(Ie=>!!Ie);if(kt.length<(Se?1:2))return;let Nt=Zn(`tool-group-${se[0].id}`,"assistant");Nt.setAttribute("data-persona-tool-group-row","true");let to=document.createElement("div");to.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",to.setAttribute("data-persona-tool-group","true");let Ft=document.createElement("div");Ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",Ft.id=`tool-group-summary-${se[0].id}`;let jt=`Called ${se.length} ${se.length===1?"tool":"tools"}`,Lt=n.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(Ie=>Ie.toolCall).filter(Ie=>!!Ie),defaultSummary:jt,config:n});_(Ft,Lt)||(Ft.textContent=jt);let co=document.createElement("div");co.className="persona-tool-group-stack persona-flex persona-flex-col",co.id=`tool-group-stack-${se[0].id}`,co.setAttribute("data-persona-tool-group-stack","true"),to.appendChild(Ft),Se||to.appendChild(co),Nt.appendChild(to),kt[0].before(Nt),kt.forEach((Ie,De)=>{if(Se){Ie.remove();return}Ie.style.setProperty("--persona-message-row-max-width","100%");let xe=document.createElement("div");xe.className="persona-tool-group-item persona-relative",xe.setAttribute("data-persona-tool-group-item","true"),De<kt.length-1&&xe.setAttribute("data-persona-tool-group-connector","true"),xe.appendChild(Ie),co.appendChild(xe)})})}rS(Ot,$);let zi=B=>B.variant==="tool"&&!z||B.variant==="reasoning"&&!$n||hn(B),ks=l.some(B=>B.role==="assistant"&&B.streaming&&!zi(B)),yn=l.length-1;for(;yn>=0&&zi(l[yn]);)yn--;let eo=yn>=0?l[yn]:void 0,bn=yn<l.length-1,Ea=eo?.role==="assistant"&&!eo.streaming&&eo.variant!=="approval"&&!bn;if(qo&&l.some(B=>B.role==="user")&&!ks&&!Ea){let B={config:n,streaming:!0,location:"standalone",defaultRenderer:$s},Fe=i.find(se=>se.renderLoadingIndicator),Se=null;if(Fe?.renderLoadingIndicator&&(Se=Fe.renderLoadingIndicator(B)),Se===null&&n.loadingIndicator?.render&&(Se=n.loadingIndicator.render(B)),Se===null&&(Se=$s()),Se){let se=document.createElement("div"),kt=n.loadingIndicator?.showBubble!==!1,Nt=n.layout?.messages?.layout??"bubble";se.className=kt?Bl("assistant",Nt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),se.setAttribute("data-typing-indicator","true"),kt&&(se.style.color="var(--persona-message-assistant-text, var(--persona-text))",Nt!=="flat"&&(se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),se.appendChild(Se);let to=Zn("typing-indicator","assistant");to.appendChild(se),g.appendChild(to)}}if(!qo&&l.length>0){let B=l[l.length-1],Fe={config:n,lastMessage:B,messageCount:l.length},Se=i.find(kt=>kt.renderIdleIndicator),se=null;if(Se?.renderIdleIndicator&&(se=Se.renderIdleIndicator(Fe)),se===null&&n.loadingIndicator?.renderIdle&&(se=n.loadingIndicator.renderIdle(Fe)),se){let kt=document.createElement("div"),Nt=n.loadingIndicator?.showBubble!==!1;kt.className=Nt?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),kt.setAttribute("data-idle-indicator","true"),kt.appendChild(se);let to=Zn("idle-indicator","assistant");to.appendChild(kt),g.appendChild(to)}}if(Ev(g),pu(s,g),Hf(s),et){let{messageId:B,element:Fe}=et,Se=s.querySelector(`#wrapper-${B}`);Se&&Fe.parentElement!==Se&&(Si(Se,U.get(B)??"user"),Se.replaceChildren(Fe))}if(re.length>0)for(let{messageId:B,fingerprint:Fe,bubble:Se}of re){let se=s.querySelector(`#wrapper-${B}`);se&&(Si(se,U.get(B)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Fe),sa.set(B,Fe)))}if(sa.size>0)for(let B of sa.keys())$.has(B)||sa.delete(B);if(ce.length>0)for(let{messageId:B,fingerprint:Fe,bubble:Se}of ce){let se=s.querySelector(`#wrapper-${B}`);se&&(Si(se,U.get(B)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Fe),ls.set(B,Fe)))}if(ls.size>0)for(let B of ls.keys())$.has(B)||ls.delete(B);if(ft.length>0)for(let{messageId:B,fingerprint:Fe,bubble:Se}of ft){let se=s.querySelector(`#wrapper-${B}`);se&&(Si(se,U.get(B)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Fe),Mr.set(B,Fe)))}if(Mr.size>0)for(let B of Mr.keys())$.has(B)||Mr.delete(B)},Tp=!1,xd=()=>{Tp||(Tp=!0,ac().catch(()=>{Tp=!1}))},Jo=(s,l,f)=>{l.length>0&&xd(),$A(s,l,f),ey()},wi=null,jA=()=>{if(wi)return;let s=f=>{let g=f.composedPath();g.includes(Ge)||Kt&&g.includes(Kt)||pt(!1,"user")};wi=s,(e.ownerDocument??document).addEventListener("pointerdown",s,!0)},By=()=>{if(!wi)return;(e.ownerDocument??document).removeEventListener("pointerdown",wi,!0),wi=null};fe.push(()=>By());let Ai=null,zA=()=>{if(Ai)return;let s=f=>{f.key==="Escape"&&(f.isComposing||pt(!1,"user"))};Ai=s,(e.ownerDocument??document).addEventListener("keydown",s,!0)},Oy=()=>{if(!Ai)return;(e.ownerDocument??document).removeEventListener("keydown",Ai,!0),Ai=null};fe.push(()=>Oy());let Mi=!1,Dy=new Set,KA=()=>{let s=n.launcher?.composerBar?.peek?.streamAnimation;return s||n.features?.streamAnimation},ua=()=>{if(!Le())return;let s=Oe.peekBanner,l=Oe.peekTextNode;if(!s||!l)return;if(ve){s.classList.remove("persona-pill-peek--visible");return}let f=I?.getMessages()??[],g;for(let _t=f.length-1;_t>=0;_t--){let Pt=f[_t];if(Pt.role==="assistant"&&Pt.content){g=Pt;break}}if(!g){s.classList.remove("persona-pill-peek--visible");return}let v=g.content,A=!!g.streaming,_=KA(),$=fu(_),U=$.type!=="none"?hp($.type,_?.plugins):null,j=U?.isAnimating?.(g)===!0,J=U!==null&&(A||j);J&&U&&!Dy.has(U.name)&&(Il(U,e),Dy.add(U.name));let re=J&&U?.containerClass?U.containerClass:null,ce=l.dataset.personaPeekStreamClass??null;ce&&ce!==re&&(l.classList.remove(ce),delete l.dataset.personaPeekStreamClass),re&&ce!==re&&(l.classList.add(re),l.dataset.personaPeekStreamClass=re),J?(l.style.setProperty("--persona-stream-step",`${$.speed}ms`),l.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(l.style.removeProperty("--persona-stream-step"),l.style.removeProperty("--persona-stream-duration"));let Ye=J?mu(v,$.buffer,U,g,A):v;if(J&&$.placeholder==="skeleton"&&A&&(!Ye||!Ye.trim())){let _t=document.createElement("div"),Pt=Ll();Pt.classList.add("persona-pill-peek__skeleton"),_t.appendChild(Pt),pu(l,_t)}else{let _t=Math.max(0,Ye.length-100),Pt=Ye.length>100?Ye.slice(-100):Ye,io=dr(Pt);if(!J||!U){let et=Ye.length>100?`\u2026${Pt}`:Pt;l.textContent!==et&&(l.textContent=et)}else{let et=io;(U.wrap==="char"||U.wrap==="word")&&(et=kl(io,U.wrap,`peek-${g.id}`,{skipTags:U.skipTags,startIndex:_t}));let lo=document.createElement("div");if(lo.innerHTML=et,U.useCaret&&Pt.length>0){let Wn=gu(),ir=lo.querySelectorAll(".persona-stream-char, .persona-stream-word"),hn=ir[ir.length-1];hn?.parentNode?hn.parentNode.insertBefore(Wn,hn.nextSibling):lo.appendChild(Wn)}pu(l,lo),U.onAfterRender?.({container:l,bubble:s,messageId:g.id,message:g,speed:$.speed,duration:$.duration})}}let Gt=qo||Mi;s.classList.toggle("persona-pill-peek--visible",Gt)};if(Le()){let s=Oe.peekBanner;if(s){let g=v=>{v.preventDefault(),v.stopPropagation(),pt(!0,"user")};s.addEventListener("pointerdown",g),fe.push(()=>{s.removeEventListener("pointerdown",g)})}let l=()=>{Mi||(Mi=!0,ua())},f=()=>{Mi&&(Mi=!1,ua())};Ce.addEventListener("pointerenter",l),Ce.addEventListener("pointerleave",f),fe.push(()=>{Ce.removeEventListener("pointerenter",l),Ce.removeEventListener("pointerleave",f)}),Kt&&(Kt.addEventListener("pointerenter",l),Kt.addEventListener("pointerleave",f),fe.push(()=>{Kt.removeEventListener("pointerenter",l),Kt.removeEventListener("pointerleave",f)}))}let GA=s=>{let l=n.launcher?.composerBar??{},f=l.expandedSize??"anchored",g=l.bottomOffset??"16px",v=l.collapsedMaxWidth,A=l.expandedMaxWidth??"880px",_=l.expandedTopOffset??"5vh",$=l.modalMaxWidth??"880px",U=l.modalMaxHeight??"min(90vh, 800px)",j="calc(100vw - 32px)",J="var(--persona-pill-area-height, 80px)",re=Ge.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",Kt){let ce=Kt.style;ce.bottom=g,ce.width=v??""}if(s&&f!=="fullscreen"){if(f==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=$,re.maxWidth=j,re.maxHeight=U,re.height=U;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${g} + ${J})`,re.top=_,re.width=A,re.maxWidth=j}},Ti=()=>{if(ve&&xd(),!qe())return;if(Le()){let j=(n.launcher?.composerBar??{}).expandedSize??"anchored",J=ve?"expanded":"collapsed";Ge.dataset.state=J,Ge.dataset.expandedSize=j,Kt&&(Kt.dataset.state=J,Kt.dataset.expandedSize=j),Ge.style.removeProperty("display"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),GA(ve),de.style.display=ve?"flex":"none",os(),ve?(jA(),zA()):(By(),Oy()),ua();return}let s=Ct(n),l=e.ownerDocument.defaultView??window,f=n.launcher?.mobileBreakpoint??640,g=n.launcher?.mobileFullscreen??!0,v=l.innerWidth<=f,A=g&&v&&pe,_=Do(n).reveal;ve?(Ge.style.removeProperty("display"),Ge.style.display=s?"flex":"",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0"),Ce.classList.add("persona-scale-100","persona-opacity-100"),Tt?(Tt.setPanelOpen(!0),Tt.element.style.display="none"):mo&&(mo.style.display="none")):(s?s&&(_==="overlay"||_==="push")&&!A?(Ge.style.removeProperty("display"),Ge.style.display="flex",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.setProperty("display","none","important"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.display="",Ge.classList.add("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100"),Ce.classList.add("persona-scale-95","persona-opacity-0")),Tt?(Tt.setPanelOpen(!1),Tt.element.style.display=s?"none":""):mo&&(mo.style.display=s?"none":""))},pt=(s,l="user")=>{if(!qe()||ve===s)return;let f=ve;ve=s,Ti();let g=(()=>{let A=n.launcher?.sidebarMode??!1,_=e.ownerDocument.defaultView??window,$=n.launcher?.mobileFullscreen??!0,U=n.launcher?.mobileBreakpoint??640,j=_.innerWidth<=U,J=Ct(n)&&$&&j,re=Le()&&(n.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return A||$&&j&&pe||J||re})();if(ve&&g){if(!Pn){let A=e.getRootNode(),_=A instanceof ShadowRoot?A.host:e.closest(".persona-host");_&&(Pn=Sg(_,n.launcher?.zIndex??ro))}kn||(kn=wg(e.ownerDocument))}else ve||(Pn?.(),Pn=null,kn?.(),kn=null);ve&&(Vi(),Ap()||(Uo()==="follow"?kr(!0):hd()));let v={open:ve,source:l,timestamp:Date.now()};ve&&!f?C.emit("widget:opened",v):!ve&&f&&C.emit("widget:closed",v),C.emit("widget:state",{open:ve,launcherEnabled:pe,voiceActive:je.active,streaming:I.isStreaming()})},Lr={inputDisabled:!1,sendDisabled:!1},Ln=()=>Lr.inputDisabled,Ep=()=>Wo(n.voiceRecognition?.provider)&&!!I&&(I.isBargeInActive()||["listening","processing","speaking"].includes(I.getVoiceStatus())),ys=()=>Lr.inputDisabled||Lr.sendDisabled,XA=()=>(Lr.inputDisabled?Lr.inputReason:void 0)??(Lr.sendDisabled?Lr.sendReason:void 0);function Pp(){if(!we)return;if(he.getState().phase==="streaming"){we.disabled=!1;return}let s=Ze?!Ze.isReady():!1;we.disabled=ys()||s}function Cd(){if(!wn)return;let s=he.getState(),l=n.sendButton?.visibility==="when-text"&&s.phase!=="streaming"&&s.text.trim().length===0&&s.attachments.length===0;wn.toggleAttribute("data-persona-send-hidden",l)}function QA(){let s=XA();if(Le()){let l=cn??ke;s?l.setAttribute("title",s):l.removeAttribute("title"),ke.toggleAttribute(ii,!!s);return}if(s){at.setAttribute("role","status"),at.setAttribute("aria-live","polite"),at.setAttribute(ii,""),at.textContent=s;return}if(at.hasAttribute(ii)&&(at.removeAttribute("role"),at.removeAttribute("aria-live"),at.removeAttribute(ii),u)){let l=I.getStatus();jl(at,Ph(l),n.statusIndicator??{},l)}}function kp(){let s=Qm(n.composer?.inputDisabled),l=Qm(n.composer?.sendDisabled);Lr={inputDisabled:s.disabled,inputReason:s.reason,sendDisabled:l.disabled,sendReason:l.reason},he.setInputDisabled(s.disabled),he.setSendDisabled(l.disabled);let f=he.getState().phase==="streaming",g=s.disabled,v=f||g;ie&&(ie instanceof HTMLTextAreaElement?ie.disabled=g:ie.setAttribute("contenteditable",g?"false":"true"),ie.setAttribute("aria-disabled",g?"true":"false")),St&&(St.disabled=g),ht&&(ht.disabled=g);for(let A of Rt?.affordanceButtons??[])A.querySelectorAll("button").forEach(_=>{_.disabled=g});ne&&(ne.disabled=g||f&&!Ep()),ss.forEach(A=>{A.elements.forEach(_=>{_.toggleAttribute("data-disabled",v),_ instanceof HTMLButtonElement||_.setAttribute("aria-disabled",v?"true":"false")}),A.buttons.forEach(_=>{_.disabled=v})}),Wp.forEach(A=>{A.toggleAttribute("data-disabled",v),A instanceof HTMLButtonElement?A.disabled=v:A.setAttribute("aria-disabled",v?"true":"false"),A.querySelectorAll("button").forEach(_=>{_.disabled=v})}),ke.dataset.personaComposerStreaming=f?"true":"false",ke.dataset.personaComposerInputDisabled=g?"true":"false",ke.dataset.personaComposerSendDisabled=ys()?"true":"false",ke.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(A=>{(A instanceof HTMLButtonElement||A instanceof HTMLInputElement||A instanceof HTMLTextAreaElement||A instanceof HTMLSelectElement)&&(A.disabled=f)}),Pp(),QA()}let Ei=s=>{he.setStreaming(s),kh(s?"stop":"send"),kp()},bs=()=>{je.active||ie&&ie.focus()};C.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>bs(),200)});let vs=null,Pi=!1,Lp=!Ao.hidden,Ir=null,Ip=!T,Sd=null;fe.push(()=>{Sd?.cancel(),Sd=null});let YA=s=>{let l=OS(s);if(l===Xl)return;Xl=l,e.setAttribute("data-persona-conversation-state",l);let f=ep();Yl(),Ip&&(Sd?.cancel(),Sd=WS(ke,l==="active"?f:ep(),l==="active"?"drop":"rise")),ko()},_y=null,Ny,Fy=null,pa=null,Rp=!1,ki=s=>{let l=Cn(n),f=`${l.variant}|${l.dismiss}|${l.anchor??"bottom"}|${l.align??""}|${l.iconPlacement}|${l.kicker??""}|${l.title}|${l.subtitle}`;(f!==_y||l.icon!==Ny)&&(_y=f,Ny=l.icon,Su({host:Ao,iconHolder:eA,kicker:tA,title:oA,subtitle:nA,starterSuggestions:Qu},l));let g=l.message===void 0?null:`${n.layout?.messages?.layout??"bubble"}|${l.message}`;g!==Fy&&(Fy=g,wu(No,l.message,n));let v=s??(I?I.getMessages():n.initialMessages);YA(v);let A=Pi,_=!A&&Yr(l,v),$=_!==Lp;if(Lp=_,pa){Ir?.cancel(),Ir=null,A!==Rp&&(Rp=A,A?Ng(oe,Ao,null):_g(oe,Ao,pa)),Ja(oe,Ao,!A);return}if($&&!_&&!A&&l.dismiss==="on-first-message"&&Ip){Ir=HS(Ao,j=>{Ir===j&&(Ir=null),!Lp&&!pa&&(Ja(oe,Ao,!1),ko()),j?.cancel()});return}if(Ir){if(!_&&!A)return;Ir.cancel(),Ir=null}let U=!Ao.hidden;Ja(oe,Ao,_),!_&&U&&ko()},Hp=[],Wp=[],Bp=!1,Uy=null,qy,Vy=()=>{Wp.length=0;let s=Hp.splice(0,Hp.length);for(let l of s)try{l()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};fe.push(Vy);let JA=(s,l)=>{let f=Mg(s,l);if(!f)return n.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),R("span");let g=n.suggestions?.starters,v=Tg({item:{...f,behavior:f.behavior??g?.behavior??"send"},index:l,surface:"starter",source:"config",variant:g?.variant??"card",streaming:u?I.isStreaming():!1,config:n,plugins:i,chipsConfig:n.suggestionChipsConfig,session:I,getTextarea:()=>ie,eventTarget:Ao,submitPrompt:Xd});return Wp.push(v),v},Op=()=>{if(Bp)return;Bp=!0;let s=Cn(n);Uy=`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`,qy=s.icon;try{Vy(),Ng(oe,Ao,pa),pa=null,Rp=!1;let l=I?I.getMessages():n.initialMessages,f=Yr(s,l),g=0,v=null;for(let A of i)if(A.renderWelcome&&(v=A.renderWelcome({config:s,variant:s.variant,visible:f,defaultRenderer:()=>Ao,sendMessage:_=>{if(!I||I.isStreaming())return;let $=_.trim();$&&I.sendMessage($)},requestRender:()=>Op(),renderStarter:_=>JA(_,g++),storage:p(A.id),onCleanup:_=>{Hp.push(_)}}),v))break;v&&v!==Ao&&(pa=v,_g(oe,Ao,v))}finally{Bp=!1}ki()},ZA=()=>{let s=Cn(n);`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`===Uy&&s.icon===qy||Op()},wd=()=>{ki(),ea||(ie.placeholder=vC(he.getState().activeModeIds,n.composer?.modes)??n.copy?.inputPlaceholder??"How can I help...",!(n.sendButton?.useIcon??!1)&&!I?.isStreaming()&&(we.textContent=n.copy?.sendButtonLabel??"Send")),ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ie.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},eM=!!n.setStoredConversationId,fa=s=>ae(l=>{let f={...l};return delete f[s],f}),Ad=s=>{let l=V[s];return typeof l=="string"?l:null},$y=()=>{let s=V.durableResume;if(!s||typeof s!="object")return null;let l=s;return typeof l.executionId=="string"&&l.executionId.length>0&&typeof l.after=="string"&&l.after.length>0?{executionId:l.executionId,after:l.after}:null};n.clientToken&&(n={...n,getStoredSessionId:()=>Ad("sessionId"),setStoredSessionId:s=>{ae(l=>({...l,sessionId:s}))},clearStoredSessionId:n.clearStoredSessionId??(()=>fa("sessionId")),getStoredConversationId:n.getStoredConversationId??(()=>Ad("conversationId")),setStoredConversationId:n.setStoredConversationId??(s=>{ae(l=>({...l,conversationId:s}))}),clearStoredConversationId:n.clearStoredConversationId??(()=>fa("conversationId"))});let jy=()=>n.clientToken??null,zy=s=>bw(s,Y(),n.persistState===!1),Ky=jy(),Zo=Ky?zy(Ky):null,er={...Zo?{visitorStore:Zo}:{},historyBootstrapReady:D,getStoredMessageCursor:()=>Ad("historyMessageCursor"),setStoredMessageCursor:s=>{if(s===null){fa("historyMessageCursor");return}ae(l=>({...l,historyMessageCursor:s}))},getPendingDisplayProjections:()=>{let s=V.pendingDisplayProjections;if(!s||typeof s!="object")return null;let l=s;return typeof l.conversationId!="string"||!Array.isArray(l.messageIds)?null:{conversationId:l.conversationId,messageIds:l.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:s=>{if(!s){fa("pendingDisplayProjections");return}ae(l=>({...l,pendingDisplayProjections:s}))},getStoredResumableHandle:$y,setStoredResumableHandle:s=>{if(!s){fa("durableResume");return}ae(l=>({...l,durableResume:s}))},shouldResumeDurableConversation:()=>X&&$y()!==null,...eM?{}:{getStoredConversationRevision:()=>Ad("conversationRevision"),setStoredConversationRevision:s=>{if(s===null){fa("conversationRevision");return}ae(l=>({...l,conversationRevision:s}))}}};if(X){let s=n.onExecutionState,l=e.ownerDocument.defaultView,f=!1,g=()=>f=!0,v=()=>f=!1;l?.addEventListener("pagehide",g),l?.addEventListener("pageshow",v),fe.push(()=>{l?.removeEventListener("pagehide",g),l?.removeEventListener("pageshow",v)}),n={...n,reconnectStream:n.reconnectStream??(A=>I.getClient().reconnectClientTokenStream(A)),onExecutionState:A=>{(A||!f)&&er.setStoredResumableHandle?.(A?{executionId:A.executionId,after:A.lastEventId}:null),s?.(A)}}}let tM=()=>{let s=jy();if(s&&Zo?.matches(s,Y(),n.persistState===!1)||!s&&!Zo)return;Zo?.destroy(),Zo=s?zy(s):null;let l={...er};Zo?l.visitorStore=Zo:delete l.visitorStore,er=l,I.setHistoryInternals(er)},xs=null,oM=()=>{xs==null&&(xs=setInterval(()=>{let s=Te.querySelectorAll("[data-tool-elapsed]");if(s.length===0){clearInterval(xs),xs=null;return}let l=Date.now();s.forEach(f=>{let g=Number(f.getAttribute("data-tool-elapsed"));g&&(f.textContent=vc(l-g))})},100))},Dp=(s,l)=>{if(Object.is(s,l))return!0;if(s===null||l===null||typeof s!="object"||typeof l!="object")return!1;if(Array.isArray(s)||Array.isArray(l))return!Array.isArray(s)||!Array.isArray(l)||s.length!==l.length?!1:s.every((_,$)=>Dp(_,l[$]));let f=s,g=l,v=Object.keys(f),A=Object.keys(g);return v.length===A.length&&v.every(_=>Object.prototype.hasOwnProperty.call(g,_)&&Dp(f[_],g[_]))},Gy=s=>{let{content:l,rawContent:f,llmContent:g,...v}=s;return v},_p=s=>s.role==="assistant"&&s.streaming===!0&&!s.variant&&!s.toolCall&&!s.tools&&!s.approval&&!s.reasoning&&!s.contentParts&&!s.stopReason&&!ql(s),nM=(s,l,f)=>{if(s.length!==l.length)return!1;let g=s[f.index],v=l[f.index];return!g||!v||g.id!==f.id||v.id!==f.id?!1:(!Object.is(g.content,v.content)||!Object.is(g.rawContent,v.rawContent)||!Object.is(g.llmContent,v.llmContent))&&_p(g)&&_p(v)&&Dp(Gy(g),Gy(v))},Np=null,ma=null,Cs=null,tr=null,Fp=null,rM=s=>{if(!X)return la(s);Fp=s,queueMicrotask(()=>{Fp===s&&(Fp=null,la(s))})},Md=s=>{Np=s;let l,f;ma=null;for(let v=s.length-1;v>=0;v-=1){let A=s[v];if(!l&&A.role==="user"&&(l=A),!f&&A.role==="assistant"&&(f=A),!ma&&_p(A)&&(ma={index:v,id:A.id}),l&&f&&ma)break}Jo(Te,s,wt),hr()?.updateInlineArtifactBlocks(Te,Yo.artifacts,{suppressTransition:qo}),oM(),ki(s),ra(s),kr(!qo),VA(s),s.length===0&&(gn(),vi=!0,cd=!1,ia=null,ud=!1),!yp||aa?(yp=!0,fs=l?.id??null,bp=f?.id??null):l&&l.id!==fs?(fs=l.id,_A(l.id)):f&&f.id!==bp&&NA(),f&&(bp=f.id),qA(s);let g=je.lastUserMessageId;l&&l.id!==g&&(je.lastUserMessageId=l.id,C.emit("user:message",l)),je.lastUserMessageWasVoice=!!l?.viaVoice,rM(s),ua()},Up=()=>{tr!==null&&(cancelAnimationFrame(tr),tr=null);let s=Cs;Cs=null,s&&Md(s)},Xy=()=>{tr!==null&&cancelAnimationFrame(tr),tr=null,Cs=null},sM=s=>{let l=Cs??Np;if(qo&&l&&ma&&nM(l,s,ma)){Cs=s,tr===null&&(tr=requestAnimationFrame(()=>{tr=null;let f=Cs;Cs=null,f&&Md(f)}));return}if(s.length===0){Xy(),Md(s);return}Up(),Md(s)};I=new Da(n,{onMessagesChanged(s){sM(s)},onStatusChanged(s){let l=n.statusIndicator??{};jl(at,(g=>g==="idle"?l.idleText??qt.idle:g==="connecting"?l.connectingText??qt.connecting:g==="connected"?l.connectedText??qt.connected:g==="error"?l.errorText??qt.error:g==="paused"?l.pausedText??qt.paused:g==="resuming"?l.resumingText??qt.resuming:qt[g])(s),l,s),Xu()},onStreamingChanged(s){s||(I?.getMessages().length===0?Xy():Up()),qo=s,Ei(s),Xu(),I&&Jo(Te,I.getMessages(),wt),s||(kr(!0),OA(),Cy=!0,I&&Sy(I.getMessages(),jr(n))),$t(),Gl(s?"Responding\u2026":"Response complete."),ua()},onVoiceStatusChanged(s){if(C.emit("voice:status",{status:s,timestamp:Date.now()}),!(s!=="disconnected"&&!Wo(n.voiceRecognition?.provider)))switch(s){case"listening":ar(),Ma();break;case"processing":ar(),iT();break;case"speaking":ar(),lT();break;default:s==="idle"&&I.isBargeInActive()?(ar(),Ma(),ne?.setAttribute("aria-label","End voice session")):(je.active=!1,ar(),Jn("system"),mn());break}},onArtifactsState(s){Yo=s,s.artifacts.length===0&&(ta=!1),hr()?.updateInlineArtifactBlocks(Te,s.artifacts,{suppressTransition:qo}),fn(),la()},onHistoryStateChanged(s){Th(s)},onHistoryNotice(s){Eh(s)},onReconnect(s){let{executionId:l,lastEventId:f}=s.handle;s.phase==="paused"?C.emit("stream:paused",{executionId:l,after:f}):s.phase==="resuming"?C.emit("stream:resuming",{executionId:l,after:f,attempt:s.attempt??1}):C.emit("stream:resumed",{executionId:l,after:f})}},er),dt.current=I,fe.push(()=>I.cancel()),fe.push(()=>{I.destroy(),Zo?.destroy(),Zo=null});let qp=null;if(I.onReadAloudChange((s,l)=>{Jh=s,Zh=l,ey();let f=s??qp;s&&(qp=s);let g=f?I.getMessages().find(v=>v.id===f)??null:null;C.emit("message:read-aloud",{messageId:f,message:g,state:l,timestamp:Date.now()}),l==="idle"&&(qp=null)}),u=!0,yp=!0,n.voiceRecognition?.enabled===!0&&Wo(n.voiceRecognition.provider))try{I.setupVoice()}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",s)}let aM=720,iM=250,Qe=uh(n.features?.history?.copy),jo=null,Vp=!1,it=null,Td=null,Ed="conversation",$p=null,fo=null,In=null,Pd=I.getHistoryState(),jp=null,Li=0,zp=null,kd=null,Ld=null,Kp=`persona-history-${Math.random().toString(36).slice(2,8)}`,Gp=()=>n.features?.history?.enabled===!0,Rn=()=>Gp()&&!!jo&&!Vp,Qy=()=>{let s=I.getStatus();return qo||s==="paused"||s==="resuming"},Xp=()=>{let s=n.features?.history?.scope;if(s)return s;let l=n.getIdentityProof?"verified-user":"browser",f=jo?.capabilities.scopes;return!f||f.includes(l)?l:f[0]??l},ga=()=>Td?.scope??Xp(),Yy=()=>I.getClientSession()?.targetId??null,Jy=s=>`${s.state}:${"reason"in s?s.reason:""}`,lM=s=>{let l=Jy(s);l!==jp&&(jp=l,C.emit("history:identityStatusChanged",{status:s,timestamp:Date.now()}))},Id=s=>{s&&(zn.textContent="",zn.textContent=s)},Zy=null,eb=null,dM=()=>{if(!Gp())return null;let s=ww();if(s)return s();let l=n.features?.history?.provider;return l?typeof l!="function"?l:(Zy!==l&&(Zy=l,eb=l()),eb):I.isClientTokenMode()?Aw({client:I.getClient(),getIdentityProofConfigured:()=>typeof n.getIdentityProof=="function",onActivationCommitted:f=>I.bindActivatedSession(f),getClient:()=>I.getClient()}):null},tb=()=>{kd?.(),kd=null,Ld?.(),Ld=null,Vp=!1,jo=dM();let s={...er};jo?s.historyProvider=jo:delete s.historyProvider,er=s,I.setHistoryInternals(er),jo&&(kd=jo.subscribeAvailability?.(l=>{Vp=!l,l||Lo({restoreFocus:!1}),Hr()})??null,Ld=jo.subscribeIdentityStatus(l=>lM(l)),jp=Jy(jo.getIdentityStatus()))},Qp=()=>{let s=n.features?.history?.presentation??"panel";if(s==="panel"||s==="auto"&&!(!pe||Ct(n)))return"panel";let l=En??de;return(l.getBoundingClientRect().width||l.clientWidth)>=aM?"rail":"panel"},en=(s,l)=>{l?(s.setAttribute("aria-hidden","true"),s.setAttribute("inert","")):(s.removeAttribute("aria-hidden"),s.removeAttribute("inert"))},Rd="data-persona-history-suppressed",zo=null,Rr=null,Ss=null,Ii=null,Yp=null,ob="",nb=()=>Ae===Yp?ob:n.layout?.showHeader===!1?"none":"",cM=()=>Wt==="panel"&&!!Ss&&Ii===Ss.element&&n.layout?.showHeader!==!1&&nb()!=="none",uM=()=>{for(let s of Array.from(Ae.children))s!==zo&&s.setAttribute(Rd,"")},pM=()=>{for(let s of Array.from(de.querySelectorAll(`[${Rd}]`)))s.removeAttribute(Rd)},fM=()=>{let s=Ss;if(!s)return;if(Array.from(Ae.children).some(g=>g!==zo&&!g.hasAttribute(Rd))){Rr&&Rr!==Ae&&(Rr.style.removeProperty("min-height"),Rr=null);let g=Ae.offsetHeight;g>0&&(Ae.style.minHeight=`${g}px`,Rr=Ae)}zo||(zo=R("div","persona-history-header-host")),s.setHeaderPlacement("external");let f=s.getHeaderElement();f.parentNode!==zo&&zo.replaceChildren(f),zo.parentNode!==Ae&&Ae.appendChild(zo),uM()},rb=()=>{Rr&&(Rr.style.removeProperty("min-height"),Rr=null),zo&&(Ss?.setHeaderPlacement("inline"),zo.remove(),zo=null,pM())},Hd=null,Jp=()=>{if(Hd){if(oe.style.display="none",en(oe,!0),ke.hidden=!0,en(ke,!0),cM()){fM(),Ae.style.display=nb(),en(Ae,!1);return}rb(),Ae.style.display="none",en(Ae,!0)}};Gu=Jp;let mM=s=>{let l=oe.style.display,f=ke.hidden,g=ke,v=Ae,A=Ae.style.display;Yp=v,ob=A,Hd=()=>{Hd=null,rb(),Yp=null,oe.style.display=l,en(oe,!1),g.hidden=f,en(g,!1),ke!==g&&(ke.hidden=!1,en(ke,!1)),v.style.display=A,en(v,!1),Ae!==v&&(Ae.style.display=n.layout?.showHeader===!1?"none":"",en(Ae,!1))},ke.parentNode?.insertBefore(s,ke),Jp()},ha=null,ws=null,Ri=null,ya=null,sb=()=>[Ae,Oe.closeButtonWrapper,Oe.clearChatButtonWrapper,oe,ke],gM=52,Wd=()=>n.features?.history?.rail?.collapsible!==!1,ba=()=>n.features?.history?.rail?.side==="right"?"right":"left",Zp=200,ef=400,tf=s=>Math.min(ef,Math.max(Zp,Math.round(s))),hM=()=>n.features?.history?.rail?.resizable===!0,Hi,yM=()=>{if(Hi===void 0&&(Hi=null,n.persistState!==!1))try{let s=Number(window.localStorage.getItem(`${Y()}rail-width`));s&&(Hi=s)}catch{}return Hi},Wi=()=>tf(yM()??n.features?.history?.rail?.width??260),bM=s=>{if(Hi=s,n.persistState!==!1)try{window.localStorage.setItem(`${Y()}rail-width`,String(s))}catch{}},Bd=()=>Wd()&&n.features?.history?.rail?.collapsedBehavior==="overlay",Dt=!1,ab=s=>{let l=R("img");return l.src=s,l.alt="",l.setAttribute("aria-hidden","true"),l},vM=()=>{let s=n.features?.history?.rail?.brand;if(!s)return;let l=!1,f;return g=>{if(s.render)try{return s.render({collapsed:g})??null}catch(v){return l||(l=!0,console.warn("[persona] history rail brand threw",v)),null}return f===void 0&&(s.iconUrl?f=ab(s.iconUrl):f=s.icon?le(s.icon,20):null),f?f.cloneNode(!0):null}},xM=()=>n.features?.history?.rail?.sections?.map(s=>{let l=!1,f=g=>{l||(l=!0,console.warn("[persona] history rail section threw",s.id,g))};return{id:s.id,title:s.title,placement:s.placement??"above-conversations",items:s.items.map(g=>{let v;return{id:g.id,label:g.label,badge:g.badge,iconNode:()=>{if(v!==void 0)return v;try{g.renderIcon?v=g.renderIcon()??null:g.iconUrl?v=ab(g.iconUrl):v=g.icon?le(g.icon,20):null}catch(A){f(A),v=null}return v},onSelect:()=>{try{g.onSelect()}catch(A){f(A)}}}})}})??[],CM=s=>{let l=xM();for(let f of s)l.some(g=>g.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):l.push(f);return l.length?l:void 0},Bi=null,ib=()=>`${Y()}rail-collapsed`,of=()=>{if(Bi===null&&(Bi=n.features?.history?.rail?.defaultCollapsed===!0,n.persistState!==!1))try{let s=window.localStorage.getItem(ib());s&&(Bi=s==="1")}catch{}return Bi},nf=s=>{if(Bi=s,n.persistState!==!1)try{window.localStorage.setItem(ib(),s?"1":"0")}catch{}},Oi=()=>Wt==="rail"&&Wd()&&!Bd()&&of(),rf=()=>{},lb=()=>{if(Bd()){rf();return}nf(!of()),it?.view.setCollapsed(Oi()),jn(),ko()},sf=()=>{let s=n.features?.history?.rail?.collapseShortcut;return!s||!cu(s)?null:{combo:s,hint:uu(s),aria:Ml(s)}},db=()=>{c.forEach(l=>l()),c=[];let s=sf();s&&c.push(d.register({id:"history-rail-collapse",combo:s.combo,scope:n.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>At&&Wt==="rail"&&Wd()||xa(),run:()=>Bd()?rf():lb()}));for(let l of n.layout?.header?.trailingActions??[])l.shortcut&&c.push(d.register({id:`header-action-${l.id}`,combo:l.shortcut,run:()=>{let f=e.querySelector(`[data-persona-header-action="${l.id}"]`);f?f.click():n.layout?.header?.onAction?.(l.id)}}));for(let l of i)for(let f of l.shortcuts??[])c.push(d.register({...f,id:`${l.id}:${f.id}`}))};db();let SM=300,Od="var(--persona-history-overlay-margin,8px)",tn=null,or=null,Dd=0,nr=null,va=null,As=!1,af=0,cb=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,xa=()=>Rn()&&Bd()&&(Wt??Qp())==="rail",wM=()=>At&&!Dt,Di=()=>{va!==null&&clearTimeout(va),va=null},AM=()=>{lh().catch(()=>{})},ub=()=>{Di(),Dt&&(va=setTimeout(()=>{va=null,!(As||!Dt)&&(nr?.contains(document.activeElement)||Lo({restoreFocus:!1}))},SM))},MM=(s,l)=>{let f=nr?.getBoundingClientRect();if(!f)return!1;let g=tn?.getBoundingClientRect(),v=g?Math.min(g.top,f.top):f.top;return s>=f.left&&s<=f.right&&l>=v&&l<=f.bottom||!!g&&s>=g.left&&s<=g.right&&l>=g.top&&l<=g.bottom},lf=s=>{Dt&&(As=MM(s.clientX,s.clientY),As?Di():va===null&&ub())},pb=s=>{At||!xa()||(Dt=!0,Ni({invoker:tn,keyboard:s?.keyboard===!0}).then(()=>{At?!As&&document.activeElement!==tn&&Lo():Dt=!1}))},fb=()=>{let s=Ii?.querySelector('[data-persona-history-focus="collapse"]');s&&(s.setAttribute("aria-label",Dt?Qe.expandLabel:Qe.collapseLabel),s.setAttribute("aria-expanded",Dt?"false":"true"))},mb=()=>{nf(!1);let s=it;if(!Dt||!s){Ni({invoker:tn});return}let l=document.activeElement===tn;Dt=!1,_d(),s.element.remove(),cf(s.element),fb(),l&&Fd(),ko(),Hr()},TM=()=>{nf(!0),Lo()};rf=()=>{!At||Dt?mb():TM()};let EM=()=>{let s=sf(),l=Ns({ariaLabel:Qe.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":Kp,...s?{"aria-keyshortcuts":s.aria}:{}}}),f=l.button;f.addEventListener("mouseenter",()=>{As=!0,Di(),!(cb()||Date.now()<af)&&pb()}),f.addEventListener("mouseleave",()=>{As=!1,af=0,ub()}),f.addEventListener("focus",()=>{At||AM()}),f.addEventListener("click",g=>{Rn()&&(g.detail!==0&&cb()&&!At?pb():mb())}),tn=f,or=l.wrapper},_i=()=>{if(or&&!or.isConnected&&(or=null,tn=null),!xa()){or?.remove(),or=null,tn=null;return}tn||EM();let s=or,l=tn;if(!s||!l)return;let f=ba()!=="right"?Ae.firstChild:null;(f??Ae.lastChild)!==s&&Ae.insertBefore(s,f),s.style.display=wM()||Dd>0?"none":"",l.setAttribute("aria-label",Qe.expandLabel),l.setAttribute("aria-expanded",At?"true":"false"),nr&&jn()},gb=s=>{if(!Dt)return;let l=s.target;l instanceof Node&&(nr?.contains(l)||or?.contains(l)||l instanceof Element&&l.closest('.persona-dropdown-menu,[role="alertdialog"]')||Lo({restoreFocus:!1}))};document.addEventListener("pointerdown",gb,!0),fe.push(()=>{document.removeEventListener("pointerdown",gb,!0),document.removeEventListener("pointermove",lf),Ca?.(),Di()});let df=null,Ca=null,hb=16,yb=s=>{bM(tf(s)),jn(),ko()},PM=()=>{let s=R("div","persona-rail-resizer");return s.tabIndex=0,s.setAttribute("role","separator"),s.setAttribute("aria-orientation","vertical"),s.setAttribute("aria-valuemin",String(Zp)),s.setAttribute("aria-valuemax",String(ef)),s.addEventListener("pointerdown",l=>{let f=ws;if(!f||l.button!==0)return;l.preventDefault(),Ca?.();let g=l.clientX,v=f.getBoundingClientRect().width||Wi(),A=ba()==="right"?-1:1,_=v,$=e.ownerDocument;f.style.transition="none";let U=J=>{_=tf(v+A*(J.clientX-g)),f.style.flex=`0 0 ${_}px`,s.setAttribute("aria-valuenow",String(_))},j=()=>{Ca=null,$.removeEventListener("pointermove",U),$.removeEventListener("pointerup",j),$.removeEventListener("pointercancel",j),f.style.removeProperty("transition");try{s.releasePointerCapture(l.pointerId)}catch{}yb(_)};Ca=j,$.addEventListener("pointermove",U),$.addEventListener("pointerup",j),$.addEventListener("pointercancel",j);try{s.setPointerCapture(l.pointerId)}catch{}}),s.addEventListener("keydown",l=>{let f=ba()==="right"?-hb:hb,g=Wi(),v=l.key==="ArrowRight"?g+f:l.key==="ArrowLeft"?g-f:l.key==="Home"?Zp:l.key==="End"?ef:null;v!==null&&(l.preventDefault(),yb(v))}),s},kM=(s,l)=>{if(!hM()||Oi()){Ca?.(),df?.remove();return}let f=df??PM();df=f,f.setAttribute("aria-label",Qe.resizeLabel),f.setAttribute("aria-valuenow",String(Wi())),f.nextElementSibling!==l&&s.insertBefore(f,l)};jn=()=>{it?.view.setRailSide(ba());let s=ba()==="right",l=nr;if(l){let $=tn?tn.getBoundingClientRect().bottom-de.getBoundingClientRect().top:0;l.style.top=`calc(${Math.max(0,Math.round($))}px + ${Od})`,l.style.width=`${Wi()}px`,l.style.left=s?"":Od,l.style.right=s?Od:""}let f=ws,g=ha,v=Ri;if(!f||!g||!v)return;f.style.flex=`0 0 ${Oi()?gM:Wi()}px`;let A="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=s?"":A,f.style.borderLeft=s?A:"";let _=s?v:f;g.firstElementChild!==_&&g.append(_,s?f:v),kM(g,s?f:v)};let bb=s=>{if(ya&&ws){ya.replaceWith(s),ya=null,jn();return}let l=R("div","persona-history-rail-shell");l.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=R("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let g=R("div","persona-history-rail-host");g.style.cssText="display:flex;min-height:0;overflow:hidden",de.insertBefore(l,Ae.parentNode===de?Ae:oe);for(let v of sb())v?.parentNode===de&&f.appendChild(v);l.append(g,f),g.appendChild(s),ha=l,ws=g,Ri=f,jn()},LM=()=>{if(ha)return;let s=R("div","persona-history-rail-placeholder");s.style.cssText="flex:1 1 auto;min-height:0",ya=s,bb(s),ko()},vb=()=>{ya&&(_d(),ko())},IM=s=>{let l=R("div","persona-history-rail-overlay");l.style.cssText=`position:absolute;bottom:${Od};display:flex;overflow:hidden;z-index:${qa-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,de.style.position="relative",de.appendChild(l),l.appendChild(s),document.addEventListener("pointermove",lf),nr=l,jn(),fb()},_d=()=>{Hd?.(),nr&&(As&&(af=Date.now()+150),document.removeEventListener("pointermove",lf),nr.remove(),nr=null);let s=ha;if(s){Ca?.();for(let l of sb())l&&s.contains(l)&&de.insertBefore(l,s);s.remove(),ha=null,ws=null,Ri=null,ya=null}},xb=s=>{Ii=s,s.id=Kp,s.style.flex="1 1 auto",s.style.minHeight="0"},cf=s=>{xb(s),(Wt!=="rail"||Dt)&&vb(),Wt!=="rail"?mM(s):Dt?IM(s):bb(s)},Nd=()=>{if(_i(),Ib(),!At||!it)return;let s=Qp();if(s===Wt)return;let l=document.activeElement,f=l instanceof HTMLElement&&(it.element.contains(l)||zo?.contains(l)===!0)?l:null;_d(),it.element.remove(),it.view.setHeaderPlacement("inline"),Wt=s,it.view.setPresentation(s),it.view.setCollapsed(Oi()),it.requestRender(),it.element.isConnected||cf(it.element),f?.isConnected?f.focus():Fd(),$t(),ko(),Hr()},Cb=(s,l)=>zo?.querySelector(l)??s.querySelector(l),Fd=()=>{let s=it?.element??Ii;if(!s)return;let l=Cb(s,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(l){l.focus();return}let f=Cb(s,".persona-history-title")??s;f.tabIndex=-1,f.focus()},Ni=async s=>{if(!Rn()||At)return;let l=jo;if(!l)return;if(!Dt&&xa()&&of()){_i();return}Ud();let f=++Li;Ed=s?.returnSurface??"conversation",$p=s?.invoker??fo;let g=xa()&&!Dt;g&&(Dd+=1,_i(),LM());let v;try{v=await lh()}catch{Id(Qe.openHistoryLabel),g&&(Dd-=1,f===Li&&(vb(),_i()));return}if(g&&(Dd-=1),f!==Li||At)return;Td={scope:Xp()},Wt=Qp(),At=!0;let A=Wt==="panel"&&n.layout?.showHeader!==!1&&Ae.style.display!=="none"?"external":"inline",_=n.features?.history?.rowAvatar,$=sf(),U=$?{hint:$.hint,aria:$.aria}:null,j={provider:l,context:Td,targetId:Yy(),presentation:Wt,collapsible:Wd(),collapsed:Oi(),railSide:ba(),renderRailHeader:n.features?.history?.rail?.renderHeader,railBrand:vM(),onToggleCollapse:lb,...U?{collapseShortcut:U}:{},headerPlacement:A,showScopeStatus:n.features?.history?.showScopeStatus!==!1,showDelete:n.features?.history?.showDelete!==!1,showDeleteAll:n.features?.history?.showDeleteAll!==!1,...n.features?.history?.listActions?.length?{listActions:n.features.history.listActions}:{},rowAvatar:_===!1?!1:typeof _=="string"?_:n.launcher?.iconUrl,activeConversationId:I.getActiveConversationId(),...n.features?.history?.grouping?{grouping:n.features.history.grouping}:{},...n.features?.history?.copy?{copy:n.features.history.copy}:{},...n.features?.history?.pageSize!==void 0?{pageSize:n.features.history.pageSize}:{},onSelect:J=>pf(J,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:J=>Ms(J),attachTooltip:Jt,onStartNew:()=>ff({focusComposer:!0}),onClose:()=>Lo(),onRequestDeleteConversation:J=>Lb(J),onRequestClearHistory:()=>DM(),...l.resetDevice?{onRequestResetIdentity:()=>_M()}:{}};it=Sw({plugins:i,config:n,getPresentation:()=>Wt??"panel",getReturnSurface:()=>Ed,close:()=>Lo(),createView:({slots:J,renderDom:re,onModelChange:ce,railSections:Ye})=>(Ss=v.createHistoryView({...j,railSections:CM(Ye),slots:J,renderDom:re,onModelChange:ce,onAnnounce:Id}),Ss),onElementChanged:(J,re)=>{if(!re?.isConnected)return cf(J);xb(J),re.replaceWith(J),Jp()}}),it.view.setNewConversationRequired(Pd.recovery==="new_conversation_required"),s?.focus!==!1&&(Wt!=="rail"||s?.keyboard===!0)&&Fd(),$t(),ko(),Hr(),C.emit("history:opened",{presentation:Wt,returnSurface:Ed,timestamp:Date.now()})},Ud=()=>{},Lo=s=>{if(!At)return;Li+=1;let l=Ed,f=$p,g=it,v=s?.restoreFocus!==!1;At=!1;let A=!1,_=null,$=()=>{if(!A){if(A=!0,Ud=()=>{},_!==null&&clearTimeout(_),Dt=!1,Di(),_d(),g?.dispose(),g?.view.destroy(),g?.element.remove(),it===g&&(it=null,Ss=null,Ii=null,Wt=null,Td=null,$p=null),$t(),ko(),Hr(),v){let j=f??fo;j?.isConnected?j.focus():bs()}C.emit("history:closed",{returnSurface:l,timestamp:Date.now()})}},U=g&&g.element===g.view.element?g.view.playExit():null;if(!U){$();return}Ud=$,_=setTimeout($,iM),U.then($)},Sb=s=>{if(!(s.key!=="Escape"||!At||!it)){if(Wt==="rail"){let l=s.target;if(!(l instanceof Node)||!(it.element.contains(l)||Dt&&or?.contains(l)===!0))return}s.preventDefault(),s.stopPropagation(),Lo()}};de.addEventListener("keydown",Sb),fe.push(()=>de.removeEventListener("keydown",Sb));let qd=null,wb=!1,Fi=()=>{if(!xr)return;let s=n.layout?.header?.titleSource==="conversation",l=s&&qd?.trim()||null;xr.textContent=l??n.launcher?.title??"Chat Assistant";let f=xr.closest(".persona-combo-btn");if(!f)return;let g=!s||I.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",g?"false":"true"),f.setAttribute("aria-haspopup",g?"true":"false"),g||f.setAttribute("aria-expanded","false"),f.style.cursor=g?"pointer":"default";let v=f.querySelector("svg");v&&(v.style.display=g?"":"none")},RM=s=>{s!==qd&&(qd=s,Fi())},Ms=s=>{wb=s?.starred===!0,RM(s&&s.title.trim()||null),Fi()};Fi(),de.addEventListener("persona:title-menu-builtin",s=>{let l=s.detail?.actionId,f=I.getActiveConversationId();f&&(l==="delete"?Lb(f):l==="star"&&I.canUpdateConversations()&&mf(f,{starred:!wb}).catch(()=>{}))});let Vd=0,HM=250,$d=null,jd=()=>{$d&&clearTimeout($d),$d=null};fe.push(jd);let Ab=()=>{jd();let s=vs;s&&(Pi=!0,s.hidden=!1,Te.style.display="none",ki())},zd=()=>{Vd+=1,jd(),vs&&(vs.remove(),vs=null,Pi=!1,Te.style.removeProperty("display"),en(ke,!1),ki())},WM=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Te.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},uf=(s,l)=>Q("div",{className:yo("persona-conversation-loading-bubble",l&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:s}}),Mb=()=>Q("div",{className:"persona-conversation-loading-body"},uf("58%",!1),uf("72%",!0),uf("44%",!1)),Tb=s=>{vs?.remove(),vs=s,s.hidden=!Pi,oe.insertBefore(s,Te),jd(),Pi||($d=setTimeout(Ab,HM)),en(ke,!0)},BM=()=>{let s={config:n,streaming:!1,location:"conversation-open",defaultRenderer:Mb},l=null,f=i.find(g=>g.renderLoadingIndicator);f?.renderLoadingIndicator&&(l=f.renderLoadingIndicator(s)),l===null&&n.loadingIndicator?.render&&(l=n.loadingIndicator.render(s)),Tb(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},l??Mb()))},OM=s=>{let l=()=>{pf(s,{focusComposer:!0}).catch(()=>{})},f=Rn()?()=>{zd(),Ni()}:void 0,g=($,U)=>{let j=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:$});return j.addEventListener("click",U),j},v=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},g(Qe.openConversationRetryLabel,l),f?g(Qe.openConversationBackLabel,f):null)),A=Object.freeze({conversationId:s,config:n,copy:Object.freeze({title:Qe.openConversationErrorTitle,retryLabel:Qe.openConversationRetryLabel,backLabel:Qe.openConversationBackLabel}),retry:l,...f?{back:f}:{},defaultRenderer:v}),_=null;for(let $ of i)if($.renderHistoryOpenError){try{_=$.renderHistoryOpenError(A)}catch(U){console.warn("[persona] renderHistoryOpenError threw",U),_=null}if(_)break}Tb(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},_??v())),Ab()};C.on("history:closed",()=>{vs&&en(ke,!0)});let pf=async(s,{focusComposer:l=!1}={})=>{let f=ga(),g=!!it;it?.view.setActiveConversationId(s),zd();let v=Vd;BM(),At&&(Wt==="panel"||Dt)&&Lo({restoreFocus:!1}),aa=!0;try{await I.openConversation(s,{scope:f})}catch(A){throw v===Vd&&OM(s),A}finally{aa=!1}v===Vd&&(zd(),Ot.clear(),gn(),Po(),Ap()||hd(),WM(),rr(),g||Ms(null),C.emit("history:conversationOpened",{conversationId:s,title:qd,scope:f,timestamp:Date.now()}),l&&bs())},ff=async({focusComposer:s=!1}={})=>{zd(),await I.startNewConversation({scope:ga()}),Ms(null),Ot.clear(),gn(),Po(),hd(),rr();let l=I.getActiveConversationId();it?.view.setActiveConversationId(l),C.emit("history:conversationStarted",{conversationId:l,timestamp:Date.now()}),At&&(Wt==="panel"||Dt)&&Lo({restoreFocus:!1}),s&&bs()},mf=async(s,l)=>{let f=await I.updateConversation(s,{...l,...l.title!==void 0?{title:l.title.trim()}:{}});return it?.view.applyConversationSummary(f),!it&&s===I.getActiveConversationId()&&Ms(f),f},Eb=async s=>{let l=ga(),f=I.getActiveConversationId()===s;await I.deleteConversation(s,{scope:l}),it?.view.removeConversationSummary(s),f&&(Ms(null),Ot.clear(),gn(),Po(),rr()),C.emit("history:conversationDeleted",{conversationId:s,scope:l,wasActive:f,timestamp:Date.now()})},Pb=async s=>{let l=s?.scope??ga(),f=s?.allTargets?null:s?.targetId??Yy(),g=await I.clearConversationHistory({...f?{targetId:f}:{},scope:l});return Ms(null),Ot.clear(),gn(),Po(),rr(),C.emit("history:cleared",{deleted:g.deleted,scope:l,targetId:f,timestamp:Date.now()}),g},kb=async()=>{if(!jo?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let s=!1;try{s=(await I.resetHistoryDevice()).remoteRevocationConfirmed}finally{Ms(null),I.clearArtifacts(),Ot.clear(),Np=null,n.clearStoredSessionId?.(),n.clearStoredConversationId?.(),V={},be.syncFromMetadata(),N?.clear&&fd(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),gn(),Po(),rr(),Lo({restoreFocus:!1}),bs(),ve||Tt?.launcher.element.focus()}return Id(s?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),C.emit("history:identityReset",{remoteRevocationConfirmed:s,timestamp:Date.now()}),{remoteRevocationConfirmed:s}},gf=()=>En?Ce:de,Lb=async s=>await Ou({host:gf(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Eb(s),"deleted"):"cancelled",DM=async()=>{let s=ga()==="verified-user";return await Ou({host:gf(),title:Qe.clearHistoryConfirmTitle,description:s?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Pb(),"cleared"):"cancelled"},_M=async()=>{if(!await Ou({host:gf(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:l}=await kb();return{outcome:"reset",remoteRevocationConfirmed:l}},on=R("button","persona-history-earlier");on.type="button",on.textContent=Qe.showEarlierMessagesLabel,on.setAttribute("data-persona-history-earlier",""),Object.assign(on.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let rr=()=>{if(!(Rn()&&!!Pd.nextMessageCursor&&!!I.getActiveConversationId())){on.remove();return}on.textContent=Qe.showEarlierMessagesLabel,on.parentNode!==oe&&oe.insertBefore(on,oe.firstChild)};on.addEventListener("click",()=>{let s=I.getActiveConversationId(),l=Pd.nextMessageCursor;if(!s||!l||on.disabled)return;on.disabled=!0;let f=oe.scrollHeight,g=oe.scrollTop;I.loadOlderMessages(s,l,{scope:ga()}).then(()=>{oe.scrollTop=g+(oe.scrollHeight-f),ko()}).catch(()=>{}).finally(()=>{on.disabled=!1,rr()})});let NM=()=>{let s=Ns({ariaLabel:Qe.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return s.button.addEventListener("click",l=>{if(!(!Rn()||Qy())){if(At){Lo();return}Ni({invoker:s.button,keyboard:l.detail===0})}}),s},Ib=()=>{if(!Rn()){In?.remove(),fo=null,In=null;return}if(In&&!In.isConnected&&(fo=null,In=null),!fo&&Ae){let g=NM();fo=g.button,In=g.wrapper;let v=Oe.clearChatButtonWrapper||Oe.closeButtonWrapper;v?.parentNode&&Ae.contains(v)?v.parentNode.insertBefore(In,v):Ae.appendChild(In)}if(!fo||!In)return;let s=xa()||At&&Wt==="rail";if(In.style.display=s?"none":"",s){document.activeElement===fo&&Fd();return}let l=Qy();fo.disabled=l,fo.setAttribute("aria-disabled",l?"true":"false");let f=l?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;fo.setAttribute("aria-label",f),(n.features?.history?.presentation??"panel")==="panel"?(fo.removeAttribute("aria-expanded"),fo.removeAttribute("aria-controls")):(fo.setAttribute("aria-expanded",At?"true":"false"),fo.setAttribute("aria-controls",Kp))},Kd=!1,FM=()=>{let s=Oe.clearChatButton;if(s){if(Rn()){Kd||(zp=s.getAttribute("aria-label")??"",Kd=!0),s.setAttribute("aria-label",Qe.newConversationLabel),s.removeAttribute("title");return}Kd&&(Kd=!1,zp&&s.setAttribute("aria-label",zp))}},Hr=()=>{Qe=uh(n.features?.history?.copy),Ib(),_i(),FM(),rr()};Xu=Hr,Th=s=>{Pd=s,it?.view.setNewConversationRequired(s.recovery==="new_conversation_required"),Ei(s.sendBlocked||qo),rr()},Eh=s=>{(s.code==="history_continuity_reset"||s.code==="conversation_deleted_recovered")&&(Ot.clear(),gn(),Po()),Id(s.message),it?.view.refresh()},tb(),Hr(),fe.push(()=>{kd?.(),Ld?.(),Li+=1,Ud(),it?.dispose(),it?.view.destroy(),it=null}),n.clientToken&&I.initClientSession().then(()=>{if(Rn())return I.reconcileBootConversation({scope:Xp()})}).then(()=>{rr()}).catch(s=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",s)}),(E||n.onSSEEvent)&&I.setSSEEventCallback((s,l)=>{n.onSSEEvent?.(s,l),Ku(s,l)});let Rb=()=>{let s=n.resume??(X?er.getStoredResumableHandle?.():null);s&&typeof n.reconnectStream=="function"&&I.resumeFromHandle(s)};T?T.then(s=>{if(s){if(s.metadata&&(V=ph(s.metadata),be.syncFromMetadata()),s.messages?.length){aa=!0;try{I.hydrateMessages(s.messages)}finally{aa=!1}xd()}s.artifacts?.length&&I.hydrateArtifacts(s.artifacts,s.selectedArtifactId??null),Py(s.draft)}}).catch(s=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",s)}).finally(()=>{Ip=!0,O(),Rb()}):(Py(W),Rb());let UM=()=>{!Le()||ve||!(n.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},qM=(s,l)=>s?l?{refs:[...s.refs,...l.refs],finalize:async()=>{let[f,g]=await Promise.allSettled([s.finalize(),l.finalize()]),v=[];return f.status==="fulfilled"?v.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),g.status==="fulfilled"?v.push(g.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",g.reason),lL(v)}}:s:l,hf=()=>{let l=ie.getInlineMessageFields?.();return l&&l.contentSegments.some(g=>g.kind==="mention")?l.contentSegments:void 0},sr=!1,Ts=null,Gd=()=>{ie.value="",ie.style.height="auto",An(),qi()},yf="data-persona-composer-notice",Sa=null;function VM(s){Gl(s),!(Le()||!at)&&(at.hasAttribute(ii)||(at.setAttribute(yf,""),at.setAttribute("role","status"),at.setAttribute("aria-live","polite"),at.textContent=s,Sa&&clearTimeout(Sa),Sa=setTimeout(()=>{if(Sa=null,!!at?.hasAttribute(yf)&&(at.removeAttribute(yf),at.removeAttribute("role"),at.removeAttribute("aria-live"),u)){let l=I.getStatus();jl(at,Ph(l),n.statusIndicator??{},l)}},4e3)))}function $M(){let s=he.getState().pendingSubmission;s&&(Js(void 0),ie&&(ie.value=s.text,ie.dispatchEvent(new Event("input",{bubbles:!0})),An()),s.options.selectedModelId&&(he.setSelectedModelId(s.options.selectedModelId),Sr?.repaint()),s.options.activeModeIds?.length&&Jl(s.options.activeModeIds),s.options.quote&&Mn(s.options.quote),ie?.focus())}let jM=s=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",s)},Hb=(s={})=>{let l=(s.overrideText??ie?.value??"").trim();return s.resolveInlineCommand&&l?(Rt?.takeInlineCommand(l)??Promise.resolve(null)).then(f=>Wb(s,l,f)):Wb(s,l,null)},Wb=(s,l,f)=>{if(f?.kind==="action"){Gd(),Rt?.clear(),ts();return}let g=f?.kind==="server"?f.mentions:null,v=f?.kind==="prompt"?f.sendText:l,A=s.pending?.contentParts,_=(Ze?.hasAttachments()??!1)||(A?.length??0)>0;if(!RC({text:v,hasAttachments:_,attachmentsReady:Ze?.isReady()??!0,hasMentions:Rt?.hasMentions()??!1,hasServerMentions:!!g,inputDisabled:Ln(),sendDisabled:ys()}))return;let $=I.isStreaming()?rp():"block";if($==="defer-one"&&!s.pending){if(he.getState().pendingSubmission){VM("One message is already queued. Edit or remove it first.");return}zM({intent:s,sendText:v,serverMentions:g});return}let U={text:v,mentionRefs:[...Rt?.getMentionRefs()??[],...g?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:hf(),options:{...he.getState().selectedModelId&&{selectedModelId:he.getState().selectedModelId},...he.getState().activeModeIds.length>0&&{activeModeIds:[...he.getState().activeModeIds]},...he.getState().quote&&{quote:{...he.getState().quote}}},viaVoice:s.viaVoice};s.pending&&(U.options={...s.pending.options},U.contentSegments=s.pending.contentSegments,U.mentionRefs=[...s.pending.mentionRefs],U.viaVoice=s.pending.viaVoice);let j=()=>{if(A?.length)return[...A];if(!Ze?.hasAttachments())return;let ft=[...Ze.getContentParts()];return U.text&&ft.push(an(U.text)),ft};U.contentParts=j();let J=()=>{cs(),UM();let ft=Rt?.collectForSubmit()??null,Gt=qM(ft,g),_t=j();s.consumeDraft!==!1&&Gd();let Pt={selectedModelId:U.options.selectedModelId,activeModeIds:U.options.activeModeIds},io=$==="interrupt";io&&I.cancel(),I.sendMessage(U.text,{contentParts:_t,mentions:Gt??void 0,contentSegments:U.contentSegments,viaVoice:U.viaVoice,composerOptions:Pt,...U.options.quote&&{quote:U.options.quote},...io&&{interrupt:!0}}),Ze?.hasAttachments()&&Ze.clearAttachments(),ft&&Rt?.clear(),ts();let et=he.getState().activeModeIds,lo=bC(et,n.composer?.modes);lo.length!==et.length&&Jl(lo),he.getState().quote&&Mn(void 0),gd(),dp.release(),un()},re=n.composer?.onBeforeSend;if(!re){J();return}let ce=new AbortController;Ts=ce;let Ye=ft=>{if(Ts=null,ft.status==="error"){jM(ft.error);return}ft.status==="proceed"&&J()},ct=HC(re,U,ce.signal);if(!(ct instanceof Promise)){Ye(ct);return}return he.setPreparing(!0),ct.then(Ye).finally(()=>he.setPreparing(!1))};function zM(s){let l=he.getState(),f=Ze?.hasAttachments()??!1,g=f?[...Ze.getContentParts()]:[];f&&s.sendText&&g.push(an(s.sendText));let v=ig({text:s.sendText,contentParts:g.length?g:void 0,mentionRefs:[...Rt?.getMentionRefs()??[],...s.serverMentions?.refs??[]],contentSegments:hf(),options:{...l.selectedModelId&&{selectedModelId:l.selectedModelId},...l.activeModeIds.length>0&&{activeModeIds:[...l.activeModeIds]},...l.quote&&{quote:{...l.quote}}},viaVoice:s.intent.viaVoice});Js(v),s.intent.consumeDraft!==!1&&Gd(),f&&Ze.clearAttachments(),Rt?.clear(),ts(),l.quote&&Mn(void 0),gd(),dp.release(),un(),Gl("Message queued. It sends when the response finishes.")}function KM(){let s=he.getState().pendingSubmission;s&&(Js(void 0),Qd(s.text,{consumeDraft:!1,pending:s}))}function GM(s){if(n.messageActions?.showEdit!==!0)return;let l=I.getMessages().find(f=>f.id===s);!l||!Zf(l)||ds!==s&&(cs(),ds=s,Tr=wC({messageId:s,initialText:l.content,onSave:f=>XM(s,f),onCancel:()=>cs()}),Ot.delete(s),Jo(Te,I.getMessages(),wt),Tr.focus())}function XM(s,l){let f=Tr;if(ds=null,Tr=null,f?.destroy(),Ot.delete(s),!I.resubmitFrom(s,{reason:"edit",replacement:{text:l,mentionRefs:[],options:{}}})){Jo(Te,I.getMessages(),wt);return}ko()}function QM(s){if(I.isStreaming())return;let l=Jf(I.getMessages(),s);l&&(cs(),I.resubmitFrom(l,{reason:"retry"})&&ko())}Zl={regenerate:QM,edit:GM,quote:s=>{let f=I.getMessages().find(g=>g.id===s)?.content?.trim();f&&(Mn({text:f,messageId:s}),ie?.focus())}};let Ui=async s=>{if(!sr){sr=!0;try{await Hb({resolveInlineCommand:!0,...s})}finally{sr=!1}}};function Xd(s){ys()||(Gd(),Qd(s,{consumeDraft:!1}))}let Qd=(s,l)=>{if(sr)return;sr=!0;let f=()=>{sr=!1};try{let g=Hb({...l,overrideText:s});g instanceof Promise?g.finally(f):f()}catch(g){throw f(),g}},YM=s=>{if(s.preventDefault(),I.isStreaming()){I.cancel(),st?.reset(),gt?.update();return}sr||Ui()},JM=()=>n.features?.composerHistory!==!1,bf={...hg},vf=!1,qi=()=>{bf={...hg}},ZM=()=>I.getMessages().filter(s=>s.role==="user").map(s=>s.content??"").filter(s=>s.length>0),eT=s=>{if(!ie)return;vf=!0,ie.value=s,ie.dispatchEvent(new Event("input",{bubbles:!0})),vf=!1;let l=ie.value.length;ie.setSelectionRange(l,l)},tT=s=>{vf||(s.isComposing||Rt?.handleInput(s.inputType??void 0),qi())},oT=()=>({submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:xl(ie)}),nT=s=>{if(ie&&!Ln()&&!(!s.isComposing&&Rt?.handleKeydown(s))){if(JM()&&(s.key==="ArrowUp"||s.key==="ArrowDown")&&!s.shiftKey&&!s.metaKey&&!s.ctrlKey&&!s.altKey&&!s.isComposing){let l=ie.selectionStart===0&&ie.selectionEnd===0,f=ZC({direction:s.key==="ArrowUp"?"up":"down",history:ZM(),currentValue:ie.value,atStart:l,state:bf});if(bf=f.state,f.handled){s.preventDefault(),f.value!==void 0&&eT(f.value);return}}if(oC(s,oT())){if(I.isStreaming()){if(s.preventDefault(),rp()==="block"||sr||ys())return;qi(),Ui();return}if(sr){s.preventDefault();return}if(ys()){s.preventDefault();return}qi(),s.preventDefault(),we.click()}}},Bb=s=>{if(!(s.key!=="Escape"||s.isComposing)&&s.composedPath().includes(de)){if(Ts){Ts.abort(),Ts=null,s.preventDefault(),s.stopImmediatePropagation();return}I.isStreaming()&&(I.cancel(),st?.reset(),gt?.update(),qi(),s.preventDefault(),s.stopImmediatePropagation())}},rT=async s=>{if(n.attachments?.enabled!==!0||!Ze||Ln())return;let l=rL(s.clipboardData);l.length!==0&&(s.preventDefault(),await Ze.handleFiles(l))},nn=null,Hn=!1,wa=null,vt=null,xf=()=>n.voiceRecognition?.completionBehavior==="review";function Es(s){ne?.setAttribute("data-state",s),s==="recording"?aT():Af()}let Ob="--persona-voice-level",Cf=.5,Aa=null,Sf=-1,Yd=0,Db=()=>{let s=[],l=Fo??ne?.parentElement??null;return l&&s.push(l),ke&&s.push(ke),s},wf=s=>{let l=Math.round(Math.max(0,Math.min(1,s))*100)/100;if(l!==Sf){Sf=l;for(let f of Db())f.style.setProperty(Ob,String(l))}},sT=()=>{Sf=-1,Yd=0;for(let s of Db())s.style.removeProperty(Ob)};function aT(){if(Aa!==null)return;if(typeof requestAnimationFrame!="function"){wf(u?I.getVoiceLevel()??Cf:Cf);return}let s=()=>{Aa=requestAnimationFrame(s);let l=u?I.getVoiceLevel():null;if(l===null){wf(Cf);return}Yd+=(l-Yd)*.3,wf(Yd)};Aa=requestAnimationFrame(s)}function Af(){Aa!==null&&(cancelAnimationFrame(Aa),Aa=null),sT()}let _b=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Jd=(s="user")=>{if(Hn||I.isStreaming())return;let l=_b();if(!l)return;nn=new l;let f=n.voiceRecognition??{},g=f.pauseDuration??2e3;nn.continuous=f.provider?.browser?.continuous??!0,nn.interimResults=!0,nn.lang=f.provider?.browser?.language??"en-US";let v=ie.value;nn.onresult=A=>{let _="",$="";for(let j=0;j<A.results.length;j++){let J=A.results[j],re=J[0].transcript;J.isFinal?_+=re+" ":$=re}let U=v+_+$;ie.value=U,An(),wa&&clearTimeout(wa),(_||$)&&(wa=window.setTimeout(()=>{if(ie.value.trim()&&nn&&Hn){if(Wr(),xf())return;Ui({viaVoice:!0})}},g))},nn.onerror=A=>{A.error!=="no-speech"&&Wr()},nn.onend=()=>{if(Hn){let A=ie.value.trim();!xf()&&A&&A!==v.trim()&&Ui({viaVoice:!0}),Wr()}};try{if(nn.start(),Hn=!0,je.active=!0,s!=="system"&&(je.manuallyDeactivated=!1),Jn(s),mn(),un(),ne){let A=n.voiceRecognition??{};vt={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:A.iconName??"mic",iconSize:parseFloat(A.iconSize??"")||bo};let _=A.recordingBackgroundColor,$=A.recordingIconColor,U=A.recordingBorderColor;if(ne.classList.add("persona-voice-recording"),Es("recording"),ne.style.backgroundColor=_??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=$??"var(--persona-voice-recording-indicator, #ffffff)",$){let j=ne.querySelector("svg");j&&j.setAttribute("stroke",$)}U&&(ne.style.borderColor=U),ne.setAttribute("aria-label","Stop voice recognition")}}catch{Wr("system")}},Wr=(s="user")=>{if(Hn){if(Hn=!1,wa&&(clearTimeout(wa),wa=null),nn){try{nn.stop()}catch{}nn=null}if(je.active=!1,Jn(s),mn(),un(),ne){if(ne.classList.remove("persona-voice-recording"),Es("idle"),vt){ne.style.backgroundColor=vt.backgroundColor,ne.style.color=vt.color,ne.style.borderColor=vt.borderColor;let l=ne.querySelector("svg");l&&l.setAttribute("stroke",vt.color||"currentColor"),vt=null}ne.setAttribute("aria-label","Start voice recognition")}}},Mf=()=>{if(!ne||vt)return;let s=n.voiceRecognition??{};vt={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:s.iconName??"mic",iconSize:parseFloat(s.iconSize??"")||bo}},Tf=(s,l)=>{if(!ne)return;let f=ne.querySelector("svg");f&&f.remove();let g=vt?.iconSize??(parseFloat(n.voiceRecognition?.iconSize??"")||bo),v=le(s,g,l,1.5);v&&ne.appendChild(v)},Zd=()=>{ne&&ne.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ma=()=>{if(!ne)return;Mf();let s=n.voiceRecognition??{},l=s.recordingBackgroundColor,f=s.recordingIconColor,g=s.recordingBorderColor;if(Zd(),ne.classList.add("persona-voice-recording"),Es("recording"),ne.style.backgroundColor=l??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let v=ne.querySelector("svg");v&&v.setAttribute("stroke",f)}g&&(ne.style.borderColor=g),ne.setAttribute("aria-label","Stop voice recognition")},iT=()=>{if(!ne)return;Mf();let s=n.voiceRecognition??{},l=I.getVoiceInterruptionMode(),f=s.processingIconName??"loader",g=s.processingIconColor??vt?.color??"",v=s.processingBackgroundColor??vt?.backgroundColor??"",A=s.processingBorderColor??vt?.borderColor??"";Zd(),ne.classList.add("persona-voice-processing"),Es("processing"),ne.style.backgroundColor=v,ne.style.borderColor=A;let _=g||"currentColor";ne.style.color=_,Tf(f,_),ne.setAttribute("aria-label","Processing voice input"),l==="none"&&(ne.style.cursor="default")},lT=()=>{if(!ne)return;Mf();let s=n.voiceRecognition??{},l=I.getVoiceInterruptionMode(),f=l==="cancel"?"square":l==="barge-in"?"mic":"volume-2",g=s.speakingIconName??f,v=s.speakingIconColor??(l==="barge-in"?s.recordingIconColor??vt?.color??"":vt?.color??""),A=s.speakingBackgroundColor??(l==="barge-in"?s.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),_=s.speakingBorderColor??(l==="barge-in"?s.recordingBorderColor??"":vt?.borderColor??"");Zd(),ne.classList.add("persona-voice-speaking"),Es("speaking"),ne.style.backgroundColor=A,ne.style.borderColor=_;let $=v||"currentColor";ne.style.color=$,Tf(g,$);let U=l==="cancel"?"Stop playback and re-record":l==="barge-in"?"Speak to interrupt":"Agent is speaking";ne.setAttribute("aria-label",U),l==="none"&&(ne.style.cursor="default"),l==="barge-in"&&ne.classList.add("persona-voice-recording")},ar=()=>{ne&&(Zd(),Es("idle"),vt&&(ne.style.backgroundColor=vt.backgroundColor??"",ne.style.color=vt.color??"",ne.style.borderColor=vt.borderColor??"",Tf(vt.iconName,vt.color||"currentColor"),vt=null),ne.style.cursor="",ne.setAttribute("aria-label","Start voice recognition"))},Ef=()=>{if(!Ln()){if(Wo(n.voiceRecognition?.provider)){let s=I.getVoiceStatus(),l=I.getVoiceInterruptionMode();if(l==="none"&&(s==="processing"||s==="speaking"))return;if(l==="cancel"&&(s==="processing"||s==="speaking")){I.stopVoicePlayback();return}if(I.isBargeInActive()){I.stopVoicePlayback(),I.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,mn(),Jn("user"),ar()});return}I.toggleVoice().then(()=>{je.active=I.isVoiceActive(),je.manuallyDeactivated=!I.isVoiceActive(),mn(),Jn("user"),I.isVoiceActive()?Ma():ar()});return}if(Hn){let s=ie.value.trim();je.manuallyDeactivated=!0,mn(),Wr("user"),s&&!xf()&&Ui()}else je.manuallyDeactivated=!1,mn(),Jd("user")}};sp=Ef,ne&&fe.push(()=>{Wo(n.voiceRecognition?.provider)?(I.isVoiceActive()&&I.toggleVoice(),ar()):Wr("system")});let dT=C.on("assistant:complete",()=>{he.getState().pendingSubmission&&setTimeout(()=>{I.isStreaming()||KM()},0)});fe.push(dT);let cT=C.on("assistant:complete",()=>{My&&(je.active||je.manuallyDeactivated||My==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(Wo(n.voiceRecognition?.provider)?I.toggleVoice().then(()=>{je.active=I.isVoiceActive(),Jn("auto"),I.isVoiceActive()&&Ma()}):Jd("auto"))},600))});fe.push(cT);let uT=C.on("action:resubmit",()=>{setTimeout(()=>{I&&!I.isStreaming()&&I.continueConversation()},100)});fe.push(uT);let Nb=()=>{pt(!ve,"user")},Tt=null,mo=null;if(pe&&!Le()){let{instance:s,element:l}=jg({config:n,plugins:i,onToggle:Nb});Tt=s,s||(mo=l)}Tt?e.appendChild(Tt.element):mo&&e.appendChild(mo),Ti(),ra(),wd(),Op(),Ei(I.isStreaming()),Ap()||(Uo()==="follow"?kr(!0):hd()),LA(),Pe&&(!pe||Le()?setTimeout(()=>bs(),0):ve&&setTimeout(()=>bs(),200));let Ps=null,Fb=()=>{Ps&&(Ps.disconnect(),Ps.observe(ke),Ps.observe(de))},Vi=()=>{if(Le()){es(),Ti();return}let s=Ct(n),l=n.launcher?.sidebarMode??!1,f=e.ownerDocument.defaultView??window,g=n.launcher?.mobileFullscreen??!0,v=n.launcher?.mobileBreakpoint??640,A=f.innerWidth<=v,_=g&&A&&pe;try{if(_){os(),hi=id();return}let $=!1;so&&(so=!1,os(),$=!0);let U=id();if(!$&&U!==hi&&(os(),$=!0),hi=U,$&&nd(),!pe&&!s){Ce.style.height="",Ce.style.width="";return}if(!l&&!s){let J=n?.launcher?.width??n?.launcherWidth??Ko;Ce.style.width=J,Ce.style.maxWidth=J}ad(),dy()}finally{if(es(),Yl(),Ti(),ve&&pe){let U=(e.ownerDocument.defaultView??window).innerWidth<=(n.launcher?.mobileBreakpoint??640),j=n.launcher?.sidebarMode??!1,J=n.launcher?.mobileFullscreen??!0,re=Ct(n)&&J&&U,ce=j||J&&U&&pe||re;if(ce&&!kn){let Ye=e.getRootNode(),ct=Ye instanceof ShadowRoot?Ye.host:e.closest(".persona-host");ct&&!Pn&&(Pn=Sg(ct,n.launcher?.zIndex??ro)),kn=wg(e.ownerDocument)}else ce||(Pn?.(),Pn=null,kn?.(),kn=null)}}};Vi();let ec=e.ownerDocument.defaultView??window;if(ec.addEventListener("resize",Vi),fe.push(()=>ec.removeEventListener("resize",Vi)),typeof ResizeObserver<"u"){Ps=new ResizeObserver(()=>{Yl()}),Fb(),fe.push(()=>{Ps?.disconnect(),Ps=null});let s=new ResizeObserver(()=>{Nd()});s.observe(de),fe.push(()=>s.disconnect())}ec.addEventListener("resize",Nd),fe.push(()=>ec.removeEventListener("resize",Nd)),$o=oe.scrollTop;let Ub=Un(oe),qb=()=>{let s=oe.scrollTop,l=Un(oe),f=l<Ub;if(Ub=l,!Cr()){$o=s,$t();return}let{action:g,nextLastScrollTop:v}=iS({following:Vo.isFollowing(),currentScrollTop:s,lastScrollTop:$o,nearBottom:_s(oe,Qn),userScrollThreshold:TA,isAutoScrolling:Eo||dd||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if($o=v,g==="resume"){yd()||Po();return}g==="pause"&&Ci()};if(oe.addEventListener("scroll",qb,{passive:!0}),fe.push(()=>oe.removeEventListener("scroll",qb)),typeof ResizeObserver<"u"){let s=new ResizeObserver(()=>{DA(),Hf(Te)});s.observe(Te),s.observe(oe),fe.push(()=>s.disconnect())}let Vb=()=>{Cr()&&Vo.isFollowing()&&yd()&&Ci()},$b=oe.ownerDocument;$b.addEventListener("selectionchange",Vb),fe.push(()=>{$b.removeEventListener("selectionchange",Vb)});let pT=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),jb=s=>{pT.has(s.key)&&(ms(),Lh()&&Cr()&&Vo.isFollowing()&&Ci())},zb=s=>{s.target?.closest("a, button, [tabindex], input, textarea, select")&&(ms(),Lh()&&Cr()&&Vo.isFollowing()&&Ci())};oe.addEventListener("keydown",jb),oe.addEventListener("focusin",zb),fe.push(()=>{oe.removeEventListener("keydown",jb),oe.removeEventListener("focusin",zb)});let Kb=s=>{if(s.deltaY!==0&&ms(),!Cr())return;let l=lS({following:Vo.isFollowing(),deltaY:s.deltaY,nearBottom:_s(oe,Qn),resumeWhenNearBottom:!0});l==="pause"?Ci():l==="resume"&&!yd()&&Po()};oe.addEventListener("wheel",Kb,{passive:!0}),oe.addEventListener("touchmove",ms,{passive:!0}),oe.addEventListener("pointerdown",ms,{passive:!0}),fe.push(()=>{oe.removeEventListener("touchmove",ms),oe.removeEventListener("pointerdown",ms)}),fe.push(()=>oe.removeEventListener("wheel",Kb)),Bt.addEventListener("click",()=>{gn(),oe.scrollTop=oe.scrollHeight,$o=oe.scrollTop,Po(),kr(!0),$t()}),fe.push(()=>Bt.remove()),fe.push(()=>{Ly(),gn()});let Gb=()=>{Ne&&(as&&(Ne.removeEventListener("click",as),as=null),qe()?(Ne.style.display="",as=()=>{pt(!1,"user")},Ne.addEventListener("click",as)):Ne.style.display="none")};Gb(),(()=>{let{clearChatButton:s}=Oe;s&&s.addEventListener("click",()=>{if(Rn()){ff({focusComposer:!0}).catch(f=>{n.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}I.clearMessages(),Ot.clear(),Po(),Vr(Oe.composerOverlay);try{localStorage.removeItem(ai),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ai}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ai)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),N?.clear&&fd(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),V={},be.syncFromMetadata(),Ze?.clearAttachments(),gd(),Js(void 0),Mn(void 0),cs(),We?.clear(),st?.reset(),gt?.update()})})();let Xb=[["keydown",nT],["input",tT],["input",An],["input",ts],["keyup",ts],["paste",rT],["focus",mA]],Qb=s=>{if(s)for(let[l,f]of Xb)ot?.addListener(s,l,f)},fT=s=>{if(s)for(let[l,f]of Xb)ot?.removeListener(s,l,f)},Yb=()=>{ot&&(ot.addListener(ot.form,"submit",YM),ot.addListener(ot.footer,"click",ts),Qb(ie),ne&&ot.addListener(ne,"click",Ef))};Yb();let Jb=()=>{Rt?.onComposerSwap((s,l)=>{fT(l),ie=s,ot&&(ot.input=s),Qb(s),ip(),kp(),An()})};Jb();let Pf=!1;function Zb(){if(!Pf){Pf=!0;try{let s=ie?.value??"",l=ke.ownerDocument??document,f=ie?l.activeElement===ie:!1;Af(),ot?.destroy(),ot=null,Rt?.destroy(),Rt=null;let g=null,v=()=>(g=Le()?vu({config:n}):Vs({config:n}),g.footer),A=Fh(v)??v();_o.replaceComposer(A),ke=_o.composer.footer;let _=g!==null&&A===g.footer;ea=!_,kh=_?g.setSendButtonMode:()=>{},Nh(ke),qh(ke),Vh(),$h(),jh(),Jb(),zh(),lp(),Kh(),Yb();let $=ss.indexOf(Xn);Xn.destroy(),Xn=Wl(vr),$>=0&&(ss[$]=Xn),ie&&(ie.value=s),An(),ts(),wd(),ra(),Ei(I.isStreaming()),je.active&&Es("recording"),os(),Fb(),es(),un(),Cd(),f&&ie?.focus()}finally{Pf=!1}}}let $i=e.ownerDocument??document;$i.addEventListener("keydown",Bb,!0);let ev=()=>{xp()},tv=()=>{$i.visibilityState==="hidden"&&xp()};typeof window<"u"&&(window.addEventListener("pagehide",ev),$i.addEventListener("visibilitychange",tv),fe.push(()=>{window.removeEventListener("pagehide",ev),$i.removeEventListener("visibilitychange",tv)}));let ov="persona-attachment-drop-active",ji=0,kf=()=>{ji=0,de.classList.remove(ov)},Ta=()=>n.attachments?.enabled===!0&&Ze!==null&&!Ln(),nv=s=>{!qu(s.dataTransfer)||!Ta()||(ji++,ji===1&&de.classList.add(ov))},rv=s=>{!qu(s.dataTransfer)||!Ta()||(ji--,ji<=0&&kf())},sv=s=>{!qu(s.dataTransfer)||!Ta()||(s.preventDefault(),s.dataTransfer.dropEffect="copy")},av=s=>{if(!qu(s.dataTransfer)||!Ta())return;s.preventDefault(),s.stopPropagation(),kf();let l=Array.from(s.dataTransfer.files??[]);l.length!==0&&Ze.handleFiles(l)},Br=!0;de.addEventListener("dragenter",nv,Br),de.addEventListener("dragleave",rv,Br),e.addEventListener("dragover",sv,Br),e.addEventListener("drop",av,Br);let tc=e.ownerDocument,iv=s=>{Ta()&&s.preventDefault()},lv=s=>{Ta()&&s.preventDefault()};tc.addEventListener("dragover",iv),tc.addEventListener("drop",lv),fe.push(()=>{ot?.destroy(),ot=null,Af(),Tn?.destroy(),Tn=null,Kn?.destroy(),Kn=null,wr?.destroy(),wr=null,Ar?.destroy(),Ar=null,Sr=null,np=null,xp(),xi.destroy(),Sa&&clearTimeout(Sa),cs(),Ts?.abort(),Ts=null,Ze?.destroy(),Ze=null,he.destroy(),$i.removeEventListener("keydown",Bb,!0),Rt?.destroy()}),fe.push(()=>{de.removeEventListener("dragenter",nv,Br),de.removeEventListener("dragleave",rv,Br),e.removeEventListener("dragover",sv,Br),e.removeEventListener("drop",av,Br),tc.removeEventListener("dragover",iv),tc.removeEventListener("drop",lv),kf()}),fe.push(()=>{I.cancel()}),Tt?fe.push(()=>{Tt?.destroy()}):mo&&fe.push(()=>{mo?.remove()});let Et={update(s){let l=n.toolCall,f=n.messageActions,g=n.layout?.messages,v=n.colorScheme,A=n.loadingIndicator,_=n.iterationDisplay,$=n.features?.showReasoning,U=n.features?.showToolCalls,j=n.features?.toolCallDisplay,J=n.features?.reasoningDisplay,re=n.features?.streamAnimation?.type,ce=n.features?.history?.enabled===!0,Ye=n.features?.history?.provider,ct=n.getIdentityProof,ft=n.clientToken,Gt=n.contextMentions;n=Wu({...n,features:a},s),a=n.features,n=_l(n),r(),mp(),Ds(e,n),Ol(e,n),Dl(e,n),jn(),fn(),n.colorScheme!==v&&cy();let _t=Nl.getForInstance(n.plugins);i.length=0,i.push(..._t),db(),pe=n.launcher?.enabled??!0,yt=n.launcher?.autoExpand??!1,$n=n.features?.showReasoning??!0,z=n.features?.showToolCalls??!0,F=n.features?.scrollToBottom??{};let Pt=Uo();K=n.features?.scrollBehavior??{},Pt!==Uo()&&(gn(),Po()),Ay(),Hh(),$t();let io=E;if(E=n.features?.showEventStreamToggle??!1,E&&!io){if(We||($l(),I.setSSEEventCallback((Z,ze)=>{n.onSSEEvent?.(Z,ze),Ku(Z,ze)})),!tt&&Ae){let Z=n.features?.eventStream?.classNames,ze="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"+(Z?.toggleButton?" "+Z.toggleButton:"");tt=R("button",ze),tt.style.width="28px",tt.style.height="28px",tt.style.color=xo.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Xe=Ut(_a,"18px","currentColor",1.5);Xe&&tt.appendChild(Xe);let nt=Oe.clearChatButtonWrapper,xt=Oe.closeButtonWrapper,oo=nt||xt;oo&&oo.parentNode===Ae?Ae.insertBefore(tt,oo):Ae.appendChild(tt),tt.addEventListener("click",()=>{zt?Zs():ap()})}}else!E&&io&&(Zs(),tt&&(tt.remove(),tt=null),We?.clear(),Me?.destroy(),We=null,Me=null,st?.reset(),st=null,Ke=null);if(n.launcher?.enabled===!1&&Tt&&(Tt.destroy(),Tt=null),n.launcher?.enabled===!1&&mo&&(mo.remove(),mo=null),n.launcher?.enabled!==!1&&!Tt&&!mo){let{instance:Z,element:ze}=jg({config:n,plugins:i,onToggle:Nb});Tt=Z,Z||(mo=ze),e.appendChild(ze)}Tt&&Tt.update(n),Fi(),Jr&&n.launcher?.subtitle!==void 0&&(Jr.textContent=n.launcher.subtitle);let et=n.layout?.header;if(et?.layout!==Je&&Ae){let Z=et?Qa(n,et,{showClose:qe(),onClose:()=>pt(!1,"user")}):gr({config:n,showClose:qe(),onClose:()=>pt(!1,"user")});_o.replaceHeader(Z),Ae=_o.header.element,Mt=_o.header.iconHolder,xr=_o.header.headerTitle,Jr=_o.header.headerSubtitle,Ne=_o.header.closeButton,Je=et?.layout,Fi()}else if(et){if(Mt&&(Mt.style.display=et.showIcon===!1?"none":""),xr&&(xr.style.display=et.showTitle===!1?"none":""),Jr&&(Jr.style.display=et.showSubtitle===!1?"none":""),Ne){let Z=qe()&&et.showCloseButton!==!1;Ne.style.display=Z?"":"none"}if(Oe.clearChatButtonWrapper){let Z=et.showClearChat;if(Z!==void 0){Oe.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:ze}=Oe;ze&&!ze.classList.contains("persona-absolute")&&(Z?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}}let Wn=n.layout?.showHeader!==!1;Ae&&(Ae.style.display=Wn?"":"none");let ir=n.layout?.showFooter!==!1;ke&&(ke.style.display=ir?"":"none"),es(),$t(),pe!==Ue?pe?pt(yt,"auto"):(ve=!0,Ti()):yt!==q&&pt(yt,"auto"),q=yt,Ue=pe,Vi(),Gb();let ks=JSON.stringify(n.toolCall)!==JSON.stringify(l),yn=JSON.stringify(n.messageActions)!==JSON.stringify(f),eo=JSON.stringify(n.layout?.messages)!==JSON.stringify(g),bn=n.loadingIndicator?.render!==A?.render||n.loadingIndicator?.renderIdle!==A?.renderIdle||n.loadingIndicator?.showBubble!==A?.showBubble,Ea=n.iterationDisplay!==_,B=(n.features?.showReasoning??!0)!==($??!0)||(n.features?.showToolCalls??!0)!==(U??!0)||JSON.stringify(n.features?.toolCallDisplay)!==JSON.stringify(j)||JSON.stringify(n.features?.reasoningDisplay)!==JSON.stringify(J);(ks||yn||eo||bn||Ea||B)&&I&&(us++,Jo(Te,I.getMessages(),wt));let Se=n.features?.streamAnimation?.type;if(Se!==re&&Se&&Se!=="none"){let Z=hp(Se,n.features?.streamAnimation?.plugins);Z&&Il(Z,e)}let se=n.launcher??{},kt=se.headerIconHidden??!1,Nt=n.layout?.header?.showIcon,to=kt||Nt===!1,Ft=se.headerIconName,jt=se.headerIconSize??"48px";if(Mt){let Z=Ae,ze=Z?.querySelector(".persona-flex-col");if(to)Mt.style.display="none",Z&&ze&&!Z.contains(ze)&&Z.insertBefore(ze,Z.firstChild);else{if(Mt.style.display="",Mt.style.height=jt,Mt.style.width=jt,Z&&ze&&(Z.contains(Mt)?Mt.nextSibling!==ze&&(Mt.remove(),Z.insertBefore(Mt,ze)):Z.insertBefore(Mt,ze)),Ft){let nt=parseFloat(jt)||24,xt=le(Ft,nt*.6,"currentColor",1);xt?Mt.replaceChildren(xt):Mt.textContent=se.agentIconText??"\u{1F4AC}"}else if(se.iconUrl){let nt=Mt.querySelector("img");if(nt)nt.src=se.iconUrl,nt.style.height=jt,nt.style.width=jt;else{let xt=document.createElement("img");xt.src=se.iconUrl,xt.alt="",xt.className="persona-rounded-xl persona-object-cover",xt.style.height=jt,xt.style.width=jt,Mt.replaceChildren(xt)}}else{let nt=Mt.querySelector("svg"),xt=Mt.querySelector("img");(nt||xt)&&Mt.replaceChildren(),Mt.textContent=se.agentIconText??"\u{1F4AC}"}let Xe=Mt.querySelector("img");Xe&&(Xe.style.height=jt,Xe.style.width=jt)}}let Lt=n.layout?.header?.showTitle,co=n.layout?.header?.showSubtitle;if(xr&&(xr.style.display=Lt===!1?"none":""),Jr&&(Jr.style.display=co===!1?"none":""),Ne){let Z=qe()&&n.layout?.header?.showCloseButton!==!1;if(Ne.style.display=Z?"":"none",!Le()){let Xt=se.closeButtonSize??"";Ne.style.height=Xt,Ne.style.width=Xt,Ne.style.minWidth=Xt,Ne.style.minHeight=Xt}let ze=se.closeButtonPlacement??"inline",{closeButtonWrapper:Xe}=Oe,nt=ze==="top-right",xt=Xe?.classList.contains("persona-absolute");if(Xe&&nt!==xt)if(Xe.remove(),nt){Xe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Xt=Ri??de;Xt.style.position="relative",Xt.appendChild(Xe)}else{let Xt=se.clearChat?.placement??"inline",Qt=se.clearChat?.enabled??!0;Xe.className=Qt&&Xt==="inline"?"":"persona-ml-auto",Ae&&Ae.appendChild(Xe)}if(Ne.style.color=se.closeButtonColor||xo.actionIconColor,se.closeButtonBackgroundColor?(Ne.style.backgroundColor=se.closeButtonBackgroundColor,Ne.classList.remove("hover:persona-bg-gray-100")):(Ne.style.backgroundColor="",Ne.classList.add("hover:persona-bg-gray-100")),se.closeButtonBorderWidth||se.closeButtonBorderColor){let Xt=se.closeButtonBorderWidth||"0px",Qt=se.closeButtonBorderColor||"transparent";Ne.style.border=`${Xt} solid ${Qt}`,Ne.classList.remove("persona-border-none")}else Ne.style.border="",Ne.classList.add("persona-border-none");se.closeButtonBorderRadius?(Ne.style.borderRadius=se.closeButtonBorderRadius,Ne.classList.remove("persona-rounded-full")):(Ne.style.borderRadius="",Ne.classList.add("persona-rounded-full")),se.closeButtonPaddingX?(Ne.style.paddingLeft=se.closeButtonPaddingX,Ne.style.paddingRight=se.closeButtonPaddingX):(Ne.style.paddingLeft="",Ne.style.paddingRight=""),se.closeButtonPaddingY?(Ne.style.paddingTop=se.closeButtonPaddingY,Ne.style.paddingBottom=se.closeButtonPaddingY):(Ne.style.paddingTop="",Ne.style.paddingBottom=""),hu(Ne,se.closeButtonIconName??"x",{iconSize:Le()?Ug:void 0,iconText:se.closeButtonIconText??"\xD7"});let oo=se.closeButtonTooltipText??"Close chat",vn=se.closeButtonShowTooltip??!0;Ne.setAttribute("aria-label",oo),Xe&&Jt({anchor:Ne,trigger:Xe,text:()=>Ne?.getAttribute("aria-label")??oo,enabled:vn})}let{clearChatButton:Ie,clearChatButtonWrapper:De}=Oe;if(Ie){let Z=se.clearChat??{},ze=Z.enabled??!0,Xe=n.layout?.header?.showClearChat,nt=Xe!==void 0?Xe:ze,xt=Z.placement??"inline";if(De){De.style.display=nt?"":"none";let{closeButtonWrapper:oo}=Oe;!Le()&&oo&&!oo.classList.contains("persona-absolute")&&(nt?oo.classList.remove("persona-ml-auto"):oo.classList.add("persona-ml-auto"));let vn=xt==="top-right",Xt=De.classList.contains("persona-absolute");if(!Le()&&vn!==Xt&&nt){if(De.remove(),vn){De.className="persona-absolute persona-top-4 persona-z-50",De.style.right="48px";let Bn=Ri??de;Bn.style.position="relative",Bn.appendChild(De)}else{De.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",De.style.right="";let Bn=Oe.closeButtonWrapper;Ae&&Bn&&Bn.parentElement===Ae?Ae.insertBefore(De,Bn):Ae&&Ae.appendChild(De)}let Qt=Oe.closeButtonWrapper;Qt&&!Qt.classList.contains("persona-absolute")&&(vn?Qt.classList.add("persona-ml-auto"):Qt.classList.remove("persona-ml-auto"))}}if(nt){if(!Le()){let Qt=Z.size??"";Ie.style.height=Qt,Ie.style.width=Qt,Ie.style.minWidth=Qt,Ie.style.minHeight=Qt}let oo=Z.iconColor??"";if(Ie.style.color=oo||xo.actionIconColor,hu(Ie,Z.iconName??"refresh-cw",{iconSize:Le()?qg:void 0}),Z.backgroundColor?(Ie.style.backgroundColor=Z.backgroundColor,Ie.classList.remove("hover:persona-bg-gray-100")):(Ie.style.backgroundColor="",Ie.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let Qt=Z.borderWidth||"0px",Bn=Z.borderColor||"transparent";Ie.style.border=`${Qt} solid ${Bn}`,Ie.classList.remove("persona-border-none")}else Ie.style.border="",Ie.classList.add("persona-border-none");Z.borderRadius?(Ie.style.borderRadius=Z.borderRadius,Ie.classList.remove("persona-rounded-full")):(Ie.style.borderRadius="",Ie.classList.add("persona-rounded-full")),Z.paddingX?(Ie.style.paddingLeft=Z.paddingX,Ie.style.paddingRight=Z.paddingX):(Ie.style.paddingLeft="",Ie.style.paddingRight=""),Z.paddingY?(Ie.style.paddingTop=Z.paddingY,Ie.style.paddingBottom=Z.paddingY):(Ie.style.paddingTop="",Ie.style.paddingBottom="");let vn=Z.tooltipText??"Clear chat",Xt=Z.showTooltip??!0;Ie.setAttribute("aria-label",vn),De&&Jt({anchor:Ie,trigger:De,text:()=>Ie?.getAttribute("aria-label")??vn,enabled:Xt})}}let xe=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Fl],uo=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ks.message,Ks.messageAndClick];be=Ul({parsers:xe,handlers:uo,getSessionMetadata:ue,updateSessionMetadata:ae,emit:C.emit,documentRef:typeof document<"u"?document:null}),wt=Lw(n,be,Vn),tM(),I.updateConfig(n),(n.features?.history?.enabled===!0!==ce||n.features?.history?.provider!==Ye||n.getIdentityProof!==ct||n.clientToken!==ft)&&(Lo({restoreFocus:!1}),tb()),Hr(),Nd(),Jo(Te,I.getMessages(),wt),ra(),wd(),ZA(),Ei(I.isStreaming()),Gt!==n.contextMentions&&Zb();let Or=n.voiceRecognition?.enabled===!0,Io=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Ro=Wo(n.voiceRecognition?.provider);if(Or&&(Io||Ro))if(!ne||!Fo){let Z=ja(n);if(Z){ne=Z.button,Fo=Z.wrapper;let ze=wn&&wn.parentElement===zl?wn:null;zl?zl.insertBefore(Fo,ze):cn?.appendChild(Fo),ot&&(ot.micButton=ne),ot?.addListener(ne,"click",Ef),ne.disabled=Ln()||I.isStreaming()&&!Ep()}}else{let Z=n.voiceRecognition??{},ze=n.sendButton??{},Xe=Z.iconName??"mic",nt=Z.iconSize,xt=parseFloat(nt??"")||bo;ne.classList.add(Go),ne.classList.toggle(xn,!nt),ne.style.width=nt??"",ne.style.height=nt??"",ne.style.minWidth=nt??"",ne.style.minHeight=nt??"";let oo=Z.iconColor??ze.textColor;ne.innerHTML="";let vn=le(Xe,xt,oo||"currentColor",1.5);vn?ne.appendChild(vn):ne.textContent="\u{1F3A4}";let Xt=Z.backgroundColor??ze.backgroundColor;Xt?ne.style.backgroundColor=Xt:ne.style.backgroundColor="",oo?ne.style.color=oo:ne.style.color="var(--persona-text, #111827)",Z.borderWidth?(ne.style.borderWidth=Z.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),Z.borderColor?ne.style.borderColor=Z.borderColor:ne.style.borderColor="",Z.paddingX?(ne.style.paddingLeft=Z.paddingX,ne.style.paddingRight=Z.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),Z.paddingY?(ne.style.paddingTop=Z.paddingY,ne.style.paddingBottom=Z.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let Qt=Z.tooltipText??"Start voice recognition",Bn=Z.showTooltip??!1;ne.setAttribute("aria-label",Qt),Fo&&Jt({anchor:ne,trigger:Fo,text:()=>ne?.getAttribute("aria-label")??Qt,enabled:Bn}),Fo.style.display="",ne.disabled=Ln()||I.isStreaming()&&!Ep()}else ne&&Fo&&(Fo.style.display="none",Wo(n.voiceRecognition?.provider)?I.isVoiceActive()&&I.toggleVoice():Hn&&Wr());if(n.attachments?.enabled===!0){if(!Mo||!St){let Z=n.attachments??{};To||(To=R("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),To.style.display="none",(ie.parentElement??cn).insertBefore(To,ie)),ht||(ht=document.createElement("input"),ht.type="file",ht.accept=(Z.allowedTypes??mr).join(","),ht.multiple=(Z.maxFiles??4)>1,ht.style.display="none",ht.setAttribute("aria-label","Attach files"),(ie.parentElement??cn).insertBefore(ht,ie)),Mo=R("div","persona-send-button-wrapper"),St=R("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Go} ${xn}`),St.type="button",St.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let ze=Z.buttonIconName??"paperclip";St.style.fontSize="18px",St.style.lineHeight="1";let Xe=le(ze,bo,"currentColor",1.5);Xe?St.appendChild(Xe):St.textContent="\u{1F4CE}",St.addEventListener("click",xt=>{xt.preventDefault(),ht?.click()}),Mo.appendChild(St);let nt=Z.buttonTooltipText??"Attach file";Jt({anchor:St,trigger:Mo,text:()=>St?.getAttribute("aria-label")??nt}),Yu?Yu.append(Mo):cn.appendChild(Mo),ot&&(ot.attachmentButton=St,ot.attachmentInput=ht??void 0,ot.attachmentPreviews=To??void 0),!Ze&&ht&&To&&(Ze=Os.fromConfig(Z,Wh),Ze.setPreviewsContainer(To),ot?.addListener(ht,"change",async()=>{Ze&&ht?.files&&(await Ze.handleFileSelect(ht.files),ht.value="")}))}else{Mo.style.display="";let Z=n.attachments??{};ht&&(ht.accept=(Z.allowedTypes??mr).join(","),ht.multiple=(Z.maxFiles??4)>1),Ze&&Ze.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(de.querySelector(".persona-attachment-drop-overlay")?.remove(),de.appendChild(Iw(n.attachments?.dropOverlay)),St){let Z=n.attachments??{},ze=Z.buttonTooltipText??"Attach file";St.setAttribute("aria-label",ze),St.textContent="";let Xe=le(Z.buttonIconName??"paperclip",bo,"currentColor",1.5);Xe?St.appendChild(Xe):St.textContent="\u{1F4CE}",Mo&&Jt({anchor:St,trigger:Mo,text:()=>St?.getAttribute("aria-label")??ze})}}else Mo&&(Mo.style.display="none"),Ze&&Ze.clearAttachments(),de.querySelector(".persona-attachment-drop-overlay")?.remove();let Be=n.sendButton??{},lr=Be.useIcon??!1,Ht=Be.iconText??"\u2191",Ho=Be.iconName,Ki=Be.tooltipText??"Send message",hT=Be.showTooltip??!1,Gi=Be.size,yT=parseFloat(Gi??"")||Jm,oc=Be.backgroundColor,Xi=Be.textColor;if(lr){if(we.style.width=Gi??"",we.style.height=Gi??"",we.style.minWidth=Gi??"",we.style.minHeight=Gi??"",we.style.fontSize="18px",we.style.lineHeight="1",Xi?we.style.color=Xi:we.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!I.isStreaming())if(we.innerHTML="",Ho){let Z=parseFloat(Be.iconSize??"")||Math.round(yT*.5),ze=Xi?.trim()||"currentColor",Xe=Be.iconStrokeWidth??2,nt=le(Ho,Z,ze,Xe),xt=le(Be.stopIconName??"square",Z,ze,Xe);nt&&xt?we.appendChild(Zm(nt,xt)):nt?we.appendChild(nt):we.textContent=Ht}else we.textContent=Ht;we.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Go}`,oc?(we.style.backgroundColor=oc,we.classList.remove("persona-bg-persona-primary")):(we.style.backgroundColor="",we.classList.add("persona-bg-persona-primary"))}else we.textContent=n.copy?.sendButtonLabel??"Send",we.style.width="",we.style.height="",we.style.minWidth="",we.style.minHeight="",we.style.fontSize="",we.style.lineHeight="",we.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",oc?(we.style.backgroundColor=oc,we.classList.remove("persona-bg-persona-accent")):we.classList.add("persona-bg-persona-accent"),Xi?we.style.color=Xi:we.classList.add("persona-text-white");Be.borderWidth?(we.style.borderWidth=Be.borderWidth,we.style.borderStyle="solid"):(we.style.borderWidth="",we.style.borderStyle=""),Be.borderColor?we.style.borderColor=Be.borderColor:we.style.borderColor="",Be.paddingX?(we.style.paddingLeft=Be.paddingX,we.style.paddingRight=Be.paddingX):(we.style.paddingLeft="",we.style.paddingRight=""),Be.paddingY?(we.style.paddingTop=Be.paddingY,we.style.paddingBottom=Be.paddingY):(we.style.paddingTop="",we.style.paddingBottom=""),I.isStreaming()||we.setAttribute("aria-label",Ki),Cd(),wn&&Jt({anchor:we,trigger:wn,text:()=>we.getAttribute("aria-label")??Ki,enabled:hT}),Xh();let dv=ou(he.getState().activeModeIds,n.composer?.modes);he.setActiveModeIds(dv),Qs().length>0!==!!Kn&&lp(),Kn?.render(dv,Qs());for(let Z of[...Ys.keys()])tu(Z,n.composer?.modeGroups)||Ys.delete(Z);Ys.forEach(Z=>Z.repaint()),Sr?.repaint(),Tn?.resolve();let nc=Gr(n,Le());if(gp(),nc){Te.style.maxWidth=nc,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",No.style.maxWidth=nc,No.style.marginLeft="auto",No.style.marginRight="auto",No.style.width="100%";for(let Z of[cn,vr,To,at])Z&&(Z.style.maxWidth=nc,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{Te.style.maxWidth="",Te.style.marginLeft="",Te.style.marginRight="",Te.style.width="",No.style.maxWidth="",No.style.marginLeft="",No.style.marginRight="",No.style.width="";for(let Z of[cn,vr,To,at])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Dr=n.statusIndicator??{},bT=Dr.visible??!0;if(at.style.display=bT?"":"none",I){let Z=I.getStatus();jl(at,(Xe=>Xe==="idle"?Dr.idleText??qt.idle:Xe==="connecting"?Dr.connectingText??qt.connecting:Xe==="connected"?Dr.connectedText??qt.connected:Xe==="error"?Dr.errorText??qt.error:qt[Xe])(Z),Dr,Z)}at.classList.remove("persona-text-left","persona-text-center","persona-text-right");let vT=Dr.align==="left"?"persona-text-left":Dr.align==="center"?"persona-text-center":"persona-text-right";at.classList.add(vT),ip(),kp(),un(),Gu()},open(){qe()&&pt(!0,"api")},close(){qe()&&pt(!1,"api")},toggle(){qe()&&pt(!ve,"api")},reconnect(){I.reconnectNow()},clearChat(){Gn=!1,I.clearMessages(),Ot.clear(),Po();try{localStorage.removeItem(ai),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ai}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ai)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let s=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(s),N?.clear&&fd(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),V={},be.syncFromMetadata(),Ze?.clearAttachments(),gd(),Js(void 0),Mn(void 0),cs(),We?.clear(),st?.reset(),gt?.update()},setMessage(s){return!ie||I.isStreaming()||Ln()?!1:(!ve&&qe()&&pt(!0,"system"),ie.value=s,ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(s){if(I.isStreaming()||ys())return!1;let l=s?.trim()||ie.value.trim();return l?(!ve&&qe()&&pt(!0,"system"),ie.value="",ie.style.height="auto",An(),Qd(l,{consumeDraft:!1}),!0):!1},getComposerState(){return he.getState()},setQuote(s){let l=s?.text?.trim();l&&Mn({...s,text:l})},clearQuote(){Mn(void 0)},startVoiceRecognition(){return I.isStreaming()?!1:Wo(n.voiceRecognition?.provider)?(I.isVoiceActive()||I.isBargeInActive()||(!ve&&qe()&&pt(!0,"system"),je.manuallyDeactivated=!1,mn(),I.toggleVoice().then(()=>{je.active=I.isVoiceActive(),Jn("user"),I.isVoiceActive()&&Ma()})),!0):Hn?!0:_b()?(!ve&&qe()&&pt(!0,"system"),je.manuallyDeactivated=!1,mn(),Jd("user"),!0):!1},stopVoiceRecognition(){return Wo(n.voiceRecognition?.provider)?!I.isVoiceActive()&&!I.isBargeInActive()?!1:((I.isBargeInActive()?I.deactivateBargeIn():I.toggleVoice()).then(()=>{je.active=!1,je.manuallyDeactivated=!0,mn(),Jn("user"),ar()}),!0):Hn?(je.manuallyDeactivated=!0,mn(),Wr("user"),!0):!1},injectMessage(s){return!ve&&qe()&&pt(!0,"system"),I.injectMessage(s)},injectAssistantMessage(s){!ve&&qe()&&pt(!0,"system");let l=I.injectAssistantMessage(s);return po&&(po=!1,dn&&(clearTimeout(dn),dn=null),setTimeout(()=>{I&&!I.isStreaming()&&I.continueConversation()},100)),l},injectUserMessage(s){return!ve&&qe()&&pt(!0,"system"),I.injectUserMessage(s)},injectSystemMessage(s){return!ve&&qe()&&pt(!0,"system"),I.injectSystemMessage(s)},injectMessageBatch(s){return!ve&&qe()&&pt(!0,"system"),I.injectMessageBatch(s)},injectComponentDirective(s){return!ve&&qe()&&pt(!0,"system"),I.injectComponentDirective(s)},injectTestMessage(s){!ve&&qe()&&pt(!0,"system"),I.injectTestEvent(s)},async connectStream(s,l){return I.connectStream(s,l)},__pushEventStreamEvent(s){E&&($l(),Ku(s.type,s.payload))},showEventStream(){E&&ap()},hideEventStream(){zt&&Zs()},isEventStreamVisible(){return zt},listConversations(s){return I.listConversations(s)},getActiveConversationId(){return I.getActiveConversationId()},openConversation(s,l){return pf(s,{focusComposer:l?.focus===!0})},startNewConversation(s){return ff({focusComposer:s?.focus===!0})},deleteConversation(s){return Eb(s)},renameConversation(s,l){return mf(s,{title:l})},setConversationStarred(s,l){return mf(s,{starred:l})},clearConversationHistory(s){return Pb(s)},resetHistoryIdentity(){return kb()},async getVisitorToken(){let s=Zo;if(!s)return null;let l=await s.get();return s===Zo?l:null},getHistoryIdentityStatus(){return jo?jo.getIdentityStatus():Gp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(s){return Ni({...s?.returnSurface?{returnSurface:s.returnSurface}:{},...s?.focus!==void 0?{focus:s.focus}:{}})},hideHistory(s){Lo(s?.restoreFocus!==void 0?{restoreFocus:s.restoreFocus}:void 0)},isHistoryVisible(){return At},showArtifacts(){So(n)&&(Gn=!1,ta=!0,fn(),$e?.setMobileOpen(!0))},hideArtifacts(){So(n)&&(Gn=!0,fn())},upsertArtifact(s){return So(n)?(Dn(n.features?.artifacts,{artifactType:s.artifactType,...s.artifactType==="markdown"&&s.file?{file:s.file}:{},...s.presentation?{presentation:s.presentation}:{}})==="panel"&&(Gn=!1,ta=!0),I.upsertArtifact(s)):null},selectArtifact(s){So(n)&&I.selectArtifact(s)},clearArtifacts(){So(n)&&I.clearArtifacts()},getArtifacts(){return I?.getArtifacts()??[]},getSelectedArtifactId(){return I?.getSelectedArtifactId()??null},focusInput(){return pe&&!ve&&!Le()||!ie?!1:(ie.focus(),!0)},async resolveApproval(s,l,f){let v=I.getMessages().find(A=>A.variant==="approval"&&A.approval?.id===s);if(!v?.approval)throw new Error(`Approval not found: ${s}`);if(v.approval.toolType==="webmcp"){I.resolveWebMcpApproval(v.id,l);return}return I.resolveApproval(v.approval,l,f)},setFollowUpSuggestions(s){AA(s)},clearFollowUpSuggestions(){wy()},getMessages(){return I.getMessages()},getStatus(){return I.getStatus()},getPersistentMetadata(){return{...V}},updatePersistentMetadata(s){ae(s)},on(s,l){return C.on(s,l)},off(s,l){C.off(s,l)},isOpen(){return qe()&&ve},isVoiceActive(){return je.active},toggleReadAloud(s){I.toggleReadAloud(s)},stopReadAloud(){I.stopSpeaking()},getReadAloudState(s){return I.getReadAloudState(s)},onReadAloudChange(s){return I.onReadAloudChange(s)},getState(){return{open:qe()&&ve,launcherEnabled:pe,voiceActive:je.active,streaming:I.isStreaming()}},showCSATFeedback(s){!ve&&qe()&&pt(!0,"system");let l=Te.querySelector(".persona-feedback-container");l&&l.remove();let f=Fu({onSubmit:async(g,v)=>{I.isClientTokenMode()&&await I.submitCSATFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});Te.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(s){!ve&&qe()&&pt(!0,"system");let l=Te.querySelector(".persona-feedback-container");l&&l.remove();let f=Uu({onSubmit:async(g,v)=>{I.isClientTokenMode()&&await I.submitNPSFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});Te.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(s,l){return I.submitCSATFeedback(s,l)},async submitNPSFeedback(s,l){return I.submitNPSFeedback(s,l)},destroy(){Up(),xs!=null&&(clearInterval(xs),xs=null),fe.forEach(s=>s()),Ge.remove(),Kt?.remove(),Tt?.destroy(),mo?.remove(),as&&Ne.removeEventListener("click",as)}};if(((o?.debugTools??!1)||!!n.debug)&&typeof window<"u"){let s=window.AgentWidgetBrowser,l={controller:Et,getMessages:Et.getMessages,getStatus:Et.getStatus,getMetadata:Et.getPersistentMetadata,updateMetadata:Et.updatePersistentMetadata,clearHistory:()=>Et.clearChat(),setVoiceActive:f=>f?Et.startVoiceRecognition():Et.stopVoiceRecognition()};window.AgentWidgetBrowser=l,fe.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=s)})}if(typeof window<"u"){let s=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),l=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.focusInput()};if(window.addEventListener("persona:focusInput",l),fe.push(()=>{window.removeEventListener("persona:focusInput",l)}),E){let j=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===s)&&Et.showEventStream()},J=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===s)&&Et.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",J),fe.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",J)})}let f=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.showHistory()},g=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",g),fe.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",g)});let v=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.showArtifacts()},A=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.hideArtifacts()},_=j=>{let J=j.detail;J?.instanceId&&J.instanceId!==s||J?.artifact&&Et.upsertArtifact(J.artifact)},$=j=>{let J=j.detail;J?.instanceId&&J.instanceId!==s||typeof J?.id=="string"&&Et.selectArtifact(J.id)},U=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.clearArtifacts()};window.addEventListener("persona:showArtifacts",v),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",_),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",U),fe.push(()=>{window.removeEventListener("persona:showArtifacts",v),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",_),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",U)})}let rn=sL(n.persistState);if(rn&&qe()){let s=aL(rn.storage),l=`${rn.keyPrefix}widget-open`,f=`${rn.keyPrefix}widget-voice`,g=`${rn.keyPrefix}widget-voice-mode`;if(s){let v=rn.persist?.openState&&s.getItem(l)==="true",A=rn.persist?.voiceState&&s.getItem(f)==="true",_=rn.persist?.voiceState&&s.getItem(g)==="true";if(v&&(Tt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Et.open(),setTimeout(()=>{if(A||_)Et.startVoiceRecognition();else if(rn.persist?.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0)),rn.persist?.openState&&(C.on("widget:opened",()=>{s.setItem(l,"true")}),C.on("widget:closed",()=>{s.setItem(l,"false")})),rn.persist?.voiceState&&(C.on("voice:state",$=>{s.setItem(f,$.active?"true":"false")}),C.on("user:message",$=>{s.setItem(g,$.viaVoice?"true":"false")})),rn.clearOnChatClear){let $=()=>{s.removeItem(l),s.removeItem(f),s.removeItem(g)},U=()=>$();window.addEventListener("persona:clear-chat",U),fe.push(()=>{window.removeEventListener("persona:clear-chat",U)})}}}if(ee&&qe()&&(Tt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Et.open()},0)),ua(),!MA){let s=Pa(()=>{I&&(us++,Ot.clear(),Jo(Te,I.getMessages(),wt))});fe.push(s)}M=()=>{I&&(us++,Ot.clear(),Jo(Te,I.getMessages(),wt))},I.getMessages().length>0&&xd(),b=()=>{I&&(us++,Ot.clear(),Jo(Te,I.getMessages(),wt))};let mT=Nx(()=>{I&&(us++,Ot.clear(),Jo(Te,I.getMessages(),wt))});fe.push(mT);let gT=Zg(()=>{I&&(us++,Ot.clear(),Jo(Te,I.getMessages(),wt),hr()?.updateInlineArtifactBlocks(Te,Yo.artifacts,{suppressTransition:!0}),fn())});return fe.push(gT),Et};var Rw=(e,t)=>{let o=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(o);if(n)return Math.max(0,parseFloat(n[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(o);return r?Math.max(0,t*parseFloat(r[1])/100):420},dL=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},cL=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},uL=(e,t)=>{let o=e.parentElement;if(!o)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",o.appendChild(n);let r=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),!(!r||a)&&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.")},Hw=(e,t)=>{let o=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=o?"":"100%",e.style.display=o?"":"flex",e.style.flexDirection=o?"":"column",e.style.flex=o?"":"1 1 auto",e.style.minHeight=o?"":"0",e.style.minWidth=o?"":"0"},hh=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=""},Ww=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",hh(e)},fh=e=>{e.style.transition=""},mh=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=""},gh=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},$u=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},pL=(e,t,o,n,r)=>{r?o.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(o,n),e.appendChild(t)):o.parentElement===t&&(t.replaceChildren(),e.appendChild(o),e.appendChild(n))},fL=(e,t,o,n,r,a)=>{let i=a?t:e;r==="left"?i.firstElementChild!==n&&i.replaceChildren(n,o):i.lastElementChild!==n&&i.replaceChildren(o,n)},mL=e=>{let t=Kr(e),o=t.components?.panel,n=(r,a)=>r==null||r===""?a:vo(t,r)??r;return{inset:n(o?.inset,nu),canvasBackground:n(o?.canvasBackground,ru)}},Bw=(e,t,o,n)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=o,e.style.background=n},gL=(e,t,o,n,r,a,i,d)=>{let c=Do(a),u=c.reveal==="push",p=d!=null,m=d?.inset??"",h=d?.canvasBackground??"";pL(e,t,o,n,u),fL(e,t,o,n,c.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"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",o.style.display="flex",o.style.flexDirection="column",o.style.minHeight="0",o.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let y=e.ownerDocument.defaultView,x=a?.launcher?.mobileFullscreen??!0,M=a?.launcher?.mobileBreakpoint??640,S=y!=null?y.innerWidth<=M:!1;if(x&&S&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),mh(t),fh(n),Ww(n),gh(o),$u(r,n),Bw(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",o.style.flex="1 1 auto",o.style.width="100%",o.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??ro),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(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",o.style.flex="1 1 auto",o.style.width="100%",o.style.maxWidth="100%",o.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Ww(n),dL(n,c.maxHeight),Bw(n,p&&i,m,h),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",mh(t),fh(n),gh(o),$u(r,n);let P=c.animate?"transform 180ms ease":"none",H=c.side==="right"?"translateX(100%)":"translateX(-100%)",b=i?"translateX(0)":H;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=c.width,n.style.maxWidth=c.width,n.style.minWidth=c.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=P,n.style.transform=b,n.style.pointerEvents=i?"auto":"none",n.style.zIndex="2",c.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(c.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",fh(n),hh(n),$u(r,n);let P=Rw(c.width,e.clientWidth),H=Math.max(0,e.clientWidth),b=c.animate?"margin-left 180ms ease":"none",w=c.side==="right"?i?-P:0:i?0:-P;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${H+P}px`,t.style.transition=b,t.style.marginLeft=`${w}px`,t.style.transform="",o.style.flex="0 0 auto",o.style.flexGrow="0",o.style.flexShrink="0",o.style.width=`${H}px`,o.style.maxWidth=`${H}px`,o.style.minWidth=`${H}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=c.width,n.style.minWidth=c.width,n.style.maxWidth=c.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",mh(t),hh(n),gh(o),$u(r,n);let P=c.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let H=i?c.width:"0px",b=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",w=!i;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${H}`,n.style.width=H,n.style.maxWidth=H,n.style.minWidth=H,n.style.minHeight="0",cL(n,c.maxHeight),n.style.overflow=P||w?"hidden":"visible",n.style.transition=b,P){n.style.alignItems=c.side==="right"?"flex-start":"flex-end";let C=p?`calc(${Rw(c.width,e.clientWidth)}px - (2 * ${m}))`:c.width;r.style.width=C,r.style.minWidth=C,r.style.maxWidth=C,r.style.boxSizing="border-box"}}},hL=(e,t)=>{let o=e.ownerDocument.createElement("div");return Hw(o,t),e.appendChild(o),{mode:"direct",host:o,shell:null,syncWidgetState:()=>{},updateConfig(n){Hw(o,n)},destroy(){o.remove()}}},yL=(e,t)=>{let{ownerDocument:o}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,i=o.createElement("div"),d=o.createElement("div"),c=o.createElement("div"),u=o.createElement("aside"),p=o.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;d.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),n.insertBefore(i,e),c.appendChild(e);let h=null,y=()=>{h?.disconnect(),h=null},x=null,M=()=>{x=t?.launcher?.detachedPanel===!0?mL(t):null};M();let S=()=>{gL(i,d,c,u,p,t,m,x)},k=null,P=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=za(()=>{M(),S()}))},H=()=>{y(),Do(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{S()}),h.observe(i)))},b=!1,w=()=>{S(),H(),m&&!b&&i.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,uL(i,Do(t)))},C=i.ownerDocument.defaultView,L=()=>{w()};return C?.addEventListener("resize",L),Do(t).reveal==="push"?(d.appendChild(c),d.appendChild(u),i.appendChild(d)):(i.appendChild(c),i.appendChild(u)),w(),P(),{mode:"docked",host:p,shell:i,syncWidgetState(N){let X=N.launcherEnabled?N.open:!0;m!==X&&(m=X,w())},updateConfig(N){t=N,(t?.launcher?.enabled??!0)===!1&&(m=!0),M(),w(),P()},destroy(){C?.removeEventListener("resize",L),k?.(),k=null,y(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),i.remove()}}},Vl=(e,t)=>Ct(t)?yL(e,t):hL(e,t);var bL=e=>{if(typeof window>"u"||typeof document>"u")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},Ow=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let n=o.cloneNode(!0);e.insertBefore(n,e.firstChild)},ju=[],Dw=()=>[...ju],_w=e=>{let t=bL(e.target),o=e.useShadowDom===!0,n=t.ownerDocument,r=e.config,a=Vl(t,r),i,d=[],c=(S,k)=>{let H=!(k?.launcher?.enabled??!0)||Ct(k),b=n.createElement("div");if(b.setAttribute("data-persona-root","true"),H&&(b.style.height="100%",b.style.display="flex",b.style.flexDirection="column",b.style.flex="1",b.style.minHeight="0",b.style.minWidth="0"),o){let w=S.attachShadow({mode:"open"});w.appendChild(b),Ow(w,n)}else S.appendChild(b),Ow(S,n);return t.id&&b.setAttribute("data-persona-instance",t.id),b},u=()=>{a.syncWidgetState(i.getState())},p=()=>{d.forEach(S=>S()),d=[i.on("widget:opened",u),i.on("widget:closed",u)],u()},m=()=>{let S=c(a.host,r);i=Vu(S,r,{debugTools:e.debugTools}),p()},h=()=>{d.forEach(S=>S()),d=[],i.destroy()};m(),e.onChatReady?.();let y=S=>{h(),a.destroy(),a=Vl(t,S),r=S,m()},x={update(S){let k=Wu(r??{},S),P=Ct(r),H=Ct(k),b=Qr(r),w=Qr(k);if(P!==H||b!==w){y(k);return}r=k,a.updateConfig(r),i.update(S),u()},destroy(){h(),a.destroy();let S=ju.indexOf(M);S!==-1&&ju.splice(S,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},M=new Proxy(x,{get(S,k,P){if(k==="host")return a.host;if(k in S)return Reflect.get(S,k,P);let H=i[k];return typeof H=="function"?H.bind(i):H}});return ju.push(M),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=M),M};var Vw=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),vL=new Set(["button","a","input","select","textarea","details","summary"]),xL=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),yh=/\b(product|card|item|listing|result)\b/i,vh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,CL=3e3,SL=100;function $w(e){let t=typeof e.className=="string"?e.className:"";if(yh.test(t)||e.id&&yh.test(e.id))return!0;for(let o=0;o<e.attributes.length;o++){let n=e.attributes[o];if(n.name.startsWith("data-")&&yh.test(n.value))return!0}return!1}function jw(e){return vh.test((e.textContent??"").trim())}function zw(e){let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=t[o].getAttribute("href")??"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function wL(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Nw(e){let t=e.match(vh);return t?t[0]:null}function Fw(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let n=t.getAttribute("href");return{title:t.textContent.trim(),href:n&&n!=="#"?n:null}}let o=e.querySelector("h1, h2, h3, h4, h5, h6");return o?.textContent?.trim()?{title:o.textContent.trim(),href:null}:{title:"",href:null}}function AL(e){let t=[],o=n=>{let r=n.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(n=>o(n.textContent??"")),e.querySelectorAll('[role="button"]').forEach(n=>o(n.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{o(n.value??"")}),t.slice(0,6)}var ML="commerce-card",TL="result-card";function Uw(e){return!$w(e)||!jw(e)||!zw(e)&&!wL(e)?0:5200}function qw(e){return!$w(e)||jw(e)||!zw(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xh=[{id:ML,scoreElement(e){return Uw(e)},shouldSuppressDescendant(e,t,o){if(t===e||!e.contains(t))return!1;if(o.interactivity==="static"){let n=o.text.trim();return!!(n.length===0||vh.test(n)&&n.length<32)}return!0},formatSummary(e,t){if(Uw(e)===0)return null;let{title:o,href:n}=Fw(e),r=Nw((e.textContent??"").trim())??Nw(t.text)??"",a=AL(e);return[n&&o?`[${o}](${n})${r?`: ${r}`:""}`:o?`${o}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
139
|
-
`)}},{id:
|
|
140
|
-
`)}}];function
|
|
138
|
+
`)}if(!g&&!s){let De="max-height: -moz-available !important; max-height: stretch !important;",xe=l?"":"padding-top: 1.25em !important;",uo=l?"":`z-index: ${n.launcher?.zIndex??ro} !important;`;Ge.style.cssText+=De+xe+uo}tp(),Lt()},gp=()=>{e.style.setProperty("--persona-content-max-width",Gr(n,Le()))},ly=!1,dy=()=>{let s=gg(n,Le());Le()&&n.composer?.placement&&n.debug===!0&&!ly&&(ly=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let l=Cn(n);e.setAttribute("data-persona-composer-placement",s),e.setAttribute("data-persona-conversation-state",Xl),e.setAttribute("data-persona-welcome-anchor",l.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",l.composerGap??lu),Yl()},cy=()=>{if(Le())return;let s=Ct(n),l=n.launcher?.sidebarMode??!1;if(s||l||(n.launcher?.fullHeight??!1)||!pe)return;let g=e.ownerDocument.defaultView??window,v=n.launcher?.mobileFullscreen??!0,w=n.launcher?.mobileBreakpoint??640;if(v&&g.innerWidth<=w)return;let _=g.innerHeight,$=64,U=n.launcher?.heightOffset??0,j=Math.max(200,_-$),J=Math.min(640,j);Ce.style.height=`${Math.max(200,J-U)}px`};mp(),Ds(e,n),Ol(e,n),Dl(e,n),gp(),dy(),os=()=>{mp(),cy(),Ds(e,n),Ol(e,n),Dl(e,n),gp(),dy(),ed?e.style.setProperty("--persona-artifact-welded-outer-radius",ed):e.style.removeProperty("--persona-artifact-welded-outer-radius"),jn(),Gu()};let fe=[];fe.push(()=>{oy=!0}),fe.push(()=>{c.forEach(s=>s()),d.destroy()}),fe.push(()=>{document.removeEventListener("keydown",sy)}),fe.push(()=>{pi!==null&&clearTimeout(pi)});let Pn=null,kn=null;fe.push(()=>{Pn?.(),Pn=null,kn?.(),kn=null}),gi&&fe.push(()=>{gi?.disconnect(),gi=null}),fe.push(()=>{bi?.(),bi=null,fp(),bt&&(bt.remove(),bt=null),$e?.element.style.removeProperty("width"),$e?.element.style.removeProperty("maxWidth"),$e?.destroy()}),k&&fe.push(()=>{Ve=!0,Ke=null,It!==null&&(cancelAnimationFrame(It),It=null),gt?.destroy(),gt=null,We?.destroy(),We=null,Me=null});let rs=null,uy=()=>{rs&&(rs(),rs=null),n.colorScheme==="auto"&&(rs=za(()=>{Ds(e,n)}))};uy(),fe.push(()=>{rs&&(rs(),rs=null)}),fe.push(()=>{C=!0,y?.()}),fe.push(()=>{T=!0});let py=!1;fe.push(()=>{py=!0});let hp=(s,l)=>{let f=Pl(s,l);return f||!hS.includes(s)?f:(vS().then(g=>{if(py)return;Ka(g.wipe),Ka(g.glyphCycle);let v=Pl(s,l);v&&Il(v,e)}).catch(()=>{}),null)},ld=n.features?.streamAnimation;if(ld?.type&&ld.type!=="none"){let s=hp(ld.type,ld.plugins);s&&Il(s,e),fe.push(()=>yS(e))}let Xn=Wl(vr),fy=Wl(Qu),my=Wl(li),ss=[Xn,fy,my];fe.push(()=>{ss.forEach(s=>s.destroy())});let as=null,R,is=null,gy=!1,hy=0,yy=null,by=s=>s.reduce((l,f)=>f.role==="user"?l+1:l,0),vy=s=>{for(let l=s.length-1;l>=0;l--)if(Is(s[l]))return s[l].id??null;return null},xy=!1,TA=()=>{xy||n.debug!==!0||(xy=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},Cy=!1,Sy=!1,wy=(s,l)=>{Cy||n.debug!==!0||!l.enabled||l.expose||gy||Sy&&(R.isStreaming()||s.some(Is)||(Cy=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},ra=s=>{if(!R)return;let l=s??R.getMessages(),f=j=>{j.render([],R,ie,l)},g=j=>{ss.forEach(J=>{J!==j&&f(J)})};is&&(by(l)>hy||vy(l)!==yy)&&(is=null);let v=jr(n);wy(l,v);let w=v.enabled?hc(l):null,_=is??w,$=is?"host":"agent";if(_){let j=n.suggestions?.followUps,J=j?.placement??(j?"auto":"composer"),ce=(J==="auto"?Le()?"composer":"after-message":J)==="after-message"?my:Xn;g(ce),ce.render(_,R,ie,l,n.suggestionChipsConfig,{source:$,surface:"followUp",variant:j?.variant??"chip",behavior:j?.behavior??"send",overflow:j?.overflow??"wrap",maxItems:j?.maxItems??4,config:n,plugins:i,submitPrompt:Xd});return}if(l.some(j=>j.role==="user")){ss.forEach(f);return}let U=n.suggestions?.starters;if(U){let j=Yr(Cn(n),l),J=U.placement??"auto",re=J==="auto"?j?"welcome":"composer":J;if(re==="welcome"&&!j){TA(),ss.forEach(f);return}let ce=re==="welcome"?fy:Xn;g(ce),ce.render(U.items??n.suggestionChips,R,ie,l,n.suggestionChipsConfig,{surface:"starter",variant:U.variant??"card",behavior:U.behavior??"send",overflow:U.overflow??"wrap",maxItems:U.maxItems??4,config:n,plugins:i,submitPrompt:Xd});return}g(Xn),Xn.render(n.suggestionChips,R,ie,l,n.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:n,plugins:i,submitPrompt:Xd})},Ay=()=>{is&&(is=null,ra())},EA=s=>{let l=Array.isArray(s)?[...s]:[];if(!l.length){Ay();return}let f=R?R.getMessages():[];is=l,gy=!0,hy=by(f),yy=vy(f),ra(f)},qo=!1,Ot=rS(),sa=new Map,ls=new Map,Mr=new Map,ds=null,Tr=null;function cs(){if(!ds)return;let s=ds;ds=null,Tr?.destroy(),Tr=null,Ot.delete(s),de.querySelector(`#wrapper-${s}`)?.removeAttribute("data-preserve-runtime"),R&&Jo(Te,R.getMessages(),wt)}let us=0,PA=On()!==null,Vo=dS(),$o=0,Er=null,Eo=!1,dd=!1,Pr=0,Vt=null,ps=null,yp=!1,aa=!1,fs=null,vi=!0,cd=!1,ia=null,ud=!1,ms=()=>{ud=!0,RA()},bp=null,kA=4,Qn=24,LA=80,IA=1e3,Yn=null,My=()=>{e.setAttribute("data-persona-scrollbar",Ju()),Ju()!=="on-scroll"&&(Yn!==null&&clearTimeout(Yn),Yn=null,oe.removeAttribute("data-persona-scrollbar-visible"))},RA=()=>{Ju()==="on-scroll"&&(oe.setAttribute("data-persona-scrollbar-visible",""),Yn!==null&&clearTimeout(Yn),Yn=setTimeout(()=>{Yn=null,_s(oe,Qn)&&oe.removeAttribute("data-persona-scrollbar-visible")},IA))};My(),fe.push(()=>{Yn!==null&&clearTimeout(Yn)});let vp=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Xh=()=>je.active,un();let Ty=n.voiceRecognition?.autoResume??!1,Jn=s=>{x.emit("voice:state",{active:je.active,source:s,timestamp:Date.now()})},mn=()=>{ae(s=>({...s,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},HA=()=>{if(n.voiceRecognition?.enabled===!1)return;let s=fh(V.voiceState),l=!!s.active,f=Number(s.timestamp??0);je.manuallyDeactivated=!!s.manuallyDeactivated,l&&Date.now()-f<iL&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,Wo(n.voiceRecognition?.provider)?R.toggleVoice().then(()=>{je.active=R.isVoiceActive(),Jn("restore"),R.isVoiceActive()&&Ma()}):Jd("restore"))},1e3)},WA=()=>R?Rw(R.getMessages()).filter(s=>!s.__skipPersist):[],pd=null,Ey=(s,l)=>{typeof console<"u"&&console.error(s,l)},fd=(s,l)=>{let f=()=>{try{let _=s();return!_||typeof _.then!="function"?null:Promise.resolve(_).catch($=>{Ey(l,$)})}catch(_){return Ey(l,_),null}},g=pd,v=g?g.then(()=>f()??void 0):f();if(!v)return;let w=v.finally(()=>{pd===w&&(pd=null)});pd=w};function la(s){if(!N?.save)return;let l=s?Rw(s):R?WA():[],f=X&&R?.getResumableHandle();f&&(V={...V,durableResume:{executionId:f.executionId,after:f.lastEventId}});let g={messages:l,metadata:V,artifacts:Yo.artifacts,selectedArtifactId:Yo.selectedId,...gs?{draft:gs}:{}};fd(()=>N.save(g),"[AgentWidget] Failed to persist state:")}let gs,md=()=>!N?.save||n.persistState===!1?!1:typeof n.persistState=="object"?n.persistState.persist?.draft!==!1:!0,xi=kC({write:()=>{if(!md())return;let s=he.getState(),l=EC({text:s.text,mentionRefs:s.mentionRefs,contentSegments:hf(),selectedModelId:s.selectedModelId,activeModeIds:s.activeModeIds,quote:s.quote});JSON.stringify(l)!==JSON.stringify(gs)&&(gs=l,la())}});function Py(){md()&&xi.schedule()}function xp(){xi.flush()}function ky(s){if(!md())return;let l=PC(s,{mentionSourceIds:(n.contextMentions?.sources??[]).map(f=>f.id),modelIds:(n.composer?.models??[]).map(f=>f.id),modes:n.composer?.modes??[]});l&&(gs=s,ie&&!ie.value&&(ie.value=l.text,ie.dispatchEvent(new Event("input",{bubbles:!0})),An()),l.selectedModelId&&(he.setSelectedModelId(l.selectedModelId),Sr?.repaint()),Jl(l.activeModeIds??[]),l.quote&&Mn(l.quote),xi.cancel())}function gd(){xi.cancel(),gs&&(gs=void 0,md()&&la())}let da=null,Ly=()=>Ge.querySelector("#persona-scroll-container")||oe,ca=()=>{da!==null&&(cancelAnimationFrame(da),da=null),Eo=!1},Iy=()=>{Er!==null&&(cancelAnimationFrame(Er),Er=null),dd=!1,ca()},BA=()=>qo&&Sp()&&(Uo()!=="anchor-top"||Rh()),Cp=()=>{let s=di()||"Jump to latest",l=BA();Bt.toggleAttribute("data-persona-scroll-to-bottom-streaming",l),Pr>0?(Zr.textContent=String(Pr),Zr.style.display="",Bt.setAttribute("aria-label",`${s} (${Pr} new)`)):(Zr.textContent="",Zr.style.display="none",Bt.setAttribute("aria-label",l?`${s} (response streaming below)`:s))},Ry=()=>{Pr!==0&&(Pr=0,Cp())},OA=()=>{let s=Vt?.spacerHeight??0;return s<=0?_s(oe,Qn):vd(s)-oe.scrollTop-oe.clientHeight<=Qn},Sp=()=>Cr()?!Vo.isFollowing():!OA(),wp=()=>!!R&&R.getMessages().length>0,$t=()=>{if(!cA()||oA()){Bt.parentNode&&Bt.remove(),Bt.style.display="none";return}Bt.parentNode!==de&&de.appendChild(Bt),es();let l=Un(oe)>0&&Sp()&&wp();l?Cp():Ry(),Bt.style.display=l?"":"none"},Ci=()=>{Vo.pause()&&(Iy(),$t())},Po=()=>{Vo.resume(),Ry(),$t()},kr=(s=!1)=>{Cr()&&wp()&&Vo.isFollowing()&&(!s&&!qo||(Er!==null&&(cancelAnimationFrame(Er),Er=null),dd=!0,Er=requestAnimationFrame(()=>{Er=null,dd=!1,Vo.isFollowing()&&DA(Ly(),s?220:140)})))},Hy=(s,l,f,g=()=>!0)=>{let v=s.scrollTop,w=l(),_=w-v;if(ca(),Math.abs(_)<1){Eo=!0,s.scrollTop=w,$o=s.scrollTop,Eo=!1;return}let $=performance.now();Eo=!0;let U=J=>1-Math.pow(1-J,3),j=J=>{if(!g()){ca();return}let re=l();re!==w&&(w=re,_=w-v);let ce=J-$,Ye=Math.min(ce/f,1),ct=U(Ye),ft=v+_*ct;s.scrollTop=ft,$o=s.scrollTop,Ye<1?da=requestAnimationFrame(j):(s.scrollTop=w,$o=s.scrollTop,da=null,Eo=!1)};da=requestAnimationFrame(j)},DA=(s,l=500)=>{let f=Un(s)-s.scrollTop;if(Math.abs(f)<1){$o=s.scrollTop;return}if(Math.abs(f)>=LA){ca(),Eo=!0,s.scrollTop=Un(s),$o=s.scrollTop,Eo=!1;return}Hy(s,()=>Un(s),l,()=>Vo.isFollowing())},hd=()=>{if(!wp()){$t();return}let s=Ly();Eo=!0,s.scrollTop=Un(s),$o=s.scrollTop,Eo=!1,$t()},hs=s=>{let l=0,f=s;for(;f&&f!==oe;)l+=f.offsetTop,f=f.offsetParent;return l},_A=()=>{let s=oe.getRootNode();return(typeof s.getSelection=="function"?s.getSelection():null)??oe.ownerDocument.getSelection()},yd=()=>pS(_A(),oe),Ap=()=>{if(uA()!=="last-user-turn")return!1;let s=R?.getMessages()??[];if(s.length<2)return!1;let l=[...s].reverse().find(w=>w.role==="user");if(!l)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l.id):l.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),g=oe.querySelector(`[data-message-id="${f}"]`);if(!g)return!1;let v=Math.min(Math.max(0,hs(g)-ci()),Un(oe));return Eo=!0,oe.scrollTop=v,$o=oe.scrollTop,Eo=!1,Uo()==="follow"&&!_s(oe,Qn)&&Vo.pause(),$t(),!0},bd=s=>{let l=Math.max(0,Math.round(s));Qo.style.height=`${l}px`,Qo.style.display=l>0?"":"none",Vt&&(Vt.spacerHeight=Math.max(0,s))},vd=s=>{let l=parseFloat(getComputedStyle(oe).paddingBottom)||0,f=0;for(let v of Array.from(oe.children)){if(v===Qo||v.offsetHeight===0)continue;let w=hs(v)+v.offsetHeight;w>f&&(f=w)}let g=oe.scrollHeight-s;return f>0?Math.min(f+l,g):g},NA=()=>{if(!Vt||Vt.spacerHeight<=0)return;let s=vd(Vt.spacerHeight),l=Math.max(0,Math.round(oe.scrollTop)+oe.clientHeight-s+Qn);l<Vt.spacerHeight&&(bd(l),$t())},gn=()=>{ps!==null&&(cancelAnimationFrame(ps),ps=null),ca(),Vt=null,Qo.style.height="0px",Qo.style.display="none"},Wy=s=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Mp=s=>oe.querySelector(`[data-message-id="${Wy(s)}"]`),By=s=>{ps!==null&&cancelAnimationFrame(ps),ps=requestAnimationFrame(()=>{ps=null;let l=Wy(s),f=oe.querySelector(`[data-message-id="${l}"]`);if(!f)return;let g=hs(f),v=Vt?.spacerHeight??0,w=vd(v),{targetScrollTop:_,spacerHeight:$}=bg({anchorOffsetTop:g,topOffset:ci(),viewportHeight:oe.clientHeight,contentHeight:w,slack:Qn});Vt={initialSpacerHeight:$,contentHeightAtAnchor:w,spacerHeight:$},bd($),Hy(oe,()=>f.isConnected?Math.max(0,hs(f)-ci()):_,220)})},ko=()=>{if(Uo()!=="anchor-top"||!Vt||!ia)return;let s=Mp(ia);if(!s)return;ca();let l=Vt.spacerHeight,f=vd(l),{targetScrollTop:g,spacerHeight:v}=bg({anchorOffsetTop:hs(s),topOffset:ci(),viewportHeight:oe.clientHeight,contentHeight:f,slack:Qn});Vt={initialSpacerHeight:v,contentHeightAtAnchor:f,spacerHeight:v},bd(v),Eo=!0,oe.scrollTop=g,$o=oe.scrollTop,Eo=!1,$t()},FA=()=>{if(Cr()){if(!Vo.isFollowing()||_s(oe,1))return;kr(!qo);return}if(Vt&&Vt.initialSpacerHeight>0){let s=oe.scrollHeight-Vt.spacerHeight,l=fS({initialSpacerHeight:Vt.initialSpacerHeight,contentHeightAtAnchor:Vt.contentHeightAtAnchor,currentContentHeight:s});l!==Vt.spacerHeight&&bd(l)}$t()},UA=s=>{let l=Uo();l==="follow"?(Po(),kr(!0)):l==="anchor-top"&&(vi=!1,cd=!0,ud=!1,ia=s,By(s))},qA=()=>{if(Uo()==="anchor-top"){if(cd){vi=!1;return}vi=!0,gn(),Po(),kr(!0)}},VA=96,$A=s=>{if(fs===null)return!0;let l=Mp(fs),f=Mp(s);if(!l||!f)return!0;let g=hs(f)-hs(l);return ci()+g>oe.clientHeight-VA},jA=s=>{if(Uo()!=="anchor-top"||!cd||ud||yd())return;let l=fs===null;for(let f of s){if(!l){f.id===fs&&(l=!0);continue}if(lS(f)){if(f.id===ia||!$A(f.id))return;ia=f.id,By(f.id);return}}},zA=s=>{let l=new Map;s.forEach(f=>{let g=vp.get(f.id);l.set(f.id,{streaming:f.streaming,role:f.role}),!g&&f.role==="assistant"&&(x.emit("assistant:message",f),!aa&&(Uo()!=="anchor-top"||Rh())&&Sp()&&(Pr+=1,Cp(),$t(),Gl(Pr===1?"1 new message below.":`${Pr} new messages below.`))),f.role==="assistant"&&g?.streaming&&f.streaming===!1&&x.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(g?f.approval.status!=="pending"&&x.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):x.emit("approval:requested",{approval:f.approval,message:f}))}),vp.clear(),l.forEach((f,g)=>{vp.set(g,f)})},Si=(s,l)=>{let f=l==="user"?"user":"assistant",g=n.layout?.messages?.[f],v=g?.width??"content",w=g?.maxWidth??(v==="full"?"100%":void 0);s.classList.add("persona-message-row"),s.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),s.classList.add(`persona-message-row-${l}`,`persona-message-width-${v}`),s.classList.toggle("persona-justify-end",l==="user"),s.setAttribute("data-message-role",l),s.setAttribute("data-message-width",v),w?s.style.setProperty("--persona-message-row-max-width",w):s.style.removeProperty("--persona-message-row-max-width")},Zn=(s,l)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${s}`,f.setAttribute("data-wrapper-id",s),Si(f,l),f},KA=(s,l,f)=>{let g=document.createElement("div"),w=(()=>{let B=i.find(Fe=>Fe.renderLoadingIndicator);if(B?.renderLoadingIndicator)return B.renderLoadingIndicator;if(n.loadingIndicator?.render)return n.loadingIndicator.render})(),_=(B,Fe)=>Fe==null?!1:typeof Fe=="string"?(B.textContent=Fe,!0):(B.appendChild(Fe),!0),$=new Set,U=new Map,j=new Set,J=i.some(B=>B.renderAskUserQuestion),re=[],ce=[],Ye=n.enableComponentStreaming!==!1,ct=n.approval!==!1,ft=[],Gt=n.messageActions,_t=Gt?.showRegenerate===!0&&Gt.enabled!==!1&&dt.current?.isStreaming()!==!0?Rx(l):null,Pt=Gt?.showEdit===!0&&Gt.enabled!==!1,io=Gt?.showQuote===!0&&Gt.enabled!==!1,et=null,lo=n.features?.reasoningDisplay?.completedVisibility,Wn=B=>lo==="removed"?!0:lo==="removed-when-short"?nx(B,n.features?.reasoningDisplay?.shortThinkThreshold):!1,ir=n.features?.toolCallDisplay?.completedVisibility==="removed",hn=B=>B.variant==="reasoning"&&B.reasoning?.status==="complete"?Wn(B.reasoning):ir&&B.variant==="tool"&&B.toolCall?.status==="complete";if(l.forEach(B=>{if(hn(B))return;if($.add(B.id),U.set(B.id,B.role),ds===B.id&&Tr){let xe=Zn(B.id,B.role);xe.setAttribute("data-persona-message-edit-stub","true"),xe.setAttribute("data-preserve-runtime","true"),g.appendChild(xe),et={messageId:B.id,element:Tr.element};return}let Fe=J&&cr(B),Se=ct&&B.variant==="approval"&&!!B.approval,se=!Fe&&B.role==="assistant"&&!B.variant&&Ye&&ql(B);!Se&&Mr.has(B.id)&&(s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),Mr.delete(B.id)),!se&&ls.has(B.id)&&(s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),ls.delete(B.id));let kt=cr(B)?`:${B.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${B.agentMetadata?.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Nt={canRegenerate:_t===B.id,canEdit:Pt&&em(B),canQuote:io&&!B.variant&&(B.content?.trim().length??0)>0},to=`${Nt.canRegenerate?"r":""}${Nt.canEdit?"e":""}${Nt.canQuote?"q":""}`,Ft=nS(B,us)+kt+`:${to}`,jt=Fe||Se||se?null:sS(Ot,B.id,Ft);if(jt){g.appendChild(jt.cloneNode(!0)),cr(B)&&B.toolCall?.id&&B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(j.add(B.toolCall.id),Ra(B,n,Oe.composerOverlay));return}let Lt=null,co=i.find(xe=>!!(B.variant==="reasoning"&&xe.renderReasoning||B.variant==="tool"&&xe.renderToolCall||!B.variant&&xe.renderMessage)),Ie=n.layout?.messages;if(cr(B)&&B.agentMetadata?.askUserQuestionAnswered===!0){sa.delete(B.id),s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime");return}if(Is(B)&&jr(n).enabled)return;if(cr(B)&&n.features?.askUserQuestion?.enabled!==!1){let xe=i.find(uo=>typeof uo.renderAskUserQuestion=="function");if(xe&&dt.current){let uo=sa.get(B.id),Or=uo!==Ft,Io=null;if(Or){let{payload:ut,complete:Be}=ur(B),lr=B.id,Ht=()=>dt.current?.getMessages().find(Ho=>Ho.id===lr);Io=xe.renderAskUserQuestion({message:B,payload:ut,complete:Be,resolve:Ho=>{let Ki=Ht();Ki&&dt.current?.resolveAskUserQuestion(Ki,Ho)},dismiss:()=>{let Ho=Ht();Ho?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(Ho),dt.current?.resolveAskUserQuestion(Ho,"(dismissed)"))},config:n})}let Ro=uo!=null;if(Or&&Io===null&&!Ro){B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(j.add(B.toolCall.id),Ra(B,n,Oe.composerOverlay));return}let lt=Zn(B.id,B.role);lt.setAttribute("data-ask-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),g.appendChild(lt),re.push({messageId:B.id,fingerprint:Ft,bubble:Io});return}else{B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(j.add(B.toolCall.id),Ra(B,n,Oe.composerOverlay));return}}else if(Se){let xe=E();if(!xe){g.appendChild(Zn(B.id,B.role));return}let uo=i.find(lt=>typeof lt.renderApproval=="function")??h,Io=Mr.get(B.id)!==Ft,Ro=null;if(Io&&uo?.renderApproval){let lt=B.id,ut=(Be,lr)=>{let Ht=dt.current?.getMessages().find(Ho=>Ho.id===lt);Ht?.approval&&(Ht.approval.toolType==="webmcp"?dt.current?.resolveWebMcpApproval(Ht.id,Be):dt.current?.resolveApproval(Ht.approval,Be,lr))};Ro=uo.renderApproval({message:B,defaultRenderer:()=>xe.createApprovalBubble(B,n),config:n,approve:Be=>ut("approved",Be),deny:Be=>ut("denied",Be)})}if(Io&&Ro===null)s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),Mr.delete(B.id),Lt=xe.createApprovalBubble(B,n);else{let lt=Zn(B.id,B.role);lt.setAttribute("data-approval-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),g.appendChild(lt),ft.push({messageId:B.id,fingerprint:Ft,bubble:Ro});return}}else if(co)if(B.variant==="reasoning"&&B.reasoning&&co.renderReasoning){if(!$n)return;Lt=co.renderReasoning({message:B,defaultRenderer:()=>Gg(B,n),config:n})}else if(B.variant==="tool"&&B.toolCall&&co.renderToolCall){if(!z)return;Lt=co.renderToolCall({message:B,defaultRenderer:()=>Qg(B,n),config:n})}else co.renderMessage&&(Lt=co.renderMessage({message:B,defaultRenderer:()=>{let xe=Ya(B,f,Ie,n.messageActions,Gs,{loadingIndicatorRenderer:w,widgetConfig:n,actionEligibility:Nt});return B.role!=="user"&&S(xe,B,n,R),xe},config:n}));if(!Lt&&se){let xe=Nu(B);if(xe){let uo=ls.get(B.id),Or=uo!==Ft,Io=n.wrapComponentDirectiveInBubble!==!1&&Sn.getOptions(xe.component)?.bubbleChrome!==!1,Ro=null;if(Or){let lt=_u(xe,{config:n,message:B,transform:f});if(lt&&xe.component==="PersonaArtifactInline"){let ut=lt.hasAttribute("data-artifact-inline")?lt:lt.querySelector("[data-artifact-inline]"),Be=ut?.getAttribute("data-artifact-inline")??"",lr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Be):Be,Ht=Be?s.querySelector(`#wrapper-${B.id}`)?.querySelector(`[data-artifact-inline="${lr}"]`)??null:null;ut&&Ht&&Ht!==ut&&hr()?.hasLiveInlineArtifactBlock(Ht)&&(ut===lt?lt=Ht:ut.replaceWith(Ht))}if(lt)if(Io){let ut=document.createElement("div");if(ut.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ut.id=`bubble-${B.id}`,ut.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let Be=document.createElement("div");Be.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Be.innerHTML=f({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),ut.appendChild(Be)}ut.appendChild(lt),Ro=ut}else{let ut=document.createElement("div");if(ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ut.id=`bubble-${B.id}`,ut.setAttribute("data-message-id",B.id),ut.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let Be=document.createElement("div");Be.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Be.innerHTML=f({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),ut.appendChild(Be)}ut.appendChild(lt),Ro=ut}}if(Ro||uo!=null){let lt=Zn(B.id,B.role);lt.setAttribute("data-component-directive-stub","true"),lt.setAttribute("data-preserve-runtime","true"),g.appendChild(lt),ce.push({messageId:B.id,fingerprint:Ft,bubble:Ro});return}}}if(!Lt)if(B.variant==="reasoning"&&B.reasoning){if(!$n)return;Lt=Gg(B,n)}else if(B.variant==="tool"&&B.toolCall){if(!z)return;Lt=Qg(B,n)}else if(B.variant==="approval"&&B.approval){if(n.approval===!1)return;let xe=E();if(!xe)return;Lt=xe.createApprovalBubble(B,n)}else{let xe=n.layout?.messages;xe?.renderUserMessage&&B.role==="user"?Lt=xe.renderUserMessage({message:B,config:n,streaming:!!B.streaming}):xe?.renderAssistantMessage&&B.role==="assistant"?Lt=xe.renderAssistantMessage({message:B,config:n,streaming:!!B.streaming}):Lt=Ya(B,f,xe,n.messageActions,Gs,{loadingIndicatorRenderer:w,widgetConfig:n,actionEligibility:Nt}),B.role!=="user"&&Lt&&S(Lt,B,n,R)}let De=Zn(B.id,B.role);De.appendChild(Lt),aS(Ot,B.id,Ft,De),g.appendChild(De)}),Oe.composerOverlay&&Oe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let Se=Fe.getAttribute("data-persona-ask-sheet-for");Se&&!j.has(Se)&&Vr(Oe.composerOverlay,Se)}),n.features?.toolCallDisplay?.grouped){let B=[],Fe=[],Se=n.features.toolCallDisplay.groupedMode==="summary";l.forEach(se=>{if(se.variant==="tool"&&se.toolCall&&z){if(ir&&se.toolCall.status==="complete")return;Fe.push(se);return}se.variant==="reasoning"&&(!$n||se.reasoning?.status==="complete"&&Wn(se.reasoning))||((Fe.length>1||Se&&Fe.length>0)&&B.push(Fe),Fe=[])}),(Fe.length>1||Se&&Fe.length>0)&&B.push(Fe),B.forEach(se=>{let kt=se.map(Ie=>Array.from(g.children).find(De=>De instanceof HTMLElement&&De.getAttribute("data-wrapper-id")===Ie.id)).filter(Ie=>!!Ie);if(kt.length<(Se?1:2))return;let Nt=Zn(`tool-group-${se[0].id}`,"assistant");Nt.setAttribute("data-persona-tool-group-row","true");let to=document.createElement("div");to.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",to.setAttribute("data-persona-tool-group","true");let Ft=document.createElement("div");Ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",Ft.id=`tool-group-summary-${se[0].id}`;let jt=`Called ${se.length} ${se.length===1?"tool":"tools"}`,Lt=n.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(Ie=>Ie.toolCall).filter(Ie=>!!Ie),defaultSummary:jt,config:n});_(Ft,Lt)||(Ft.textContent=jt);let co=document.createElement("div");co.className="persona-tool-group-stack persona-flex persona-flex-col",co.id=`tool-group-stack-${se[0].id}`,co.setAttribute("data-persona-tool-group-stack","true"),to.appendChild(Ft),Se||to.appendChild(co),Nt.appendChild(to),kt[0].before(Nt),kt.forEach((Ie,De)=>{if(Se){Ie.remove();return}Ie.style.setProperty("--persona-message-row-max-width","100%");let xe=document.createElement("div");xe.className="persona-tool-group-item persona-relative",xe.setAttribute("data-persona-tool-group-item","true"),De<kt.length-1&&xe.setAttribute("data-persona-tool-group-connector","true"),xe.appendChild(Ie),co.appendChild(xe)})})}iS(Ot,$);let zi=B=>B.variant==="tool"&&!z||B.variant==="reasoning"&&!$n||hn(B),ks=l.some(B=>B.role==="assistant"&&B.streaming&&!zi(B)),yn=l.length-1;for(;yn>=0&&zi(l[yn]);)yn--;let eo=yn>=0?l[yn]:void 0,bn=yn<l.length-1,Ea=eo?.role==="assistant"&&!eo.streaming&&eo.variant!=="approval"&&!bn;if(qo&&l.some(B=>B.role==="user")&&!ks&&!Ea){let B={config:n,streaming:!0,location:"standalone",defaultRenderer:$s},Fe=i.find(se=>se.renderLoadingIndicator),Se=null;if(Fe?.renderLoadingIndicator&&(Se=Fe.renderLoadingIndicator(B)),Se===null&&n.loadingIndicator?.render&&(Se=n.loadingIndicator.render(B)),Se===null&&(Se=$s()),Se){let se=document.createElement("div"),kt=n.loadingIndicator?.showBubble!==!1,Nt=n.layout?.messages?.layout??"bubble";se.className=kt?Bl("assistant",Nt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),se.setAttribute("data-typing-indicator","true"),kt&&(se.style.color="var(--persona-message-assistant-text, var(--persona-text))",Nt!=="flat"&&(se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),se.appendChild(Se);let to=Zn("typing-indicator","assistant");to.appendChild(se),g.appendChild(to)}}if(!qo&&l.length>0){let B=l[l.length-1],Fe={config:n,lastMessage:B,messageCount:l.length},Se=i.find(kt=>kt.renderIdleIndicator),se=null;if(Se?.renderIdleIndicator&&(se=Se.renderIdleIndicator(Fe)),se===null&&n.loadingIndicator?.renderIdle&&(se=n.loadingIndicator.renderIdle(Fe)),se){let kt=document.createElement("div"),Nt=n.loadingIndicator?.showBubble!==!1;kt.className=Nt?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),kt.setAttribute("data-idle-indicator","true"),kt.appendChild(se);let to=Zn("idle-indicator","assistant");to.appendChild(kt),g.appendChild(to)}}if(Pv(g),pu(s,g),Hf(s),et){let{messageId:B,element:Fe}=et,Se=s.querySelector(`#wrapper-${B}`);Se&&Fe.parentElement!==Se&&(Si(Se,U.get(B)??"user"),Se.replaceChildren(Fe))}if(re.length>0)for(let{messageId:B,fingerprint:Fe,bubble:Se}of re){let se=s.querySelector(`#wrapper-${B}`);se&&(Si(se,U.get(B)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Fe),sa.set(B,Fe)))}if(sa.size>0)for(let B of sa.keys())$.has(B)||sa.delete(B);if(ce.length>0)for(let{messageId:B,fingerprint:Fe,bubble:Se}of ce){let se=s.querySelector(`#wrapper-${B}`);se&&(Si(se,U.get(B)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Fe),ls.set(B,Fe)))}if(ls.size>0)for(let B of ls.keys())$.has(B)||ls.delete(B);if(ft.length>0)for(let{messageId:B,fingerprint:Fe,bubble:Se}of ft){let se=s.querySelector(`#wrapper-${B}`);se&&(Si(se,U.get(B)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Fe),Mr.set(B,Fe)))}if(Mr.size>0)for(let B of Mr.keys())$.has(B)||Mr.delete(B)},Tp=!1,xd=()=>{Tp||(Tp=!0,ac().catch(()=>{Tp=!1}))},Jo=(s,l,f)=>{l.length>0&&xd(),KA(s,l,f),ty()},wi=null,GA=()=>{if(wi)return;let s=f=>{let g=f.composedPath();g.includes(Ge)||Kt&&g.includes(Kt)||pt(!1,"user")};wi=s,(e.ownerDocument??document).addEventListener("pointerdown",s,!0)},Oy=()=>{if(!wi)return;(e.ownerDocument??document).removeEventListener("pointerdown",wi,!0),wi=null};fe.push(()=>Oy());let Ai=null,XA=()=>{if(Ai)return;let s=f=>{f.key==="Escape"&&(f.isComposing||pt(!1,"user"))};Ai=s,(e.ownerDocument??document).addEventListener("keydown",s,!0)},Dy=()=>{if(!Ai)return;(e.ownerDocument??document).removeEventListener("keydown",Ai,!0),Ai=null};fe.push(()=>Dy());let Mi=!1,_y=new Set,QA=()=>{let s=n.launcher?.composerBar?.peek?.streamAnimation;return s||n.features?.streamAnimation},ua=()=>{if(!Le())return;let s=Oe.peekBanner,l=Oe.peekTextNode;if(!s||!l)return;if(ve){s.classList.remove("persona-pill-peek--visible");return}let f=R?.getMessages()??[],g;for(let _t=f.length-1;_t>=0;_t--){let Pt=f[_t];if(Pt.role==="assistant"&&Pt.content){g=Pt;break}}if(!g){s.classList.remove("persona-pill-peek--visible");return}let v=g.content,w=!!g.streaming,_=QA(),$=fu(_),U=$.type!=="none"?hp($.type,_?.plugins):null,j=U?.isAnimating?.(g)===!0,J=U!==null&&(w||j);J&&U&&!_y.has(U.name)&&(Il(U,e),_y.add(U.name));let re=J&&U?.containerClass?U.containerClass:null,ce=l.dataset.personaPeekStreamClass??null;ce&&ce!==re&&(l.classList.remove(ce),delete l.dataset.personaPeekStreamClass),re&&ce!==re&&(l.classList.add(re),l.dataset.personaPeekStreamClass=re),J?(l.style.setProperty("--persona-stream-step",`${$.speed}ms`),l.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(l.style.removeProperty("--persona-stream-step"),l.style.removeProperty("--persona-stream-duration"));let Ye=J?mu(v,$.buffer,U,g,w):v;if(J&&$.placeholder==="skeleton"&&w&&(!Ye||!Ye.trim())){let _t=document.createElement("div"),Pt=Ll();Pt.classList.add("persona-pill-peek__skeleton"),_t.appendChild(Pt),pu(l,_t)}else{let _t=Math.max(0,Ye.length-100),Pt=Ye.length>100?Ye.slice(-100):Ye,io=dr(Pt);if(!J||!U){let et=Ye.length>100?`\u2026${Pt}`:Pt;l.textContent!==et&&(l.textContent=et)}else{let et=io;(U.wrap==="char"||U.wrap==="word")&&(et=kl(io,U.wrap,`peek-${g.id}`,{skipTags:U.skipTags,startIndex:_t}));let lo=document.createElement("div");if(lo.innerHTML=et,U.useCaret&&Pt.length>0){let Wn=gu(),ir=lo.querySelectorAll(".persona-stream-char, .persona-stream-word"),hn=ir[ir.length-1];hn?.parentNode?hn.parentNode.insertBefore(Wn,hn.nextSibling):lo.appendChild(Wn)}pu(l,lo),U.onAfterRender?.({container:l,bubble:s,messageId:g.id,message:g,speed:$.speed,duration:$.duration})}}let Gt=qo||Mi;s.classList.toggle("persona-pill-peek--visible",Gt)};if(Le()){let s=Oe.peekBanner;if(s){let g=v=>{v.preventDefault(),v.stopPropagation(),pt(!0,"user")};s.addEventListener("pointerdown",g),fe.push(()=>{s.removeEventListener("pointerdown",g)})}let l=()=>{Mi||(Mi=!0,ua())},f=()=>{Mi&&(Mi=!1,ua())};Ce.addEventListener("pointerenter",l),Ce.addEventListener("pointerleave",f),fe.push(()=>{Ce.removeEventListener("pointerenter",l),Ce.removeEventListener("pointerleave",f)}),Kt&&(Kt.addEventListener("pointerenter",l),Kt.addEventListener("pointerleave",f),fe.push(()=>{Kt.removeEventListener("pointerenter",l),Kt.removeEventListener("pointerleave",f)}))}let YA=s=>{let l=n.launcher?.composerBar??{},f=l.expandedSize??"anchored",g=l.bottomOffset??"16px",v=l.collapsedMaxWidth,w=l.expandedMaxWidth??"880px",_=l.expandedTopOffset??"5vh",$=l.modalMaxWidth??"880px",U=l.modalMaxHeight??"min(90vh, 800px)",j="calc(100vw - 32px)",J="var(--persona-pill-area-height, 80px)",re=Ge.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",Kt){let ce=Kt.style;ce.bottom=g,ce.width=v??""}if(s&&f!=="fullscreen"){if(f==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=$,re.maxWidth=j,re.maxHeight=U,re.height=U;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${g} + ${J})`,re.top=_,re.width=w,re.maxWidth=j}},Ti=()=>{if(ve&&xd(),!qe())return;if(Le()){let j=(n.launcher?.composerBar??{}).expandedSize??"anchored",J=ve?"expanded":"collapsed";Ge.dataset.state=J,Ge.dataset.expandedSize=j,Kt&&(Kt.dataset.state=J,Kt.dataset.expandedSize=j),Ge.style.removeProperty("display"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),YA(ve),de.style.display=ve?"flex":"none",os(),ve?(GA(),XA()):(Oy(),Dy()),ua();return}let s=Ct(n),l=e.ownerDocument.defaultView??window,f=n.launcher?.mobileBreakpoint??640,g=n.launcher?.mobileFullscreen??!0,v=l.innerWidth<=f,w=g&&v&&pe,_=Do(n).reveal;ve?(Ge.style.removeProperty("display"),Ge.style.display=s?"flex":"",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0"),Ce.classList.add("persona-scale-100","persona-opacity-100"),Tt?(Tt.setPanelOpen(!0),Tt.element.style.display="none"):mo&&(mo.style.display="none")):(s?s&&(_==="overlay"||_==="push")&&!w?(Ge.style.removeProperty("display"),Ge.style.display="flex",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.setProperty("display","none","important"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.display="",Ge.classList.add("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100"),Ce.classList.add("persona-scale-95","persona-opacity-0")),Tt?(Tt.setPanelOpen(!1),Tt.element.style.display=s?"none":""):mo&&(mo.style.display=s?"none":""))},pt=(s,l="user")=>{if(!qe()||ve===s)return;let f=ve;ve=s,Ti();let g=(()=>{let w=n.launcher?.sidebarMode??!1,_=e.ownerDocument.defaultView??window,$=n.launcher?.mobileFullscreen??!0,U=n.launcher?.mobileBreakpoint??640,j=_.innerWidth<=U,J=Ct(n)&&$&&j,re=Le()&&(n.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return w||$&&j&&pe||J||re})();if(ve&&g){if(!Pn){let w=e.getRootNode(),_=w instanceof ShadowRoot?w.host:e.closest(".persona-host");_&&(Pn=wg(_,n.launcher?.zIndex??ro))}kn||(kn=Ag(e.ownerDocument))}else ve||(Pn?.(),Pn=null,kn?.(),kn=null);ve&&(Vi(),Ap()||(Uo()==="follow"?kr(!0):hd()));let v={open:ve,source:l,timestamp:Date.now()};ve&&!f?x.emit("widget:opened",v):!ve&&f&&x.emit("widget:closed",v),x.emit("widget:state",{open:ve,launcherEnabled:pe,voiceActive:je.active,streaming:R.isStreaming()})},Lr={inputDisabled:!1,sendDisabled:!1},Ln=()=>Lr.inputDisabled,Ep=()=>Wo(n.voiceRecognition?.provider)&&!!R&&(R.isBargeInActive()||["listening","processing","speaking"].includes(R.getVoiceStatus())),ys=()=>Lr.inputDisabled||Lr.sendDisabled,JA=()=>(Lr.inputDisabled?Lr.inputReason:void 0)??(Lr.sendDisabled?Lr.sendReason:void 0);function Pp(){if(!we)return;if(he.getState().phase==="streaming"){we.disabled=!1;return}let s=Ze?!Ze.isReady():!1;we.disabled=ys()||s}function Cd(){if(!wn)return;let s=he.getState(),l=n.sendButton?.visibility==="when-text"&&s.phase!=="streaming"&&s.text.trim().length===0&&s.attachments.length===0;wn.toggleAttribute("data-persona-send-hidden",l)}function ZA(){let s=JA();if(Le()){let l=cn??ke;s?l.setAttribute("title",s):l.removeAttribute("title"),ke.toggleAttribute(ii,!!s);return}if(s){at.setAttribute("role","status"),at.setAttribute("aria-live","polite"),at.setAttribute(ii,""),at.textContent=s;return}if(at.hasAttribute(ii)&&(at.removeAttribute("role"),at.removeAttribute("aria-live"),at.removeAttribute(ii),u)){let l=R.getStatus();jl(at,kh(l),n.statusIndicator??{},l)}}function kp(){let s=Ym(n.composer?.inputDisabled),l=Ym(n.composer?.sendDisabled);Lr={inputDisabled:s.disabled,inputReason:s.reason,sendDisabled:l.disabled,sendReason:l.reason},he.setInputDisabled(s.disabled),he.setSendDisabled(l.disabled);let f=he.getState().phase==="streaming",g=s.disabled,v=f||g;ie&&(ie instanceof HTMLTextAreaElement?ie.disabled=g:ie.setAttribute("contenteditable",g?"false":"true"),ie.setAttribute("aria-disabled",g?"true":"false")),St&&(St.disabled=g),ht&&(ht.disabled=g);for(let w of Rt?.affordanceButtons??[])w.querySelectorAll("button").forEach(_=>{_.disabled=g});ne&&(ne.disabled=g||f&&!Ep()),ss.forEach(w=>{w.elements.forEach(_=>{_.toggleAttribute("data-disabled",v),_ instanceof HTMLButtonElement||_.setAttribute("aria-disabled",v?"true":"false")}),w.buttons.forEach(_=>{_.disabled=v})}),Wp.forEach(w=>{w.toggleAttribute("data-disabled",v),w instanceof HTMLButtonElement?w.disabled=v:w.setAttribute("aria-disabled",v?"true":"false"),w.querySelectorAll("button").forEach(_=>{_.disabled=v})}),ke.dataset.personaComposerStreaming=f?"true":"false",ke.dataset.personaComposerInputDisabled=g?"true":"false",ke.dataset.personaComposerSendDisabled=ys()?"true":"false",ke.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(w=>{(w instanceof HTMLButtonElement||w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement||w instanceof HTMLSelectElement)&&(w.disabled=f)}),Pp(),ZA()}let Ei=s=>{he.setStreaming(s),Lh(s?"stop":"send"),kp()},bs=()=>{je.active||ie&&ie.focus()};x.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>bs(),200)});let vs=null,Pi=!1,Lp=!Ao.hidden,Ir=null,Ip=!P,Sd=null;fe.push(()=>{Sd?.cancel(),Sd=null});let eM=s=>{let l=NS(s);if(l===Xl)return;Xl=l,e.setAttribute("data-persona-conversation-state",l);let f=ep();Yl(),Ip&&(Sd?.cancel(),Sd=DS(ke,l==="active"?f:ep(),l==="active"?"drop":"rise")),ko()},Ny=null,Fy,Uy=null,pa=null,Rp=!1,ki=s=>{let l=Cn(n),f=`${l.variant}|${l.dismiss}|${l.anchor??"bottom"}|${l.align??""}|${l.iconPlacement}|${l.kicker??""}|${l.title}|${l.subtitle}`;(f!==Ny||l.icon!==Fy)&&(Ny=f,Fy=l.icon,Su({host:Ao,iconHolder:nA,kicker:rA,title:sA,subtitle:aA,starterSuggestions:Qu},l));let g=l.message===void 0?null:`${n.layout?.messages?.layout??"bubble"}|${l.message}`;g!==Uy&&(Uy=g,wu(No,l.message,n));let v=s??(R?R.getMessages():n.initialMessages);eM(v);let w=Pi,_=!w&&Yr(l,v),$=_!==Lp;if(Lp=_,pa){Ir?.cancel(),Ir=null,w!==Rp&&(Rp=w,w?Fg(oe,Ao,null):Ng(oe,Ao,pa)),Ja(oe,Ao,!w);return}if($&&!_&&!w&&l.dismiss==="on-first-message"&&Ip){Ir=OS(Ao,j=>{Ir===j&&(Ir=null),!Lp&&!pa&&(Ja(oe,Ao,!1),ko()),j?.cancel()});return}if(Ir){if(!_&&!w)return;Ir.cancel(),Ir=null}let U=!Ao.hidden;Ja(oe,Ao,_),!_&&U&&ko()},Hp=[],Wp=[],Bp=!1,qy=null,Vy,$y=()=>{Wp.length=0;let s=Hp.splice(0,Hp.length);for(let l of s)try{l()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};fe.push($y);let tM=(s,l)=>{let f=Tg(s,l);if(!f)return n.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),H("span");let g=n.suggestions?.starters,v=Eg({item:{...f,behavior:f.behavior??g?.behavior??"send"},index:l,surface:"starter",source:"config",variant:g?.variant??"card",streaming:u?R.isStreaming():!1,config:n,plugins:i,chipsConfig:n.suggestionChipsConfig,session:R,getTextarea:()=>ie,eventTarget:Ao,submitPrompt:Xd});return Wp.push(v),v},Op=()=>{if(Bp)return;Bp=!0;let s=Cn(n);qy=`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`,Vy=s.icon;try{$y(),Fg(oe,Ao,pa),pa=null,Rp=!1;let l=R?R.getMessages():n.initialMessages,f=Yr(s,l),g=0,v=null;for(let w of i)if(w.renderWelcome&&(v=w.renderWelcome({config:s,variant:s.variant,visible:f,defaultRenderer:()=>Ao,sendMessage:_=>{if(!R||R.isStreaming())return;let $=_.trim();$&&R.sendMessage($)},requestRender:()=>Op(),renderStarter:_=>tM(_,g++),storage:p(w.id),onCleanup:_=>{Hp.push(_)}}),v))break;v&&v!==Ao&&(pa=v,Ng(oe,Ao,v))}finally{Bp=!1}ki()},oM=()=>{let s=Cn(n);`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`===qy&&s.icon===Vy||Op()},wd=()=>{ki(),ea||(ie.placeholder=SC(he.getState().activeModeIds,n.composer?.modes)??n.copy?.inputPlaceholder??"How can I help...",!(n.sendButton?.useIcon??!1)&&!R?.isStreaming()&&(we.textContent=n.copy?.sendButtonLabel??"Send")),ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ie.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},nM=!!n.setStoredConversationId,fa=s=>ae(l=>{let f={...l};return delete f[s],f}),Ad=s=>{let l=V[s];return typeof l=="string"?l:null},jy=()=>{let s=V.durableResume;if(!s||typeof s!="object")return null;let l=s;return typeof l.executionId=="string"&&l.executionId.length>0&&typeof l.after=="string"&&l.after.length>0?{executionId:l.executionId,after:l.after}:null};n.clientToken&&(n={...n,getStoredSessionId:()=>Ad("sessionId"),setStoredSessionId:s=>{ae(l=>({...l,sessionId:s}))},clearStoredSessionId:n.clearStoredSessionId??(()=>fa("sessionId")),getStoredConversationId:n.getStoredConversationId??(()=>Ad("conversationId")),setStoredConversationId:n.setStoredConversationId??(s=>{ae(l=>({...l,conversationId:s}))}),clearStoredConversationId:n.clearStoredConversationId??(()=>fa("conversationId"))});let zy=()=>n.clientToken??null,Ky=s=>Cw(s,Y(),n.persistState===!1),Gy=zy(),Zo=Gy?Ky(Gy):null,er={...Zo?{visitorStore:Zo}:{},historyBootstrapReady:D,getStoredMessageCursor:()=>Ad("historyMessageCursor"),setStoredMessageCursor:s=>{if(s===null){fa("historyMessageCursor");return}ae(l=>({...l,historyMessageCursor:s}))},getPendingDisplayProjections:()=>{let s=V.pendingDisplayProjections;if(!s||typeof s!="object")return null;let l=s;return typeof l.conversationId!="string"||!Array.isArray(l.messageIds)?null:{conversationId:l.conversationId,messageIds:l.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:s=>{if(!s){fa("pendingDisplayProjections");return}ae(l=>({...l,pendingDisplayProjections:s}))},getStoredResumableHandle:jy,setStoredResumableHandle:s=>{if(!s){fa("durableResume");return}ae(l=>({...l,durableResume:s}))},shouldResumeDurableConversation:()=>X&&jy()!==null,...nM?{}:{getStoredConversationRevision:()=>Ad("conversationRevision"),setStoredConversationRevision:s=>{if(s===null){fa("conversationRevision");return}ae(l=>({...l,conversationRevision:s}))}}};if(X){let s=n.onExecutionState,l=e.ownerDocument.defaultView,f=!1,g=()=>f=!0,v=()=>f=!1;l?.addEventListener("pagehide",g),l?.addEventListener("pageshow",v),fe.push(()=>{l?.removeEventListener("pagehide",g),l?.removeEventListener("pageshow",v)}),n={...n,reconnectStream:n.reconnectStream??(w=>R.getClient().reconnectClientTokenStream(w)),onExecutionState:w=>{(w||!f)&&er.setStoredResumableHandle?.(w?{executionId:w.executionId,after:w.lastEventId}:null),s?.(w)}}}let rM=()=>{let s=zy();if(s&&Zo?.matches(s,Y(),n.persistState===!1)||!s&&!Zo)return;Zo?.destroy(),Zo=s?Ky(s):null;let l={...er};Zo?l.visitorStore=Zo:delete l.visitorStore,er=l,R.setHistoryInternals(er)},xs=null,sM=()=>{xs==null&&(xs=setInterval(()=>{let s=Te.querySelectorAll("[data-tool-elapsed]");if(s.length===0){clearInterval(xs),xs=null;return}let l=Date.now();s.forEach(f=>{let g=Number(f.getAttribute("data-tool-elapsed"));g&&(f.textContent=vc(l-g))})},100))},Dp=(s,l)=>{if(Object.is(s,l))return!0;if(s===null||l===null||typeof s!="object"||typeof l!="object")return!1;if(Array.isArray(s)||Array.isArray(l))return!Array.isArray(s)||!Array.isArray(l)||s.length!==l.length?!1:s.every((_,$)=>Dp(_,l[$]));let f=s,g=l,v=Object.keys(f),w=Object.keys(g);return v.length===w.length&&v.every(_=>Object.prototype.hasOwnProperty.call(g,_)&&Dp(f[_],g[_]))},Xy=s=>{let{content:l,rawContent:f,llmContent:g,...v}=s;return v},_p=s=>s.role==="assistant"&&s.streaming===!0&&!s.variant&&!s.toolCall&&!s.tools&&!s.approval&&!s.reasoning&&!s.contentParts&&!s.stopReason&&!ql(s),aM=(s,l,f)=>{if(s.length!==l.length)return!1;let g=s[f.index],v=l[f.index];return!g||!v||g.id!==f.id||v.id!==f.id?!1:(!Object.is(g.content,v.content)||!Object.is(g.rawContent,v.rawContent)||!Object.is(g.llmContent,v.llmContent))&&_p(g)&&_p(v)&&Dp(Xy(g),Xy(v))},Np=null,ma=null,Cs=null,tr=null,Fp=null,iM=s=>{if(!X)return la(s);Fp=s,queueMicrotask(()=>{Fp===s&&(Fp=null,la(s))})},Md=s=>{Np=s;let l,f;ma=null;for(let v=s.length-1;v>=0;v-=1){let w=s[v];if(!l&&w.role==="user"&&(l=w),!f&&w.role==="assistant"&&(f=w),!ma&&_p(w)&&(ma={index:v,id:w.id}),l&&f&&ma)break}Jo(Te,s,wt),hr()?.updateInlineArtifactBlocks(Te,Yo.artifacts,{suppressTransition:qo}),sM(),ki(s),ra(s),kr(!qo),zA(s),s.length===0&&(gn(),vi=!0,cd=!1,ia=null,ud=!1),!yp||aa?(yp=!0,fs=l?.id??null,bp=f?.id??null):l&&l.id!==fs?(fs=l.id,UA(l.id)):f&&f.id!==bp&&qA(),f&&(bp=f.id),jA(s);let g=je.lastUserMessageId;l&&l.id!==g&&(je.lastUserMessageId=l.id,x.emit("user:message",l)),je.lastUserMessageWasVoice=!!l?.viaVoice,iM(s),ua()},Up=()=>{tr!==null&&(cancelAnimationFrame(tr),tr=null);let s=Cs;Cs=null,s&&Md(s)},Qy=()=>{tr!==null&&cancelAnimationFrame(tr),tr=null,Cs=null},lM=s=>{let l=Cs??Np;if(qo&&l&&ma&&aM(l,s,ma)){Cs=s,tr===null&&(tr=requestAnimationFrame(()=>{tr=null;let f=Cs;Cs=null,f&&Md(f)}));return}if(s.length===0){Qy(),Md(s);return}Up(),Md(s)};R=new Da(n,{onMessagesChanged(s){lM(s)},onStatusChanged(s){let l=n.statusIndicator??{};jl(at,(g=>g==="idle"?l.idleText??qt.idle:g==="connecting"?l.connectingText??qt.connecting:g==="connected"?l.connectedText??qt.connected:g==="error"?l.errorText??qt.error:g==="paused"?l.pausedText??qt.paused:g==="resuming"?l.resumingText??qt.resuming:qt[g])(s),l,s),Xu()},onStreamingChanged(s){s||(R?.getMessages().length===0?Qy():Up()),qo=s,Ei(s),Xu(),R&&Jo(Te,R.getMessages(),wt),s||(kr(!0),NA(),Sy=!0,R&&wy(R.getMessages(),jr(n))),$t(),Gl(s?"Responding\u2026":"Response complete."),ua()},onVoiceStatusChanged(s){if(x.emit("voice:status",{status:s,timestamp:Date.now()}),!(s!=="disconnected"&&!Wo(n.voiceRecognition?.provider)))switch(s){case"listening":ar(),Ma();break;case"processing":ar(),cT();break;case"speaking":ar(),uT();break;default:s==="idle"&&R.isBargeInActive()?(ar(),Ma(),ne?.setAttribute("aria-label","End voice session")):(je.active=!1,ar(),Jn("system"),mn());break}},onArtifactsState(s){Yo=s,s.artifacts.length===0&&(ta=!1),hr()?.updateInlineArtifactBlocks(Te,s.artifacts,{suppressTransition:qo}),fn(),la()},onHistoryStateChanged(s){Eh(s)},onHistoryNotice(s){Ph(s)},onReconnect(s){let{executionId:l,lastEventId:f}=s.handle;s.phase==="paused"?x.emit("stream:paused",{executionId:l,after:f}):s.phase==="resuming"?x.emit("stream:resuming",{executionId:l,after:f,attempt:s.attempt??1}):x.emit("stream:resumed",{executionId:l,after:f})}},er),dt.current=R,fe.push(()=>R.cancel()),fe.push(()=>{R.destroy(),Zo?.destroy(),Zo=null});let qp=null;if(R.onReadAloudChange((s,l)=>{Zh=s,ey=l,ty();let f=s??qp;s&&(qp=s);let g=f?R.getMessages().find(v=>v.id===f)??null:null;x.emit("message:read-aloud",{messageId:f,message:g,state:l,timestamp:Date.now()}),l==="idle"&&(qp=null)}),u=!0,yp=!0,n.voiceRecognition?.enabled===!0&&Wo(n.voiceRecognition.provider))try{R.setupVoice()}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",s)}let dM=720,cM=250,Qe=ph(n.features?.history?.copy),jo=null,Vp=!1,it=null,Td=null,Ed="conversation",$p=null,fo=null,In=null,Pd=R.getHistoryState(),jp=null,Li=0,zp=null,kd=null,Ld=null,Kp=`persona-history-${Math.random().toString(36).slice(2,8)}`,Gp=()=>n.features?.history?.enabled===!0,Rn=()=>Gp()&&!!jo&&!Vp,Yy=()=>{let s=R.getStatus();return qo||s==="paused"||s==="resuming"},Xp=()=>{let s=n.features?.history?.scope;if(s)return s;let l=n.getIdentityProof?"verified-user":"browser",f=jo?.capabilities.scopes;return!f||f.includes(l)?l:f[0]??l},ga=()=>Td?.scope??Xp(),Jy=()=>R.getClientSession()?.targetId??null,Zy=s=>`${s.state}:${"reason"in s?s.reason:""}`,uM=s=>{let l=Zy(s);l!==jp&&(jp=l,x.emit("history:identityStatusChanged",{status:s,timestamp:Date.now()}))},Id=s=>{s&&(zn.textContent="",zn.textContent=s)},eb=null,tb=null,pM=()=>{if(!Gp())return null;let s=Tw();if(s)return s();let l=n.features?.history?.provider;return l?typeof l!="function"?l:(eb!==l&&(eb=l,tb=l()),tb):R.isClientTokenMode()?Ew({client:R.getClient(),getIdentityProofConfigured:()=>typeof n.getIdentityProof=="function",onActivationCommitted:f=>R.bindActivatedSession(f),getClient:()=>R.getClient()}):null},ob=()=>{kd?.(),kd=null,Ld?.(),Ld=null,Vp=!1,jo=pM();let s={...er};jo?s.historyProvider=jo:delete s.historyProvider,er=s,R.setHistoryInternals(er),jo&&(kd=jo.subscribeAvailability?.(l=>{Vp=!l,l||Lo({restoreFocus:!1}),Hr()})??null,Ld=jo.subscribeIdentityStatus(l=>uM(l)),jp=Zy(jo.getIdentityStatus()))},Qp=()=>{let s=n.features?.history?.presentation??"panel";if(s==="panel"||s==="auto"&&!(!pe||Ct(n)))return"panel";let l=En??de;return(l.getBoundingClientRect().width||l.clientWidth)>=dM?"rail":"panel"},en=(s,l)=>{l?(s.setAttribute("aria-hidden","true"),s.setAttribute("inert","")):(s.removeAttribute("aria-hidden"),s.removeAttribute("inert"))},Rd="data-persona-history-suppressed",zo=null,Rr=null,Ss=null,Ii=null,Yp=null,nb="",rb=()=>Ae===Yp?nb:n.layout?.showHeader===!1?"none":"",fM=()=>Wt==="panel"&&!!Ss&&Ii===Ss.element&&n.layout?.showHeader!==!1&&rb()!=="none",mM=()=>{for(let s of Array.from(Ae.children))s!==zo&&s.setAttribute(Rd,"")},gM=()=>{for(let s of Array.from(de.querySelectorAll(`[${Rd}]`)))s.removeAttribute(Rd)},hM=()=>{let s=Ss;if(!s)return;if(Array.from(Ae.children).some(g=>g!==zo&&!g.hasAttribute(Rd))){Rr&&Rr!==Ae&&(Rr.style.removeProperty("min-height"),Rr=null);let g=Ae.offsetHeight;g>0&&(Ae.style.minHeight=`${g}px`,Rr=Ae)}zo||(zo=H("div","persona-history-header-host")),s.setHeaderPlacement("external");let f=s.getHeaderElement();f.parentNode!==zo&&zo.replaceChildren(f),zo.parentNode!==Ae&&Ae.appendChild(zo),mM()},sb=()=>{Rr&&(Rr.style.removeProperty("min-height"),Rr=null),zo&&(Ss?.setHeaderPlacement("inline"),zo.remove(),zo=null,gM())},Hd=null,Jp=()=>{if(Hd){if(oe.style.display="none",en(oe,!0),ke.hidden=!0,en(ke,!0),fM()){hM(),Ae.style.display=rb(),en(Ae,!1);return}sb(),Ae.style.display="none",en(Ae,!0)}};Gu=Jp;let yM=s=>{let l=oe.style.display,f=ke.hidden,g=ke,v=Ae,w=Ae.style.display;Yp=v,nb=w,Hd=()=>{Hd=null,sb(),Yp=null,oe.style.display=l,en(oe,!1),g.hidden=f,en(g,!1),ke!==g&&(ke.hidden=!1,en(ke,!1)),v.style.display=w,en(v,!1),Ae!==v&&(Ae.style.display=n.layout?.showHeader===!1?"none":"",en(Ae,!1))},ke.parentNode?.insertBefore(s,ke),Jp()},ha=null,ws=null,Ri=null,ya=null,ab=()=>[Ae,Oe.closeButtonWrapper,Oe.clearChatButtonWrapper,oe,ke],bM=52,Wd=()=>n.features?.history?.rail?.collapsible!==!1,ba=()=>n.features?.history?.rail?.side==="right"?"right":"left",Zp=200,ef=400,tf=s=>Math.min(ef,Math.max(Zp,Math.round(s))),vM=()=>n.features?.history?.rail?.resizable===!0,Hi,xM=()=>{if(Hi===void 0&&(Hi=null,n.persistState!==!1))try{let s=Number(window.localStorage.getItem(`${Y()}rail-width`));s&&(Hi=s)}catch{}return Hi},Wi=()=>tf(xM()??n.features?.history?.rail?.width??260),CM=s=>{if(Hi=s,n.persistState!==!1)try{window.localStorage.setItem(`${Y()}rail-width`,String(s))}catch{}},Bd=()=>Wd()&&n.features?.history?.rail?.collapsedBehavior==="overlay",Dt=!1,ib=s=>{let l=H("img");return l.src=s,l.alt="",l.setAttribute("aria-hidden","true"),l},SM=()=>{let s=n.features?.history?.rail?.brand;if(!s)return;let l=!1,f;return g=>{if(s.render)try{return s.render({collapsed:g})??null}catch(v){return l||(l=!0,console.warn("[persona] history rail brand threw",v)),null}return f===void 0&&(s.iconUrl?f=ib(s.iconUrl):f=s.icon?le(s.icon,20):null),f?f.cloneNode(!0):null}},wM=()=>n.features?.history?.rail?.sections?.map(s=>{let l=!1,f=g=>{l||(l=!0,console.warn("[persona] history rail section threw",s.id,g))};return{id:s.id,title:s.title,placement:s.placement??"above-conversations",items:s.items.map(g=>{let v;return{id:g.id,label:g.label,badge:g.badge,iconNode:()=>{if(v!==void 0)return v;try{g.renderIcon?v=g.renderIcon()??null:g.iconUrl?v=ib(g.iconUrl):v=g.icon?le(g.icon,20):null}catch(w){f(w),v=null}return v},onSelect:()=>{try{g.onSelect()}catch(w){f(w)}}}})}})??[],AM=s=>{let l=wM();for(let f of s)l.some(g=>g.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):l.push(f);return l.length?l:void 0},Bi=null,lb=()=>`${Y()}rail-collapsed`,of=()=>{if(Bi===null&&(Bi=n.features?.history?.rail?.defaultCollapsed===!0,n.persistState!==!1))try{let s=window.localStorage.getItem(lb());s&&(Bi=s==="1")}catch{}return Bi},nf=s=>{if(Bi=s,n.persistState!==!1)try{window.localStorage.setItem(lb(),s?"1":"0")}catch{}},Oi=()=>Wt==="rail"&&Wd()&&!Bd()&&of(),rf=()=>{},db=()=>{if(Bd()){rf();return}nf(!of()),it?.view.setCollapsed(Oi()),jn(),ko()},sf=()=>{let s=n.features?.history?.rail?.collapseShortcut;return!s||!cu(s)?null:{combo:s,hint:uu(s),aria:Ml(s)}},cb=()=>{c.forEach(l=>l()),c=[];let s=sf();s&&c.push(d.register({id:"history-rail-collapse",combo:s.combo,scope:n.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>At&&Wt==="rail"&&Wd()||xa(),run:()=>Bd()?rf():db()}));for(let l of n.layout?.header?.trailingActions??[])l.shortcut&&c.push(d.register({id:`header-action-${l.id}`,combo:l.shortcut,run:()=>{let f=e.querySelector(`[data-persona-header-action="${l.id}"]`);f?f.click():n.layout?.header?.onAction?.(l.id)}}));for(let l of i)for(let f of l.shortcuts??[])c.push(d.register({...f,id:`${l.id}:${f.id}`}))};cb();let MM=300,Od="var(--persona-history-overlay-margin,8px)",tn=null,or=null,Dd=0,nr=null,va=null,As=!1,af=0,ub=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,xa=()=>Rn()&&Bd()&&(Wt??Qp())==="rail",TM=()=>At&&!Dt,Di=()=>{va!==null&&clearTimeout(va),va=null},EM=()=>{dh().catch(()=>{})},pb=()=>{Di(),Dt&&(va=setTimeout(()=>{va=null,!(As||!Dt)&&(nr?.contains(document.activeElement)||Lo({restoreFocus:!1}))},MM))},PM=(s,l)=>{let f=nr?.getBoundingClientRect();if(!f)return!1;let g=tn?.getBoundingClientRect(),v=g?Math.min(g.top,f.top):f.top;return s>=f.left&&s<=f.right&&l>=v&&l<=f.bottom||!!g&&s>=g.left&&s<=g.right&&l>=g.top&&l<=g.bottom},lf=s=>{Dt&&(As=PM(s.clientX,s.clientY),As?Di():va===null&&pb())},fb=s=>{At||!xa()||(Dt=!0,Ni({invoker:tn,keyboard:s?.keyboard===!0}).then(()=>{At?!As&&document.activeElement!==tn&&Lo():Dt=!1}))},mb=()=>{let s=Ii?.querySelector('[data-persona-history-focus="collapse"]');s&&(s.setAttribute("aria-label",Dt?Qe.expandLabel:Qe.collapseLabel),s.setAttribute("aria-expanded",Dt?"false":"true"))},gb=()=>{nf(!1);let s=it;if(!Dt||!s){Ni({invoker:tn});return}let l=document.activeElement===tn;Dt=!1,_d(),s.element.remove(),cf(s.element),mb(),l&&Fd(),ko(),Hr()},kM=()=>{nf(!0),Lo()};rf=()=>{!At||Dt?gb():kM()};let LM=()=>{let s=sf(),l=Ns({ariaLabel:Qe.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":Kp,...s?{"aria-keyshortcuts":s.aria}:{}}}),f=l.button;f.addEventListener("mouseenter",()=>{As=!0,Di(),!(ub()||Date.now()<af)&&fb()}),f.addEventListener("mouseleave",()=>{As=!1,af=0,pb()}),f.addEventListener("focus",()=>{At||EM()}),f.addEventListener("click",g=>{Rn()&&(g.detail!==0&&ub()&&!At?fb():gb())}),tn=f,or=l.wrapper},_i=()=>{if(or&&!or.isConnected&&(or=null,tn=null),!xa()){or?.remove(),or=null,tn=null;return}tn||LM();let s=or,l=tn;if(!s||!l)return;let f=ba()!=="right"?Ae.firstChild:null;(f??Ae.lastChild)!==s&&Ae.insertBefore(s,f),s.style.display=TM()||Dd>0?"none":"",l.setAttribute("aria-label",Qe.expandLabel),l.setAttribute("aria-expanded",At?"true":"false"),nr&&jn()},hb=s=>{if(!Dt)return;let l=s.target;l instanceof Node&&(nr?.contains(l)||or?.contains(l)||l instanceof Element&&l.closest('.persona-dropdown-menu,[role="alertdialog"]')||Lo({restoreFocus:!1}))};document.addEventListener("pointerdown",hb,!0),fe.push(()=>{document.removeEventListener("pointerdown",hb,!0),document.removeEventListener("pointermove",lf),Ca?.(),Di()});let df=null,Ca=null,yb=16,bb=s=>{CM(tf(s)),jn(),ko()},IM=()=>{let s=H("div","persona-rail-resizer");return s.tabIndex=0,s.setAttribute("role","separator"),s.setAttribute("aria-orientation","vertical"),s.setAttribute("aria-valuemin",String(Zp)),s.setAttribute("aria-valuemax",String(ef)),s.addEventListener("pointerdown",l=>{let f=ws;if(!f||l.button!==0)return;l.preventDefault(),Ca?.();let g=l.clientX,v=f.getBoundingClientRect().width||Wi(),w=ba()==="right"?-1:1,_=v,$=e.ownerDocument;f.style.transition="none";let U=J=>{_=tf(v+w*(J.clientX-g)),f.style.flex=`0 0 ${_}px`,s.setAttribute("aria-valuenow",String(_))},j=()=>{Ca=null,$.removeEventListener("pointermove",U),$.removeEventListener("pointerup",j),$.removeEventListener("pointercancel",j),f.style.removeProperty("transition");try{s.releasePointerCapture(l.pointerId)}catch{}bb(_)};Ca=j,$.addEventListener("pointermove",U),$.addEventListener("pointerup",j),$.addEventListener("pointercancel",j);try{s.setPointerCapture(l.pointerId)}catch{}}),s.addEventListener("keydown",l=>{let f=ba()==="right"?-yb:yb,g=Wi(),v=l.key==="ArrowRight"?g+f:l.key==="ArrowLeft"?g-f:l.key==="Home"?Zp:l.key==="End"?ef:null;v!==null&&(l.preventDefault(),bb(v))}),s},RM=(s,l)=>{if(!vM()||Oi()){Ca?.(),df?.remove();return}let f=df??IM();df=f,f.setAttribute("aria-label",Qe.resizeLabel),f.setAttribute("aria-valuenow",String(Wi())),f.nextElementSibling!==l&&s.insertBefore(f,l)};jn=()=>{it?.view.setRailSide(ba());let s=ba()==="right",l=nr;if(l){let $=tn?tn.getBoundingClientRect().bottom-de.getBoundingClientRect().top:0;l.style.top=`calc(${Math.max(0,Math.round($))}px + ${Od})`,l.style.width=`${Wi()}px`,l.style.left=s?"":Od,l.style.right=s?Od:""}let f=ws,g=ha,v=Ri;if(!f||!g||!v)return;f.style.flex=`0 0 ${Oi()?bM:Wi()}px`;let w="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=s?"":w,f.style.borderLeft=s?w:"";let _=s?v:f;g.firstElementChild!==_&&g.append(_,s?f:v),RM(g,s?f:v)};let vb=s=>{if(ya&&ws){ya.replaceWith(s),ya=null,jn();return}let l=H("div","persona-history-rail-shell");l.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=H("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let g=H("div","persona-history-rail-host");g.style.cssText="display:flex;min-height:0;overflow:hidden",de.insertBefore(l,Ae.parentNode===de?Ae:oe);for(let v of ab())v?.parentNode===de&&f.appendChild(v);l.append(g,f),g.appendChild(s),ha=l,ws=g,Ri=f,jn()},HM=()=>{if(ha)return;let s=H("div","persona-history-rail-placeholder");s.style.cssText="flex:1 1 auto;min-height:0",ya=s,vb(s),ko()},xb=()=>{ya&&(_d(),ko())},WM=s=>{let l=H("div","persona-history-rail-overlay");l.style.cssText=`position:absolute;bottom:${Od};display:flex;overflow:hidden;z-index:${qa-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,de.style.position="relative",de.appendChild(l),l.appendChild(s),document.addEventListener("pointermove",lf),nr=l,jn(),mb()},_d=()=>{Hd?.(),nr&&(As&&(af=Date.now()+150),document.removeEventListener("pointermove",lf),nr.remove(),nr=null);let s=ha;if(s){Ca?.();for(let l of ab())l&&s.contains(l)&&de.insertBefore(l,s);s.remove(),ha=null,ws=null,Ri=null,ya=null}},Cb=s=>{Ii=s,s.id=Kp,s.style.flex="1 1 auto",s.style.minHeight="0"},cf=s=>{Cb(s),(Wt!=="rail"||Dt)&&xb(),Wt!=="rail"?yM(s):Dt?WM(s):vb(s)},Nd=()=>{if(_i(),Rb(),!At||!it)return;let s=Qp();if(s===Wt)return;let l=document.activeElement,f=l instanceof HTMLElement&&(it.element.contains(l)||zo?.contains(l)===!0)?l:null;_d(),it.element.remove(),it.view.setHeaderPlacement("inline"),Wt=s,it.view.setPresentation(s),it.view.setCollapsed(Oi()),it.requestRender(),it.element.isConnected||cf(it.element),f?.isConnected?f.focus():Fd(),$t(),ko(),Hr()},Sb=(s,l)=>zo?.querySelector(l)??s.querySelector(l),Fd=()=>{let s=it?.element??Ii;if(!s)return;let l=Sb(s,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(l){l.focus();return}let f=Sb(s,".persona-history-title")??s;f.tabIndex=-1,f.focus()},Ni=async s=>{if(!Rn()||At)return;let l=jo;if(!l)return;if(!Dt&&xa()&&of()){_i();return}Ud();let f=++Li;Ed=s?.returnSurface??"conversation",$p=s?.invoker??fo;let g=xa()&&!Dt;g&&(Dd+=1,_i(),HM());let v;try{v=await dh()}catch{Id(Qe.openHistoryLabel),g&&(Dd-=1,f===Li&&(xb(),_i()));return}if(g&&(Dd-=1),f!==Li||At)return;Td={scope:Xp()},Wt=Qp(),At=!0;let w=Wt==="panel"&&n.layout?.showHeader!==!1&&Ae.style.display!=="none"?"external":"inline",_=n.features?.history?.rowAvatar,$=sf(),U=$?{hint:$.hint,aria:$.aria}:null,j={provider:l,context:Td,targetId:Jy(),presentation:Wt,collapsible:Wd(),collapsed:Oi(),railSide:ba(),renderRailHeader:n.features?.history?.rail?.renderHeader,railBrand:SM(),onToggleCollapse:db,...U?{collapseShortcut:U}:{},headerPlacement:w,showScopeStatus:n.features?.history?.showScopeStatus!==!1,showDelete:n.features?.history?.showDelete!==!1,showDeleteAll:n.features?.history?.showDeleteAll!==!1,...n.features?.history?.listActions?.length?{listActions:n.features.history.listActions}:{},rowAvatar:_===!1?!1:typeof _=="string"?_:n.launcher?.iconUrl,activeConversationId:R.getActiveConversationId(),...n.features?.history?.grouping?{grouping:n.features.history.grouping}:{},...n.features?.history?.copy?{copy:n.features.history.copy}:{},...n.features?.history?.pageSize!==void 0?{pageSize:n.features.history.pageSize}:{},onSelect:J=>pf(J,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:J=>Ms(J),attachTooltip:Jt,onStartNew:()=>ff({focusComposer:!0}),onClose:()=>Lo(),onRequestDeleteConversation:J=>Ib(J),onRequestClearHistory:()=>FM(),...l.resetDevice?{onRequestResetIdentity:()=>UM()}:{}};it=Mw({plugins:i,config:n,getPresentation:()=>Wt??"panel",getReturnSurface:()=>Ed,close:()=>Lo(),createView:({slots:J,renderDom:re,onModelChange:ce,railSections:Ye})=>(Ss=v.createHistoryView({...j,railSections:AM(Ye),slots:J,renderDom:re,onModelChange:ce,onAnnounce:Id}),Ss),onElementChanged:(J,re)=>{if(!re?.isConnected)return cf(J);Cb(J),re.replaceWith(J),Jp()}}),it.view.setNewConversationRequired(Pd.recovery==="new_conversation_required"),s?.focus!==!1&&(Wt!=="rail"||s?.keyboard===!0)&&Fd(),$t(),ko(),Hr(),x.emit("history:opened",{presentation:Wt,returnSurface:Ed,timestamp:Date.now()})},Ud=()=>{},Lo=s=>{if(!At)return;Li+=1;let l=Ed,f=$p,g=it,v=s?.restoreFocus!==!1;At=!1;let w=!1,_=null,$=()=>{if(!w){if(w=!0,Ud=()=>{},_!==null&&clearTimeout(_),Dt=!1,Di(),_d(),g?.dispose(),g?.view.destroy(),g?.element.remove(),it===g&&(it=null,Ss=null,Ii=null,Wt=null,Td=null,$p=null),$t(),ko(),Hr(),v){let j=f??fo;j?.isConnected?j.focus():bs()}x.emit("history:closed",{returnSurface:l,timestamp:Date.now()})}},U=g&&g.element===g.view.element?g.view.playExit():null;if(!U){$();return}Ud=$,_=setTimeout($,cM),U.then($)},wb=s=>{if(!(s.key!=="Escape"||!At||!it)){if(Wt==="rail"){let l=s.target;if(!(l instanceof Node)||!(it.element.contains(l)||Dt&&or?.contains(l)===!0))return}s.preventDefault(),s.stopPropagation(),Lo()}};de.addEventListener("keydown",wb),fe.push(()=>de.removeEventListener("keydown",wb));let qd=null,Ab=!1,Fi=()=>{if(!xr)return;let s=n.layout?.header?.titleSource==="conversation",l=s&&qd?.trim()||null;xr.textContent=l??n.launcher?.title??"Chat Assistant";let f=xr.closest(".persona-combo-btn");if(!f)return;let g=!s||R.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",g?"false":"true"),f.setAttribute("aria-haspopup",g?"true":"false"),g||f.setAttribute("aria-expanded","false"),f.style.cursor=g?"pointer":"default";let v=f.querySelector("svg");v&&(v.style.display=g?"":"none")},BM=s=>{s!==qd&&(qd=s,Fi())},Ms=s=>{Ab=s?.starred===!0,BM(s&&s.title.trim()||null),Fi()};Fi(),de.addEventListener("persona:title-menu-builtin",s=>{let l=s.detail?.actionId,f=R.getActiveConversationId();f&&(l==="delete"?Ib(f):l==="star"&&R.canUpdateConversations()&&mf(f,{starred:!Ab}).catch(()=>{}))});let Vd=0,OM=250,$d=null,jd=()=>{$d&&clearTimeout($d),$d=null};fe.push(jd);let Mb=()=>{jd();let s=vs;s&&(Pi=!0,s.hidden=!1,Te.style.display="none",ki())},zd=()=>{Vd+=1,jd(),vs&&(vs.remove(),vs=null,Pi=!1,Te.style.removeProperty("display"),en(ke,!1),ki())},DM=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Te.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},uf=(s,l)=>Q("div",{className:yo("persona-conversation-loading-bubble",l&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:s}}),Tb=()=>Q("div",{className:"persona-conversation-loading-body"},uf("58%",!1),uf("72%",!0),uf("44%",!1)),Eb=s=>{vs?.remove(),vs=s,s.hidden=!Pi,oe.insertBefore(s,Te),jd(),Pi||($d=setTimeout(Mb,OM)),en(ke,!0)},_M=()=>{let s={config:n,streaming:!1,location:"conversation-open",defaultRenderer:Tb},l=null,f=i.find(g=>g.renderLoadingIndicator);f?.renderLoadingIndicator&&(l=f.renderLoadingIndicator(s)),l===null&&n.loadingIndicator?.render&&(l=n.loadingIndicator.render(s)),Eb(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},l??Tb()))},NM=s=>{let l=()=>{pf(s,{focusComposer:!0}).catch(()=>{})},f=Rn()?()=>{zd(),Ni()}:void 0,g=($,U)=>{let j=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:$});return j.addEventListener("click",U),j},v=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},g(Qe.openConversationRetryLabel,l),f?g(Qe.openConversationBackLabel,f):null)),w=Object.freeze({conversationId:s,config:n,copy:Object.freeze({title:Qe.openConversationErrorTitle,retryLabel:Qe.openConversationRetryLabel,backLabel:Qe.openConversationBackLabel}),retry:l,...f?{back:f}:{},defaultRenderer:v}),_=null;for(let $ of i)if($.renderHistoryOpenError){try{_=$.renderHistoryOpenError(w)}catch(U){console.warn("[persona] renderHistoryOpenError threw",U),_=null}if(_)break}Eb(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},_??v())),Mb()};x.on("history:closed",()=>{vs&&en(ke,!0)});let pf=async(s,{focusComposer:l=!1}={})=>{let f=ga(),g=!!it;it?.view.setActiveConversationId(s),zd();let v=Vd;_M(),At&&(Wt==="panel"||Dt)&&Lo({restoreFocus:!1}),aa=!0;try{await R.openConversation(s,{scope:f})}catch(w){throw v===Vd&&NM(s),w}finally{aa=!1}v===Vd&&(zd(),Ot.clear(),gn(),Po(),Ap()||hd(),DM(),rr(),g||Ms(null),x.emit("history:conversationOpened",{conversationId:s,title:qd,scope:f,timestamp:Date.now()}),l&&bs())},ff=async({focusComposer:s=!1}={})=>{zd(),await R.startNewConversation({scope:ga()}),Ms(null),Ot.clear(),gn(),Po(),hd(),rr();let l=R.getActiveConversationId();it?.view.setActiveConversationId(l),x.emit("history:conversationStarted",{conversationId:l,timestamp:Date.now()}),At&&(Wt==="panel"||Dt)&&Lo({restoreFocus:!1}),s&&bs()},mf=async(s,l)=>{let f=await R.updateConversation(s,{...l,...l.title!==void 0?{title:l.title.trim()}:{}});return it?.view.applyConversationSummary(f),!it&&s===R.getActiveConversationId()&&Ms(f),f},Pb=async s=>{let l=ga(),f=R.getActiveConversationId()===s;await R.deleteConversation(s,{scope:l}),it?.view.removeConversationSummary(s),f&&(Ms(null),Ot.clear(),gn(),Po(),rr()),x.emit("history:conversationDeleted",{conversationId:s,scope:l,wasActive:f,timestamp:Date.now()})},kb=async s=>{let l=s?.scope??ga(),f=s?.allTargets?null:s?.targetId??Jy(),g=await R.clearConversationHistory({...f?{targetId:f}:{},scope:l});return Ms(null),Ot.clear(),gn(),Po(),rr(),x.emit("history:cleared",{deleted:g.deleted,scope:l,targetId:f,timestamp:Date.now()}),g},Lb=async()=>{if(!jo?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let s=!1;try{s=(await R.resetHistoryDevice()).remoteRevocationConfirmed}finally{Ms(null),R.clearArtifacts(),Ot.clear(),Np=null,n.clearStoredSessionId?.(),n.clearStoredConversationId?.(),V={},be.syncFromMetadata(),N?.clear&&fd(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),gn(),Po(),rr(),Lo({restoreFocus:!1}),bs(),ve||Tt?.launcher.element.focus()}return Id(s?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),x.emit("history:identityReset",{remoteRevocationConfirmed:s,timestamp:Date.now()}),{remoteRevocationConfirmed:s}},gf=()=>En?Ce:de,Ib=async s=>await Ou({host:gf(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Pb(s),"deleted"):"cancelled",FM=async()=>{let s=ga()==="verified-user";return await Ou({host:gf(),title:Qe.clearHistoryConfirmTitle,description:s?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await kb(),"cleared"):"cancelled"},UM=async()=>{if(!await Ou({host:gf(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:l}=await Lb();return{outcome:"reset",remoteRevocationConfirmed:l}},on=H("button","persona-history-earlier");on.type="button",on.textContent=Qe.showEarlierMessagesLabel,on.setAttribute("data-persona-history-earlier",""),Object.assign(on.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let rr=()=>{if(!(Rn()&&!!Pd.nextMessageCursor&&!!R.getActiveConversationId())){on.remove();return}on.textContent=Qe.showEarlierMessagesLabel,on.parentNode!==oe&&oe.insertBefore(on,oe.firstChild)};on.addEventListener("click",()=>{let s=R.getActiveConversationId(),l=Pd.nextMessageCursor;if(!s||!l||on.disabled)return;on.disabled=!0;let f=oe.scrollHeight,g=oe.scrollTop;R.loadOlderMessages(s,l,{scope:ga()}).then(()=>{oe.scrollTop=g+(oe.scrollHeight-f),ko()}).catch(()=>{}).finally(()=>{on.disabled=!1,rr()})});let qM=()=>{let s=Ns({ariaLabel:Qe.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return s.button.addEventListener("click",l=>{if(!(!Rn()||Yy())){if(At){Lo();return}Ni({invoker:s.button,keyboard:l.detail===0})}}),s},Rb=()=>{if(!Rn()){In?.remove(),fo=null,In=null;return}if(In&&!In.isConnected&&(fo=null,In=null),!fo&&Ae){let g=qM();fo=g.button,In=g.wrapper;let v=Oe.clearChatButtonWrapper||Oe.closeButtonWrapper;v?.parentNode&&Ae.contains(v)?v.parentNode.insertBefore(In,v):Ae.appendChild(In)}if(!fo||!In)return;let s=xa()||At&&Wt==="rail";if(In.style.display=s?"none":"",s){document.activeElement===fo&&Fd();return}let l=Yy();fo.disabled=l,fo.setAttribute("aria-disabled",l?"true":"false");let f=l?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;fo.setAttribute("aria-label",f),(n.features?.history?.presentation??"panel")==="panel"?(fo.removeAttribute("aria-expanded"),fo.removeAttribute("aria-controls")):(fo.setAttribute("aria-expanded",At?"true":"false"),fo.setAttribute("aria-controls",Kp))},Kd=!1,VM=()=>{let s=Oe.clearChatButton;if(s){if(Rn()){Kd||(zp=s.getAttribute("aria-label")??"",Kd=!0),s.setAttribute("aria-label",Qe.newConversationLabel),s.removeAttribute("title");return}Kd&&(Kd=!1,zp&&s.setAttribute("aria-label",zp))}},Hr=()=>{Qe=ph(n.features?.history?.copy),Rb(),_i(),VM(),rr()};Xu=Hr,Eh=s=>{Pd=s,it?.view.setNewConversationRequired(s.recovery==="new_conversation_required"),Ei(s.sendBlocked||qo),rr()},Ph=s=>{(s.code==="history_continuity_reset"||s.code==="conversation_deleted_recovered")&&(Ot.clear(),gn(),Po()),Id(s.message),it?.view.refresh()},ob(),Hr(),fe.push(()=>{kd?.(),Ld?.(),Li+=1,Ud(),it?.dispose(),it?.view.destroy(),it=null}),n.clientToken&&R.initClientSession().then(()=>{if(Rn())return R.reconcileBootConversation({scope:Xp()})}).then(()=>{rr()}).catch(s=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",s)}),(k||n.onSSEEvent)&&R.setSSEEventCallback((s,l)=>{n.onSSEEvent?.(s,l),Ku(s,l)});let Hb=()=>{let s=n.resume??(X?er.getStoredResumableHandle?.():null);s&&typeof n.reconnectStream=="function"&&R.resumeFromHandle(s)};P?P.then(s=>{if(s){if(s.metadata&&(V=fh(s.metadata),be.syncFromMetadata()),s.messages?.length){aa=!0;try{R.hydrateMessages(s.messages)}finally{aa=!1}xd()}s.artifacts?.length&&R.hydrateArtifacts(s.artifacts,s.selectedArtifactId??null),ky(s.draft)}}).catch(s=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",s)}).finally(()=>{Ip=!0,O(),Hb()}):(ky(W),Hb());let $M=()=>{!Le()||ve||!(n.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},jM=(s,l)=>s?l?{refs:[...s.refs,...l.refs],finalize:async()=>{let[f,g]=await Promise.allSettled([s.finalize(),l.finalize()]),v=[];return f.status==="fulfilled"?v.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),g.status==="fulfilled"?v.push(g.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",g.reason),mL(v)}}:s:l,hf=()=>{let l=ie.getInlineMessageFields?.();return l&&l.contentSegments.some(g=>g.kind==="mention")?l.contentSegments:void 0},sr=!1,Ts=null,Gd=()=>{ie.value="",ie.style.height="auto",An(),qi()},yf="data-persona-composer-notice",Sa=null;function zM(s){Gl(s),!(Le()||!at)&&(at.hasAttribute(ii)||(at.setAttribute(yf,""),at.setAttribute("role","status"),at.setAttribute("aria-live","polite"),at.textContent=s,Sa&&clearTimeout(Sa),Sa=setTimeout(()=>{if(Sa=null,!!at?.hasAttribute(yf)&&(at.removeAttribute(yf),at.removeAttribute("role"),at.removeAttribute("aria-live"),u)){let l=R.getStatus();jl(at,kh(l),n.statusIndicator??{},l)}},4e3)))}function KM(){let s=he.getState().pendingSubmission;s&&(Js(void 0),ie&&(ie.value=s.text,ie.dispatchEvent(new Event("input",{bubbles:!0})),An()),s.options.selectedModelId&&(he.setSelectedModelId(s.options.selectedModelId),Sr?.repaint()),s.options.activeModeIds?.length&&Jl(s.options.activeModeIds),s.options.quote&&Mn(s.options.quote),ie?.focus())}let GM=s=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",s)},Wb=(s={})=>{let l=(s.overrideText??ie?.value??"").trim();return s.resolveInlineCommand&&l?(Rt?.takeInlineCommand(l)??Promise.resolve(null)).then(f=>Bb(s,l,f)):Bb(s,l,null)},Bb=(s,l,f)=>{if(f?.kind==="action"){Gd(),Rt?.clear(),ts();return}let g=f?.kind==="server"?f.mentions:null,v=f?.kind==="prompt"?f.sendText:l,w=s.pending?.contentParts,_=(Ze?.hasAttachments()??!1)||(w?.length??0)>0;if(!BC({text:v,hasAttachments:_,attachmentsReady:Ze?.isReady()??!0,hasMentions:Rt?.hasMentions()??!1,hasServerMentions:!!g,inputDisabled:Ln(),sendDisabled:ys()}))return;let $=R.isStreaming()?rp():"block";if($==="defer-one"&&!s.pending){if(he.getState().pendingSubmission){zM("One message is already queued. Edit or remove it first.");return}XM({intent:s,sendText:v,serverMentions:g});return}let U={text:v,mentionRefs:[...Rt?.getMentionRefs()??[],...g?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:hf(),options:{...he.getState().selectedModelId&&{selectedModelId:he.getState().selectedModelId},...he.getState().activeModeIds.length>0&&{activeModeIds:[...he.getState().activeModeIds]},...he.getState().quote&&{quote:{...he.getState().quote}}},viaVoice:s.viaVoice};s.pending&&(U.options={...s.pending.options},U.contentSegments=s.pending.contentSegments,U.mentionRefs=[...s.pending.mentionRefs],U.viaVoice=s.pending.viaVoice);let j=()=>{if(w?.length)return[...w];if(!Ze?.hasAttachments())return;let ft=[...Ze.getContentParts()];return U.text&&ft.push(an(U.text)),ft};U.contentParts=j();let J=()=>{cs(),$M();let ft=Rt?.collectForSubmit()??null,Gt=jM(ft,g),_t=j();s.consumeDraft!==!1&&Gd();let Pt={selectedModelId:U.options.selectedModelId,activeModeIds:U.options.activeModeIds},io=$==="interrupt";io&&R.cancel(),R.sendMessage(U.text,{contentParts:_t,mentions:Gt??void 0,contentSegments:U.contentSegments,viaVoice:U.viaVoice,composerOptions:Pt,...U.options.quote&&{quote:U.options.quote},...io&&{interrupt:!0}}),Ze?.hasAttachments()&&Ze.clearAttachments(),ft&&Rt?.clear(),ts();let et=he.getState().activeModeIds,lo=CC(et,n.composer?.modes);lo.length!==et.length&&Jl(lo),he.getState().quote&&Mn(void 0),gd(),dp.release(),un()},re=n.composer?.onBeforeSend;if(!re){J();return}let ce=new AbortController;Ts=ce;let Ye=ft=>{if(Ts=null,ft.status==="error"){GM(ft.error);return}ft.status==="proceed"&&J()},ct=OC(re,U,ce.signal);if(!(ct instanceof Promise)){Ye(ct);return}return he.setPreparing(!0),ct.then(Ye).finally(()=>he.setPreparing(!1))};function XM(s){let l=he.getState(),f=Ze?.hasAttachments()??!1,g=f?[...Ze.getContentParts()]:[];f&&s.sendText&&g.push(an(s.sendText));let v=lg({text:s.sendText,contentParts:g.length?g:void 0,mentionRefs:[...Rt?.getMentionRefs()??[],...s.serverMentions?.refs??[]],contentSegments:hf(),options:{...l.selectedModelId&&{selectedModelId:l.selectedModelId},...l.activeModeIds.length>0&&{activeModeIds:[...l.activeModeIds]},...l.quote&&{quote:{...l.quote}}},viaVoice:s.intent.viaVoice});Js(v),s.intent.consumeDraft!==!1&&Gd(),f&&Ze.clearAttachments(),Rt?.clear(),ts(),l.quote&&Mn(void 0),gd(),dp.release(),un(),Gl("Message queued. It sends when the response finishes.")}function QM(){let s=he.getState().pendingSubmission;s&&(Js(void 0),Qd(s.text,{consumeDraft:!1,pending:s}))}function YM(s){if(n.messageActions?.showEdit!==!0)return;let l=R.getMessages().find(f=>f.id===s);!l||!em(l)||ds!==s&&(cs(),ds=s,Tr=TC({messageId:s,initialText:l.content,onSave:f=>JM(s,f),onCancel:()=>cs()}),Ot.delete(s),Jo(Te,R.getMessages(),wt),Tr.focus())}function JM(s,l){let f=Tr;if(ds=null,Tr=null,f?.destroy(),Ot.delete(s),!R.resubmitFrom(s,{reason:"edit",replacement:{text:l,mentionRefs:[],options:{}}})){Jo(Te,R.getMessages(),wt);return}ko()}function ZM(s){if(R.isStreaming())return;let l=Zf(R.getMessages(),s);l&&(cs(),R.resubmitFrom(l,{reason:"retry"})&&ko())}Zl={regenerate:ZM,edit:YM,quote:s=>{let f=R.getMessages().find(g=>g.id===s)?.content?.trim();f&&(Mn({text:f,messageId:s}),ie?.focus())}};let Ui=async s=>{if(!sr){sr=!0;try{await Wb({resolveInlineCommand:!0,...s})}finally{sr=!1}}};function Xd(s){ys()||(Gd(),Qd(s,{consumeDraft:!1}))}let Qd=(s,l)=>{if(sr)return;sr=!0;let f=()=>{sr=!1};try{let g=Wb({...l,overrideText:s});g instanceof Promise?g.finally(f):f()}catch(g){throw f(),g}},eT=s=>{if(s.preventDefault(),R.isStreaming()){R.cancel(),st?.reset(),gt?.update();return}sr||Ui()},tT=()=>n.features?.composerHistory!==!1,bf={...yg},vf=!1,qi=()=>{bf={...yg}},oT=()=>R.getMessages().filter(s=>s.role==="user").map(s=>s.content??"").filter(s=>s.length>0),nT=s=>{if(!ie)return;vf=!0,ie.value=s,ie.dispatchEvent(new Event("input",{bubbles:!0})),vf=!1;let l=ie.value.length;ie.setSelectionRange(l,l)},rT=s=>{vf||(s.isComposing||Rt?.handleInput(s.inputType??void 0),qi())},sT=()=>({submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:xl(ie)}),aT=s=>{if(ie&&!Ln()&&!(!s.isComposing&&Rt?.handleKeydown(s))){if(tT()&&(s.key==="ArrowUp"||s.key==="ArrowDown")&&!s.shiftKey&&!s.metaKey&&!s.ctrlKey&&!s.altKey&&!s.isComposing){let l=ie.selectionStart===0&&ie.selectionEnd===0,f=oS({direction:s.key==="ArrowUp"?"up":"down",history:oT(),currentValue:ie.value,atStart:l,state:bf});if(bf=f.state,f.handled){s.preventDefault(),f.value!==void 0&&nT(f.value);return}}if(sC(s,sT())){if(R.isStreaming()){if(s.preventDefault(),rp()==="block"||sr||ys())return;qi(),Ui();return}if(sr){s.preventDefault();return}if(ys()){s.preventDefault();return}qi(),s.preventDefault(),we.click()}}},Ob=s=>{if(!(s.key!=="Escape"||s.isComposing)&&s.composedPath().includes(de)){if(Ts){Ts.abort(),Ts=null,s.preventDefault(),s.stopImmediatePropagation();return}R.isStreaming()&&(R.cancel(),st?.reset(),gt?.update(),qi(),s.preventDefault(),s.stopImmediatePropagation())}},iT=async s=>{if(n.attachments?.enabled!==!0||!Ze||Ln())return;let l=cL(s.clipboardData);l.length!==0&&(s.preventDefault(),await Ze.handleFiles(l))},nn=null,Hn=!1,wa=null,vt=null,xf=()=>n.voiceRecognition?.completionBehavior==="review";function Es(s){ne?.setAttribute("data-state",s),s==="recording"?dT():Af()}let Db="--persona-voice-level",Cf=.5,Aa=null,Sf=-1,Yd=0,_b=()=>{let s=[],l=Fo??ne?.parentElement??null;return l&&s.push(l),ke&&s.push(ke),s},wf=s=>{let l=Math.round(Math.max(0,Math.min(1,s))*100)/100;if(l!==Sf){Sf=l;for(let f of _b())f.style.setProperty(Db,String(l))}},lT=()=>{Sf=-1,Yd=0;for(let s of _b())s.style.removeProperty(Db)};function dT(){if(Aa!==null)return;if(typeof requestAnimationFrame!="function"){wf(u?R.getVoiceLevel()??Cf:Cf);return}let s=()=>{Aa=requestAnimationFrame(s);let l=u?R.getVoiceLevel():null;if(l===null){wf(Cf);return}Yd+=(l-Yd)*.3,wf(Yd)};Aa=requestAnimationFrame(s)}function Af(){Aa!==null&&(cancelAnimationFrame(Aa),Aa=null),lT()}let Nb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Jd=(s="user")=>{if(Hn||R.isStreaming())return;let l=Nb();if(!l)return;nn=new l;let f=n.voiceRecognition??{},g=f.pauseDuration??2e3;nn.continuous=f.provider?.browser?.continuous??!0,nn.interimResults=!0,nn.lang=f.provider?.browser?.language??"en-US";let v=ie.value;nn.onresult=w=>{let _="",$="";for(let j=0;j<w.results.length;j++){let J=w.results[j],re=J[0].transcript;J.isFinal?_+=re+" ":$=re}let U=v+_+$;ie.value=U,An(),wa&&clearTimeout(wa),(_||$)&&(wa=window.setTimeout(()=>{if(ie.value.trim()&&nn&&Hn){if(Wr(),xf())return;Ui({viaVoice:!0})}},g))},nn.onerror=w=>{w.error!=="no-speech"&&Wr()},nn.onend=()=>{if(Hn){let w=ie.value.trim();!xf()&&w&&w!==v.trim()&&Ui({viaVoice:!0}),Wr()}};try{if(nn.start(),Hn=!0,je.active=!0,s!=="system"&&(je.manuallyDeactivated=!1),Jn(s),mn(),un(),ne){let w=n.voiceRecognition??{};vt={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:w.iconName??"mic",iconSize:parseFloat(w.iconSize??"")||bo};let _=w.recordingBackgroundColor,$=w.recordingIconColor,U=w.recordingBorderColor;if(ne.classList.add("persona-voice-recording"),Es("recording"),ne.style.backgroundColor=_??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=$??"var(--persona-voice-recording-indicator, #ffffff)",$){let j=ne.querySelector("svg");j&&j.setAttribute("stroke",$)}U&&(ne.style.borderColor=U),ne.setAttribute("aria-label","Stop voice recognition")}}catch{Wr("system")}},Wr=(s="user")=>{if(Hn){if(Hn=!1,wa&&(clearTimeout(wa),wa=null),nn){try{nn.stop()}catch{}nn=null}if(je.active=!1,Jn(s),mn(),un(),ne){if(ne.classList.remove("persona-voice-recording"),Es("idle"),vt){ne.style.backgroundColor=vt.backgroundColor,ne.style.color=vt.color,ne.style.borderColor=vt.borderColor;let l=ne.querySelector("svg");l&&l.setAttribute("stroke",vt.color||"currentColor"),vt=null}ne.setAttribute("aria-label","Start voice recognition")}}},Mf=()=>{if(!ne||vt)return;let s=n.voiceRecognition??{};vt={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:s.iconName??"mic",iconSize:parseFloat(s.iconSize??"")||bo}},Tf=(s,l)=>{if(!ne)return;let f=ne.querySelector("svg");f&&f.remove();let g=vt?.iconSize??(parseFloat(n.voiceRecognition?.iconSize??"")||bo),v=le(s,g,l,1.5);v&&ne.appendChild(v)},Zd=()=>{ne&&ne.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ma=()=>{if(!ne)return;Mf();let s=n.voiceRecognition??{},l=s.recordingBackgroundColor,f=s.recordingIconColor,g=s.recordingBorderColor;if(Zd(),ne.classList.add("persona-voice-recording"),Es("recording"),ne.style.backgroundColor=l??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let v=ne.querySelector("svg");v&&v.setAttribute("stroke",f)}g&&(ne.style.borderColor=g),ne.setAttribute("aria-label","Stop voice recognition")},cT=()=>{if(!ne)return;Mf();let s=n.voiceRecognition??{},l=R.getVoiceInterruptionMode(),f=s.processingIconName??"loader",g=s.processingIconColor??vt?.color??"",v=s.processingBackgroundColor??vt?.backgroundColor??"",w=s.processingBorderColor??vt?.borderColor??"";Zd(),ne.classList.add("persona-voice-processing"),Es("processing"),ne.style.backgroundColor=v,ne.style.borderColor=w;let _=g||"currentColor";ne.style.color=_,Tf(f,_),ne.setAttribute("aria-label","Processing voice input"),l==="none"&&(ne.style.cursor="default")},uT=()=>{if(!ne)return;Mf();let s=n.voiceRecognition??{},l=R.getVoiceInterruptionMode(),f=l==="cancel"?"square":l==="barge-in"?"mic":"volume-2",g=s.speakingIconName??f,v=s.speakingIconColor??(l==="barge-in"?s.recordingIconColor??vt?.color??"":vt?.color??""),w=s.speakingBackgroundColor??(l==="barge-in"?s.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),_=s.speakingBorderColor??(l==="barge-in"?s.recordingBorderColor??"":vt?.borderColor??"");Zd(),ne.classList.add("persona-voice-speaking"),Es("speaking"),ne.style.backgroundColor=w,ne.style.borderColor=_;let $=v||"currentColor";ne.style.color=$,Tf(g,$);let U=l==="cancel"?"Stop playback and re-record":l==="barge-in"?"Speak to interrupt":"Agent is speaking";ne.setAttribute("aria-label",U),l==="none"&&(ne.style.cursor="default"),l==="barge-in"&&ne.classList.add("persona-voice-recording")},ar=()=>{ne&&(Zd(),Es("idle"),vt&&(ne.style.backgroundColor=vt.backgroundColor??"",ne.style.color=vt.color??"",ne.style.borderColor=vt.borderColor??"",Tf(vt.iconName,vt.color||"currentColor"),vt=null),ne.style.cursor="",ne.setAttribute("aria-label","Start voice recognition"))},Ef=()=>{if(!Ln()){if(Wo(n.voiceRecognition?.provider)){let s=R.getVoiceStatus(),l=R.getVoiceInterruptionMode();if(l==="none"&&(s==="processing"||s==="speaking"))return;if(l==="cancel"&&(s==="processing"||s==="speaking")){R.stopVoicePlayback();return}if(R.isBargeInActive()){R.stopVoicePlayback(),R.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,mn(),Jn("user"),ar()});return}R.toggleVoice().then(()=>{je.active=R.isVoiceActive(),je.manuallyDeactivated=!R.isVoiceActive(),mn(),Jn("user"),R.isVoiceActive()?Ma():ar()});return}if(Hn){let s=ie.value.trim();je.manuallyDeactivated=!0,mn(),Wr("user"),s&&!xf()&&Ui()}else je.manuallyDeactivated=!1,mn(),Jd("user")}};sp=Ef,ne&&fe.push(()=>{Wo(n.voiceRecognition?.provider)?(R.isVoiceActive()&&R.toggleVoice(),ar()):Wr("system")});let pT=x.on("assistant:complete",()=>{he.getState().pendingSubmission&&setTimeout(()=>{R.isStreaming()||QM()},0)});fe.push(pT);let fT=x.on("assistant:complete",()=>{Ty&&(je.active||je.manuallyDeactivated||Ty==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(Wo(n.voiceRecognition?.provider)?R.toggleVoice().then(()=>{je.active=R.isVoiceActive(),Jn("auto"),R.isVoiceActive()&&Ma()}):Jd("auto"))},600))});fe.push(fT);let mT=x.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});fe.push(mT);let Fb=()=>{pt(!ve,"user")},Tt=null,mo=null;if(pe&&!Le()){let{instance:s,element:l}=zg({config:n,plugins:i,onToggle:Fb});Tt=s,s||(mo=l)}Tt?e.appendChild(Tt.element):mo&&e.appendChild(mo),Ti(),ra(),wd(),Op(),Ei(R.isStreaming()),Ap()||(Uo()==="follow"?kr(!0):hd()),HA(),Pe&&(!pe||Le()?setTimeout(()=>bs(),0):ve&&setTimeout(()=>bs(),200));let Ps=null,Ub=()=>{Ps&&(Ps.disconnect(),Ps.observe(ke),Ps.observe(de))},Vi=()=>{if(Le()){es(),Ti();return}let s=Ct(n),l=n.launcher?.sidebarMode??!1,f=e.ownerDocument.defaultView??window,g=n.launcher?.mobileFullscreen??!0,v=n.launcher?.mobileBreakpoint??640,w=f.innerWidth<=v,_=g&&w&&pe;try{if(_){os(),hi=id();return}let $=!1;so&&(so=!1,os(),$=!0);let U=id();if(!$&&U!==hi&&(os(),$=!0),hi=U,$&&nd(),!pe&&!s){Ce.style.height="",Ce.style.width="";return}if(!l&&!s){let J=n?.launcher?.width??n?.launcherWidth??Ko;Ce.style.width=J,Ce.style.maxWidth=J}ad(),cy()}finally{if(es(),Yl(),Ti(),ve&&pe){let U=(e.ownerDocument.defaultView??window).innerWidth<=(n.launcher?.mobileBreakpoint??640),j=n.launcher?.sidebarMode??!1,J=n.launcher?.mobileFullscreen??!0,re=Ct(n)&&J&&U,ce=j||J&&U&&pe||re;if(ce&&!kn){let Ye=e.getRootNode(),ct=Ye instanceof ShadowRoot?Ye.host:e.closest(".persona-host");ct&&!Pn&&(Pn=wg(ct,n.launcher?.zIndex??ro)),kn=Ag(e.ownerDocument)}else ce||(Pn?.(),Pn=null,kn?.(),kn=null)}}};Vi();let ec=e.ownerDocument.defaultView??window;if(ec.addEventListener("resize",Vi),fe.push(()=>ec.removeEventListener("resize",Vi)),typeof ResizeObserver<"u"){Ps=new ResizeObserver(()=>{Yl()}),Ub(),fe.push(()=>{Ps?.disconnect(),Ps=null});let s=new ResizeObserver(()=>{Nd()});s.observe(de),fe.push(()=>s.disconnect())}ec.addEventListener("resize",Nd),fe.push(()=>ec.removeEventListener("resize",Nd)),$o=oe.scrollTop;let qb=Un(oe),Vb=()=>{let s=oe.scrollTop,l=Un(oe),f=l<qb;if(qb=l,!Cr()){$o=s,$t();return}let{action:g,nextLastScrollTop:v}=cS({following:Vo.isFollowing(),currentScrollTop:s,lastScrollTop:$o,nearBottom:_s(oe,Qn),userScrollThreshold:kA,isAutoScrolling:Eo||dd||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if($o=v,g==="resume"){yd()||Po();return}g==="pause"&&Ci()};if(oe.addEventListener("scroll",Vb,{passive:!0}),fe.push(()=>oe.removeEventListener("scroll",Vb)),typeof ResizeObserver<"u"){let s=new ResizeObserver(()=>{FA(),Hf(Te)});s.observe(Te),s.observe(oe),fe.push(()=>s.disconnect())}let $b=()=>{Cr()&&Vo.isFollowing()&&yd()&&Ci()},jb=oe.ownerDocument;jb.addEventListener("selectionchange",$b),fe.push(()=>{jb.removeEventListener("selectionchange",$b)});let gT=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),zb=s=>{gT.has(s.key)&&(ms(),Ih()&&Cr()&&Vo.isFollowing()&&Ci())},Kb=s=>{s.target?.closest("a, button, [tabindex], input, textarea, select")&&(ms(),Ih()&&Cr()&&Vo.isFollowing()&&Ci())};oe.addEventListener("keydown",zb),oe.addEventListener("focusin",Kb),fe.push(()=>{oe.removeEventListener("keydown",zb),oe.removeEventListener("focusin",Kb)});let Gb=s=>{if(s.deltaY!==0&&ms(),!Cr())return;let l=uS({following:Vo.isFollowing(),deltaY:s.deltaY,nearBottom:_s(oe,Qn),resumeWhenNearBottom:!0});l==="pause"?Ci():l==="resume"&&!yd()&&Po()};oe.addEventListener("wheel",Gb,{passive:!0}),oe.addEventListener("touchmove",ms,{passive:!0}),oe.addEventListener("pointerdown",ms,{passive:!0}),fe.push(()=>{oe.removeEventListener("touchmove",ms),oe.removeEventListener("pointerdown",ms)}),fe.push(()=>oe.removeEventListener("wheel",Gb)),Bt.addEventListener("click",()=>{gn(),oe.scrollTop=oe.scrollHeight,$o=oe.scrollTop,Po(),kr(!0),$t()}),fe.push(()=>Bt.remove()),fe.push(()=>{Iy(),gn()});let Xb=()=>{Ne&&(as&&(Ne.removeEventListener("click",as),as=null),qe()?(Ne.style.display="",as=()=>{pt(!1,"user")},Ne.addEventListener("click",as)):Ne.style.display="none")};Xb(),(()=>{let{clearChatButton:s}=Oe;s&&s.addEventListener("click",()=>{if(Rn()){ff({focusComposer:!0}).catch(f=>{n.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}R.clearMessages(),Ot.clear(),Po(),Vr(Oe.composerOverlay);try{localStorage.removeItem(ai),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ai}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ai)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),N?.clear&&fd(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),V={},be.syncFromMetadata(),Ze?.clearAttachments(),gd(),Js(void 0),Mn(void 0),cs(),We?.clear(),st?.reset(),gt?.update()})})();let Qb=[["keydown",aT],["input",rT],["input",An],["input",ts],["keyup",ts],["paste",iT],["focus",yA]],Yb=s=>{if(s)for(let[l,f]of Qb)ot?.addListener(s,l,f)},hT=s=>{if(s)for(let[l,f]of Qb)ot?.removeListener(s,l,f)},Jb=()=>{ot&&(ot.addListener(ot.form,"submit",eT),ot.addListener(ot.footer,"click",ts),Yb(ie),ne&&ot.addListener(ne,"click",Ef))};Jb();let Zb=()=>{Rt?.onComposerSwap((s,l)=>{hT(l),ie=s,ot&&(ot.input=s),Yb(s),ip(),kp(),An()})};Zb();let Pf=!1;function ev(){if(!Pf){Pf=!0;try{let s=ie?.value??"",l=ke.ownerDocument??document,f=ie?l.activeElement===ie:!1;Af(),ot?.destroy(),ot=null,Rt?.destroy(),Rt=null;let g=null,v=()=>(g=Le()?vu({config:n}):Vs({config:n}),g.footer),w=Uh(v)??v();_o.replaceComposer(w),ke=_o.composer.footer;let _=g!==null&&w===g.footer;ea=!_,Lh=_?g.setSendButtonMode:()=>{},Fh(ke),Vh(ke),$h(),jh(),zh(),Zb(),Kh(),lp(),Gh(),Jb();let $=ss.indexOf(Xn);Xn.destroy(),Xn=Wl(vr),$>=0&&(ss[$]=Xn),ie&&(ie.value=s),An(),ts(),wd(),ra(),Ei(R.isStreaming()),je.active&&Es("recording"),os(),Ub(),es(),un(),Cd(),f&&ie?.focus()}finally{Pf=!1}}}let $i=e.ownerDocument??document;$i.addEventListener("keydown",Ob,!0);let tv=()=>{xp()},ov=()=>{$i.visibilityState==="hidden"&&xp()};typeof window<"u"&&(window.addEventListener("pagehide",tv),$i.addEventListener("visibilitychange",ov),fe.push(()=>{window.removeEventListener("pagehide",tv),$i.removeEventListener("visibilitychange",ov)}));let nv="persona-attachment-drop-active",ji=0,kf=()=>{ji=0,de.classList.remove(nv)},Ta=()=>n.attachments?.enabled===!0&&Ze!==null&&!Ln(),rv=s=>{!qu(s.dataTransfer)||!Ta()||(ji++,ji===1&&de.classList.add(nv))},sv=s=>{!qu(s.dataTransfer)||!Ta()||(ji--,ji<=0&&kf())},av=s=>{!qu(s.dataTransfer)||!Ta()||(s.preventDefault(),s.dataTransfer.dropEffect="copy")},iv=s=>{if(!qu(s.dataTransfer)||!Ta())return;s.preventDefault(),s.stopPropagation(),kf();let l=Array.from(s.dataTransfer.files??[]);l.length!==0&&Ze.handleFiles(l)},Br=!0;de.addEventListener("dragenter",rv,Br),de.addEventListener("dragleave",sv,Br),e.addEventListener("dragover",av,Br),e.addEventListener("drop",iv,Br);let tc=e.ownerDocument,lv=s=>{Ta()&&s.preventDefault()},dv=s=>{Ta()&&s.preventDefault()};tc.addEventListener("dragover",lv),tc.addEventListener("drop",dv),fe.push(()=>{ot?.destroy(),ot=null,Af(),Tn?.destroy(),Tn=null,Kn?.destroy(),Kn=null,wr?.destroy(),wr=null,Ar?.destroy(),Ar=null,Sr=null,np=null,xp(),xi.destroy(),Sa&&clearTimeout(Sa),cs(),Ts?.abort(),Ts=null,Ze?.destroy(),Ze=null,he.destroy(),$i.removeEventListener("keydown",Ob,!0),Rt?.destroy()}),fe.push(()=>{de.removeEventListener("dragenter",rv,Br),de.removeEventListener("dragleave",sv,Br),e.removeEventListener("dragover",av,Br),e.removeEventListener("drop",iv,Br),tc.removeEventListener("dragover",lv),tc.removeEventListener("drop",dv),kf()}),fe.push(()=>{R.cancel()}),Tt?fe.push(()=>{Tt?.destroy()}):mo&&fe.push(()=>{mo?.remove()});let Et={update(s){let l=n.toolCall,f=n.messageActions,g=n.layout?.messages,v=n.colorScheme,w=n.loadingIndicator,_=n.iterationDisplay,$=n.features?.showReasoning,U=n.features?.showToolCalls,j=n.features?.toolCallDisplay,J=n.features?.reasoningDisplay,re=n.features?.streamAnimation?.type,ce=n.features?.history?.enabled===!0,Ye=n.features?.history?.provider,ct=n.getIdentityProof,ft=n.clientToken,Gt=n.contextMentions;n=Wu({...n,features:a},s),a=n.features,n=_l(n),r(),mp(),Ds(e,n),Ol(e,n),Dl(e,n),jn(),fn(),n.colorScheme!==v&&uy();let _t=Nl.getForInstance(n.plugins);i.length=0,i.push(..._t),cb(),pe=n.launcher?.enabled??!0,yt=n.launcher?.autoExpand??!1,$n=n.features?.showReasoning??!0,z=n.features?.showToolCalls??!0,F=n.features?.scrollToBottom??{};let Pt=Uo();K=n.features?.scrollBehavior??{},Pt!==Uo()&&(gn(),Po()),My(),Wh(),$t();let io=k;if(k=n.features?.showEventStreamToggle??!1,k&&!io){if(We||($l(),R.setSSEEventCallback((Z,ze)=>{n.onSSEEvent?.(Z,ze),Ku(Z,ze)})),!tt&&Ae){let Z=n.features?.eventStream?.classNames,ze="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"+(Z?.toggleButton?" "+Z.toggleButton:"");tt=H("button",ze),tt.style.width="28px",tt.style.height="28px",tt.style.color=xo.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Xe=Ut(_a,"18px","currentColor",1.5);Xe&&tt.appendChild(Xe);let nt=Oe.clearChatButtonWrapper,xt=Oe.closeButtonWrapper,oo=nt||xt;oo&&oo.parentNode===Ae?Ae.insertBefore(tt,oo):Ae.appendChild(tt),tt.addEventListener("click",()=>{zt?Zs():ap()})}}else!k&&io&&(Zs(),tt&&(tt.remove(),tt=null),We?.clear(),Me?.destroy(),We=null,Me=null,st?.reset(),st=null,Ke=null);if(n.launcher?.enabled===!1&&Tt&&(Tt.destroy(),Tt=null),n.launcher?.enabled===!1&&mo&&(mo.remove(),mo=null),n.launcher?.enabled!==!1&&!Tt&&!mo){let{instance:Z,element:ze}=zg({config:n,plugins:i,onToggle:Fb});Tt=Z,Z||(mo=ze),e.appendChild(ze)}Tt&&Tt.update(n),Fi(),Jr&&n.launcher?.subtitle!==void 0&&(Jr.textContent=n.launcher.subtitle);let et=n.layout?.header;if(et?.layout!==Je&&Ae){let Z=et?Qa(n,et,{showClose:qe(),onClose:()=>pt(!1,"user")}):gr({config:n,showClose:qe(),onClose:()=>pt(!1,"user")});_o.replaceHeader(Z),Ae=_o.header.element,Mt=_o.header.iconHolder,xr=_o.header.headerTitle,Jr=_o.header.headerSubtitle,Ne=_o.header.closeButton,Je=et?.layout,Fi()}else if(et){if(Mt&&(Mt.style.display=et.showIcon===!1?"none":""),xr&&(xr.style.display=et.showTitle===!1?"none":""),Jr&&(Jr.style.display=et.showSubtitle===!1?"none":""),Ne){let Z=qe()&&et.showCloseButton!==!1;Ne.style.display=Z?"":"none"}if(Oe.clearChatButtonWrapper){let Z=et.showClearChat;if(Z!==void 0){Oe.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:ze}=Oe;ze&&!ze.classList.contains("persona-absolute")&&(Z?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}}let Wn=n.layout?.showHeader!==!1;Ae&&(Ae.style.display=Wn?"":"none");let ir=n.layout?.showFooter!==!1;ke&&(ke.style.display=ir?"":"none"),es(),$t(),pe!==Ue?pe?pt(yt,"auto"):(ve=!0,Ti()):yt!==q&&pt(yt,"auto"),q=yt,Ue=pe,Vi(),Xb();let ks=JSON.stringify(n.toolCall)!==JSON.stringify(l),yn=JSON.stringify(n.messageActions)!==JSON.stringify(f),eo=JSON.stringify(n.layout?.messages)!==JSON.stringify(g),bn=n.loadingIndicator?.render!==w?.render||n.loadingIndicator?.renderIdle!==w?.renderIdle||n.loadingIndicator?.showBubble!==w?.showBubble,Ea=n.iterationDisplay!==_,B=(n.features?.showReasoning??!0)!==($??!0)||(n.features?.showToolCalls??!0)!==(U??!0)||JSON.stringify(n.features?.toolCallDisplay)!==JSON.stringify(j)||JSON.stringify(n.features?.reasoningDisplay)!==JSON.stringify(J);(ks||yn||eo||bn||Ea||B)&&R&&(us++,Jo(Te,R.getMessages(),wt));let Se=n.features?.streamAnimation?.type;if(Se!==re&&Se&&Se!=="none"){let Z=hp(Se,n.features?.streamAnimation?.plugins);Z&&Il(Z,e)}let se=n.launcher??{},kt=se.headerIconHidden??!1,Nt=n.layout?.header?.showIcon,to=kt||Nt===!1,Ft=se.headerIconName,jt=se.headerIconSize??"48px";if(Mt){let Z=Ae,ze=Z?.querySelector(".persona-flex-col");if(to)Mt.style.display="none",Z&&ze&&!Z.contains(ze)&&Z.insertBefore(ze,Z.firstChild);else{if(Mt.style.display="",Mt.style.height=jt,Mt.style.width=jt,Z&&ze&&(Z.contains(Mt)?Mt.nextSibling!==ze&&(Mt.remove(),Z.insertBefore(Mt,ze)):Z.insertBefore(Mt,ze)),Ft){let nt=parseFloat(jt)||24,xt=le(Ft,nt*.6,"currentColor",1);xt?Mt.replaceChildren(xt):Mt.textContent=se.agentIconText??"\u{1F4AC}"}else if(se.iconUrl){let nt=Mt.querySelector("img");if(nt)nt.src=se.iconUrl,nt.style.height=jt,nt.style.width=jt;else{let xt=document.createElement("img");xt.src=se.iconUrl,xt.alt="",xt.className="persona-rounded-xl persona-object-cover",xt.style.height=jt,xt.style.width=jt,Mt.replaceChildren(xt)}}else{let nt=Mt.querySelector("svg"),xt=Mt.querySelector("img");(nt||xt)&&Mt.replaceChildren(),Mt.textContent=se.agentIconText??"\u{1F4AC}"}let Xe=Mt.querySelector("img");Xe&&(Xe.style.height=jt,Xe.style.width=jt)}}let Lt=n.layout?.header?.showTitle,co=n.layout?.header?.showSubtitle;if(xr&&(xr.style.display=Lt===!1?"none":""),Jr&&(Jr.style.display=co===!1?"none":""),Ne){let Z=qe()&&n.layout?.header?.showCloseButton!==!1;if(Ne.style.display=Z?"":"none",!Le()){let Xt=se.closeButtonSize??"";Ne.style.height=Xt,Ne.style.width=Xt,Ne.style.minWidth=Xt,Ne.style.minHeight=Xt}let ze=se.closeButtonPlacement??"inline",{closeButtonWrapper:Xe}=Oe,nt=ze==="top-right",xt=Xe?.classList.contains("persona-absolute");if(Xe&&nt!==xt)if(Xe.remove(),nt){Xe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Xt=Ri??de;Xt.style.position="relative",Xt.appendChild(Xe)}else{let Xt=se.clearChat?.placement??"inline",Qt=se.clearChat?.enabled??!0;Xe.className=Qt&&Xt==="inline"?"":"persona-ml-auto",Ae&&Ae.appendChild(Xe)}if(Ne.style.color=se.closeButtonColor||xo.actionIconColor,se.closeButtonBackgroundColor?(Ne.style.backgroundColor=se.closeButtonBackgroundColor,Ne.classList.remove("hover:persona-bg-gray-100")):(Ne.style.backgroundColor="",Ne.classList.add("hover:persona-bg-gray-100")),se.closeButtonBorderWidth||se.closeButtonBorderColor){let Xt=se.closeButtonBorderWidth||"0px",Qt=se.closeButtonBorderColor||"transparent";Ne.style.border=`${Xt} solid ${Qt}`,Ne.classList.remove("persona-border-none")}else Ne.style.border="",Ne.classList.add("persona-border-none");se.closeButtonBorderRadius?(Ne.style.borderRadius=se.closeButtonBorderRadius,Ne.classList.remove("persona-rounded-full")):(Ne.style.borderRadius="",Ne.classList.add("persona-rounded-full")),se.closeButtonPaddingX?(Ne.style.paddingLeft=se.closeButtonPaddingX,Ne.style.paddingRight=se.closeButtonPaddingX):(Ne.style.paddingLeft="",Ne.style.paddingRight=""),se.closeButtonPaddingY?(Ne.style.paddingTop=se.closeButtonPaddingY,Ne.style.paddingBottom=se.closeButtonPaddingY):(Ne.style.paddingTop="",Ne.style.paddingBottom=""),hu(Ne,se.closeButtonIconName??"x",{iconSize:Le()?qg:void 0,iconText:se.closeButtonIconText??"\xD7"});let oo=se.closeButtonTooltipText??"Close chat",vn=se.closeButtonShowTooltip??!0;Ne.setAttribute("aria-label",oo),Xe&&Jt({anchor:Ne,trigger:Xe,text:()=>Ne?.getAttribute("aria-label")??oo,enabled:vn})}let{clearChatButton:Ie,clearChatButtonWrapper:De}=Oe;if(Ie){let Z=se.clearChat??{},ze=Z.enabled??!0,Xe=n.layout?.header?.showClearChat,nt=Xe!==void 0?Xe:ze,xt=Z.placement??"inline";if(De){De.style.display=nt?"":"none";let{closeButtonWrapper:oo}=Oe;!Le()&&oo&&!oo.classList.contains("persona-absolute")&&(nt?oo.classList.remove("persona-ml-auto"):oo.classList.add("persona-ml-auto"));let vn=xt==="top-right",Xt=De.classList.contains("persona-absolute");if(!Le()&&vn!==Xt&&nt){if(De.remove(),vn){De.className="persona-absolute persona-top-4 persona-z-50",De.style.right="48px";let Bn=Ri??de;Bn.style.position="relative",Bn.appendChild(De)}else{De.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",De.style.right="";let Bn=Oe.closeButtonWrapper;Ae&&Bn&&Bn.parentElement===Ae?Ae.insertBefore(De,Bn):Ae&&Ae.appendChild(De)}let Qt=Oe.closeButtonWrapper;Qt&&!Qt.classList.contains("persona-absolute")&&(vn?Qt.classList.add("persona-ml-auto"):Qt.classList.remove("persona-ml-auto"))}}if(nt){if(!Le()){let Qt=Z.size??"";Ie.style.height=Qt,Ie.style.width=Qt,Ie.style.minWidth=Qt,Ie.style.minHeight=Qt}let oo=Z.iconColor??"";if(Ie.style.color=oo||xo.actionIconColor,hu(Ie,Z.iconName??"refresh-cw",{iconSize:Le()?Vg:void 0}),Z.backgroundColor?(Ie.style.backgroundColor=Z.backgroundColor,Ie.classList.remove("hover:persona-bg-gray-100")):(Ie.style.backgroundColor="",Ie.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let Qt=Z.borderWidth||"0px",Bn=Z.borderColor||"transparent";Ie.style.border=`${Qt} solid ${Bn}`,Ie.classList.remove("persona-border-none")}else Ie.style.border="",Ie.classList.add("persona-border-none");Z.borderRadius?(Ie.style.borderRadius=Z.borderRadius,Ie.classList.remove("persona-rounded-full")):(Ie.style.borderRadius="",Ie.classList.add("persona-rounded-full")),Z.paddingX?(Ie.style.paddingLeft=Z.paddingX,Ie.style.paddingRight=Z.paddingX):(Ie.style.paddingLeft="",Ie.style.paddingRight=""),Z.paddingY?(Ie.style.paddingTop=Z.paddingY,Ie.style.paddingBottom=Z.paddingY):(Ie.style.paddingTop="",Ie.style.paddingBottom="");let vn=Z.tooltipText??"Clear chat",Xt=Z.showTooltip??!0;Ie.setAttribute("aria-label",vn),De&&Jt({anchor:Ie,trigger:De,text:()=>Ie?.getAttribute("aria-label")??vn,enabled:Xt})}}let xe=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Fl],uo=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ks.message,Ks.messageAndClick];be=Ul({parsers:xe,handlers:uo,getSessionMetadata:ue,updateSessionMetadata:ae,emit:x.emit,documentRef:typeof document<"u"?document:null}),wt=Hw(n,be,Vn),rM(),R.updateConfig(n),(n.features?.history?.enabled===!0!==ce||n.features?.history?.provider!==Ye||n.getIdentityProof!==ct||n.clientToken!==ft)&&(Lo({restoreFocus:!1}),ob()),Hr(),Nd(),Jo(Te,R.getMessages(),wt),ra(),wd(),oM(),Ei(R.isStreaming()),Gt!==n.contextMentions&&ev();let Or=n.voiceRecognition?.enabled===!0,Io=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Ro=Wo(n.voiceRecognition?.provider);if(Or&&(Io||Ro))if(!ne||!Fo){let Z=ja(n);if(Z){ne=Z.button,Fo=Z.wrapper;let ze=wn&&wn.parentElement===zl?wn:null;zl?zl.insertBefore(Fo,ze):cn?.appendChild(Fo),ot&&(ot.micButton=ne),ot?.addListener(ne,"click",Ef),ne.disabled=Ln()||R.isStreaming()&&!Ep()}}else{let Z=n.voiceRecognition??{},ze=n.sendButton??{},Xe=Z.iconName??"mic",nt=Z.iconSize,xt=parseFloat(nt??"")||bo;ne.classList.add(Go),ne.classList.toggle(xn,!nt),ne.style.width=nt??"",ne.style.height=nt??"",ne.style.minWidth=nt??"",ne.style.minHeight=nt??"";let oo=Z.iconColor??ze.textColor;ne.innerHTML="";let vn=le(Xe,xt,oo||"currentColor",1.5);vn?ne.appendChild(vn):ne.textContent="\u{1F3A4}";let Xt=Z.backgroundColor??ze.backgroundColor;Xt?ne.style.backgroundColor=Xt:ne.style.backgroundColor="",oo?ne.style.color=oo:ne.style.color="var(--persona-text, #111827)",Z.borderWidth?(ne.style.borderWidth=Z.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),Z.borderColor?ne.style.borderColor=Z.borderColor:ne.style.borderColor="",Z.paddingX?(ne.style.paddingLeft=Z.paddingX,ne.style.paddingRight=Z.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),Z.paddingY?(ne.style.paddingTop=Z.paddingY,ne.style.paddingBottom=Z.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let Qt=Z.tooltipText??"Start voice recognition",Bn=Z.showTooltip??!1;ne.setAttribute("aria-label",Qt),Fo&&Jt({anchor:ne,trigger:Fo,text:()=>ne?.getAttribute("aria-label")??Qt,enabled:Bn}),Fo.style.display="",ne.disabled=Ln()||R.isStreaming()&&!Ep()}else ne&&Fo&&(Fo.style.display="none",Wo(n.voiceRecognition?.provider)?R.isVoiceActive()&&R.toggleVoice():Hn&&Wr());if(n.attachments?.enabled===!0){if(!Mo||!St){let Z=n.attachments??{};To||(To=H("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),To.style.display="none",(ie.parentElement??cn).insertBefore(To,ie)),ht||(ht=document.createElement("input"),ht.type="file",ht.accept=(Z.allowedTypes??mr).join(","),ht.multiple=(Z.maxFiles??4)>1,ht.style.display="none",ht.setAttribute("aria-label","Attach files"),(ie.parentElement??cn).insertBefore(ht,ie)),Mo=H("div","persona-send-button-wrapper"),St=H("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Go} ${xn}`),St.type="button",St.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let ze=Z.buttonIconName??"paperclip";St.style.fontSize="18px",St.style.lineHeight="1";let Xe=le(ze,bo,"currentColor",1.5);Xe?St.appendChild(Xe):St.textContent="\u{1F4CE}",St.addEventListener("click",xt=>{xt.preventDefault(),ht?.click()}),Mo.appendChild(St);let nt=Z.buttonTooltipText??"Attach file";Jt({anchor:St,trigger:Mo,text:()=>St?.getAttribute("aria-label")??nt}),Yu?Yu.append(Mo):cn.appendChild(Mo),ot&&(ot.attachmentButton=St,ot.attachmentInput=ht??void 0,ot.attachmentPreviews=To??void 0),!Ze&&ht&&To&&(Ze=Os.fromConfig(Z,Bh),Ze.setPreviewsContainer(To),ot?.addListener(ht,"change",async()=>{Ze&&ht?.files&&(await Ze.handleFileSelect(ht.files),ht.value="")}))}else{Mo.style.display="";let Z=n.attachments??{};ht&&(ht.accept=(Z.allowedTypes??mr).join(","),ht.multiple=(Z.maxFiles??4)>1),Ze&&Ze.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(de.querySelector(".persona-attachment-drop-overlay")?.remove(),de.appendChild(Ww(n.attachments?.dropOverlay)),St){let Z=n.attachments??{},ze=Z.buttonTooltipText??"Attach file";St.setAttribute("aria-label",ze),St.textContent="";let Xe=le(Z.buttonIconName??"paperclip",bo,"currentColor",1.5);Xe?St.appendChild(Xe):St.textContent="\u{1F4CE}",Mo&&Jt({anchor:St,trigger:Mo,text:()=>St?.getAttribute("aria-label")??ze})}}else Mo&&(Mo.style.display="none"),Ze&&Ze.clearAttachments(),de.querySelector(".persona-attachment-drop-overlay")?.remove();let Be=n.sendButton??{},lr=Be.useIcon??!1,Ht=Be.iconText??"\u2191",Ho=Be.iconName,Ki=Be.tooltipText??"Send message",vT=Be.showTooltip??!1,Gi=Be.size,xT=parseFloat(Gi??"")||Zm,oc=Be.backgroundColor,Xi=Be.textColor;if(lr){if(we.style.width=Gi??"",we.style.height=Gi??"",we.style.minWidth=Gi??"",we.style.minHeight=Gi??"",we.style.fontSize="18px",we.style.lineHeight="1",Xi?we.style.color=Xi:we.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!R.isStreaming())if(we.innerHTML="",Ho){let Z=parseFloat(Be.iconSize??"")||Math.round(xT*.5),ze=Xi?.trim()||"currentColor",Xe=Be.iconStrokeWidth??2,nt=le(Ho,Z,ze,Xe),xt=le(Be.stopIconName??"square",Z,ze,Xe);nt&&xt?we.appendChild(eg(nt,xt)):nt?we.appendChild(nt):we.textContent=Ht}else we.textContent=Ht;we.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Go}`,oc?(we.style.backgroundColor=oc,we.classList.remove("persona-bg-persona-primary")):(we.style.backgroundColor="",we.classList.add("persona-bg-persona-primary"))}else we.textContent=n.copy?.sendButtonLabel??"Send",we.style.width="",we.style.height="",we.style.minWidth="",we.style.minHeight="",we.style.fontSize="",we.style.lineHeight="",we.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",oc?(we.style.backgroundColor=oc,we.classList.remove("persona-bg-persona-accent")):we.classList.add("persona-bg-persona-accent"),Xi?we.style.color=Xi:we.classList.add("persona-text-white");Be.borderWidth?(we.style.borderWidth=Be.borderWidth,we.style.borderStyle="solid"):(we.style.borderWidth="",we.style.borderStyle=""),Be.borderColor?we.style.borderColor=Be.borderColor:we.style.borderColor="",Be.paddingX?(we.style.paddingLeft=Be.paddingX,we.style.paddingRight=Be.paddingX):(we.style.paddingLeft="",we.style.paddingRight=""),Be.paddingY?(we.style.paddingTop=Be.paddingY,we.style.paddingBottom=Be.paddingY):(we.style.paddingTop="",we.style.paddingBottom=""),R.isStreaming()||we.setAttribute("aria-label",Ki),Cd(),wn&&Jt({anchor:we,trigger:wn,text:()=>we.getAttribute("aria-label")??Ki,enabled:vT}),Qh();let cv=ou(he.getState().activeModeIds,n.composer?.modes);he.setActiveModeIds(cv),Qs().length>0!==!!Kn&&lp(),Kn?.render(cv,Qs());for(let Z of[...Ys.keys()])tu(Z,n.composer?.modeGroups)||Ys.delete(Z);Ys.forEach(Z=>Z.repaint()),Sr?.repaint(),Tn?.resolve();let nc=Gr(n,Le());if(gp(),nc){Te.style.maxWidth=nc,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",No.style.maxWidth=nc,No.style.marginLeft="auto",No.style.marginRight="auto",No.style.width="100%";for(let Z of[cn,vr,To,at])Z&&(Z.style.maxWidth=nc,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{Te.style.maxWidth="",Te.style.marginLeft="",Te.style.marginRight="",Te.style.width="",No.style.maxWidth="",No.style.marginLeft="",No.style.marginRight="",No.style.width="";for(let Z of[cn,vr,To,at])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Dr=n.statusIndicator??{},CT=Dr.visible??!0;if(at.style.display=CT?"":"none",R){let Z=R.getStatus();jl(at,(Xe=>Xe==="idle"?Dr.idleText??qt.idle:Xe==="connecting"?Dr.connectingText??qt.connecting:Xe==="connected"?Dr.connectedText??qt.connected:Xe==="error"?Dr.errorText??qt.error:qt[Xe])(Z),Dr,Z)}at.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ST=Dr.align==="left"?"persona-text-left":Dr.align==="center"?"persona-text-center":"persona-text-right";at.classList.add(ST),ip(),kp(),un(),Gu()},open(){qe()&&pt(!0,"api")},close(){qe()&&pt(!1,"api")},toggle(){qe()&&pt(!ve,"api")},reconnect(){R.reconnectNow()},clearChat(){Gn=!1,R.clearMessages(),Ot.clear(),Po();try{localStorage.removeItem(ai),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ai}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ai)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let s=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(s),N?.clear&&fd(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),V={},be.syncFromMetadata(),Ze?.clearAttachments(),gd(),Js(void 0),Mn(void 0),cs(),We?.clear(),st?.reset(),gt?.update()},setMessage(s){return!ie||R.isStreaming()||Ln()?!1:(!ve&&qe()&&pt(!0,"system"),ie.value=s,ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(s){if(R.isStreaming()||ys())return!1;let l=s?.trim()||ie.value.trim();return l?(!ve&&qe()&&pt(!0,"system"),ie.value="",ie.style.height="auto",An(),Qd(l,{consumeDraft:!1}),!0):!1},getComposerState(){return he.getState()},setQuote(s){let l=s?.text?.trim();l&&Mn({...s,text:l})},clearQuote(){Mn(void 0)},startVoiceRecognition(){return R.isStreaming()?!1:Wo(n.voiceRecognition?.provider)?(R.isVoiceActive()||R.isBargeInActive()||(!ve&&qe()&&pt(!0,"system"),je.manuallyDeactivated=!1,mn(),R.toggleVoice().then(()=>{je.active=R.isVoiceActive(),Jn("user"),R.isVoiceActive()&&Ma()})),!0):Hn?!0:Nb()?(!ve&&qe()&&pt(!0,"system"),je.manuallyDeactivated=!1,mn(),Jd("user"),!0):!1},stopVoiceRecognition(){return Wo(n.voiceRecognition?.provider)?!R.isVoiceActive()&&!R.isBargeInActive()?!1:((R.isBargeInActive()?R.deactivateBargeIn():R.toggleVoice()).then(()=>{je.active=!1,je.manuallyDeactivated=!0,mn(),Jn("user"),ar()}),!0):Hn?(je.manuallyDeactivated=!0,mn(),Wr("user"),!0):!1},injectMessage(s){return!ve&&qe()&&pt(!0,"system"),R.injectMessage(s)},injectAssistantMessage(s){!ve&&qe()&&pt(!0,"system");let l=R.injectAssistantMessage(s);return po&&(po=!1,dn&&(clearTimeout(dn),dn=null),setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)),l},injectUserMessage(s){return!ve&&qe()&&pt(!0,"system"),R.injectUserMessage(s)},injectSystemMessage(s){return!ve&&qe()&&pt(!0,"system"),R.injectSystemMessage(s)},injectMessageBatch(s){return!ve&&qe()&&pt(!0,"system"),R.injectMessageBatch(s)},injectComponentDirective(s){return!ve&&qe()&&pt(!0,"system"),R.injectComponentDirective(s)},injectTestMessage(s){!ve&&qe()&&pt(!0,"system"),R.injectTestEvent(s)},async connectStream(s,l){return R.connectStream(s,l)},__pushEventStreamEvent(s){k&&($l(),Ku(s.type,s.payload))},showEventStream(){k&&ap()},hideEventStream(){zt&&Zs()},isEventStreamVisible(){return zt},listConversations(s){return R.listConversations(s)},getActiveConversationId(){return R.getActiveConversationId()},openConversation(s,l){return pf(s,{focusComposer:l?.focus===!0})},startNewConversation(s){return ff({focusComposer:s?.focus===!0})},deleteConversation(s){return Pb(s)},renameConversation(s,l){return mf(s,{title:l})},setConversationStarred(s,l){return mf(s,{starred:l})},clearConversationHistory(s){return kb(s)},resetHistoryIdentity(){return Lb()},async getVisitorToken(){let s=Zo;if(!s)return null;let l=await s.get();return s===Zo?l:null},getHistoryIdentityStatus(){return jo?jo.getIdentityStatus():Gp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(s){return Ni({...s?.returnSurface?{returnSurface:s.returnSurface}:{},...s?.focus!==void 0?{focus:s.focus}:{}})},hideHistory(s){Lo(s?.restoreFocus!==void 0?{restoreFocus:s.restoreFocus}:void 0)},isHistoryVisible(){return At},showArtifacts(){So(n)&&(Gn=!1,ta=!0,fn(),$e?.setMobileOpen(!0))},hideArtifacts(){So(n)&&(Gn=!0,fn())},upsertArtifact(s){return So(n)?(Dn(n.features?.artifacts,{artifactType:s.artifactType,...s.artifactType==="markdown"&&s.file?{file:s.file}:{},...s.presentation?{presentation:s.presentation}:{}})==="panel"&&(Gn=!1,ta=!0),R.upsertArtifact(s)):null},selectArtifact(s){So(n)&&R.selectArtifact(s)},clearArtifacts(){So(n)&&R.clearArtifacts()},getArtifacts(){return R?.getArtifacts()??[]},getSelectedArtifactId(){return R?.getSelectedArtifactId()??null},focusInput(){return pe&&!ve&&!Le()||!ie?!1:(ie.focus(),!0)},async resolveApproval(s,l,f){let v=R.getMessages().find(w=>w.variant==="approval"&&w.approval?.id===s);if(!v?.approval)throw new Error(`Approval not found: ${s}`);if(v.approval.toolType==="webmcp"){R.resolveWebMcpApproval(v.id,l);return}return R.resolveApproval(v.approval,l,f)},setFollowUpSuggestions(s){EA(s)},clearFollowUpSuggestions(){Ay()},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...V}},updatePersistentMetadata(s){ae(s)},on(s,l){return x.on(s,l)},off(s,l){x.off(s,l)},isOpen(){return qe()&&ve},isVoiceActive(){return je.active},toggleReadAloud(s){R.toggleReadAloud(s)},stopReadAloud(){R.stopSpeaking()},getReadAloudState(s){return R.getReadAloudState(s)},onReadAloudChange(s){return R.onReadAloudChange(s)},getState(){return{open:qe()&&ve,launcherEnabled:pe,voiceActive:je.active,streaming:R.isStreaming()}},showCSATFeedback(s){!ve&&qe()&&pt(!0,"system");let l=Te.querySelector(".persona-feedback-container");l&&l.remove();let f=Fu({onSubmit:async(g,v)=>{R.isClientTokenMode()&&await R.submitCSATFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});Te.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(s){!ve&&qe()&&pt(!0,"system");let l=Te.querySelector(".persona-feedback-container");l&&l.remove();let f=Uu({onSubmit:async(g,v)=>{R.isClientTokenMode()&&await R.submitNPSFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});Te.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(s,l){return R.submitCSATFeedback(s,l)},async submitNPSFeedback(s,l){return R.submitNPSFeedback(s,l)},destroy(){Up(),xs!=null&&(clearInterval(xs),xs=null),fe.forEach(s=>s()),Ge.remove(),Kt?.remove(),Tt?.destroy(),mo?.remove(),as&&Ne.removeEventListener("click",as)}};if(((o?.debugTools??!1)||!!n.debug)&&typeof window<"u"){let s=window.AgentWidgetBrowser,l={controller:Et,getMessages:Et.getMessages,getStatus:Et.getStatus,getMetadata:Et.getPersistentMetadata,updateMetadata:Et.updatePersistentMetadata,clearHistory:()=>Et.clearChat(),setVoiceActive:f=>f?Et.startVoiceRecognition():Et.stopVoiceRecognition()};window.AgentWidgetBrowser=l,fe.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=s)})}if(typeof window<"u"){let s=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),l=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.focusInput()};if(window.addEventListener("persona:focusInput",l),fe.push(()=>{window.removeEventListener("persona:focusInput",l)}),k){let j=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===s)&&Et.showEventStream()},J=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===s)&&Et.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",J),fe.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",J)})}let f=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.showHistory()},g=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",g),fe.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",g)});let v=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.showArtifacts()},w=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.hideArtifacts()},_=j=>{let J=j.detail;J?.instanceId&&J.instanceId!==s||J?.artifact&&Et.upsertArtifact(J.artifact)},$=j=>{let J=j.detail;J?.instanceId&&J.instanceId!==s||typeof J?.id=="string"&&Et.selectArtifact(J.id)},U=j=>{let J=j.detail;(!J?.instanceId||J.instanceId===s)&&Et.clearArtifacts()};window.addEventListener("persona:showArtifacts",v),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",_),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",U),fe.push(()=>{window.removeEventListener("persona:showArtifacts",v),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",_),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",U)})}let rn=uL(n.persistState);if(rn&&qe()){let s=pL(rn.storage),l=`${rn.keyPrefix}widget-open`,f=`${rn.keyPrefix}widget-voice`,g=`${rn.keyPrefix}widget-voice-mode`;if(s){let v=rn.persist?.openState&&s.getItem(l)==="true",w=rn.persist?.voiceState&&s.getItem(f)==="true",_=rn.persist?.voiceState&&s.getItem(g)==="true";if(v&&(Tt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Et.open(),setTimeout(()=>{if(w||_)Et.startVoiceRecognition();else if(rn.persist?.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0)),rn.persist?.openState&&(x.on("widget:opened",()=>{s.setItem(l,"true")}),x.on("widget:closed",()=>{s.setItem(l,"false")})),rn.persist?.voiceState&&(x.on("voice:state",$=>{s.setItem(f,$.active?"true":"false")}),x.on("user:message",$=>{s.setItem(g,$.viaVoice?"true":"false")})),rn.clearOnChatClear){let $=()=>{s.removeItem(l),s.removeItem(f),s.removeItem(g)},U=()=>$();window.addEventListener("persona:clear-chat",U),fe.push(()=>{window.removeEventListener("persona:clear-chat",U)})}}}if(ee&&qe()&&(Tt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Et.open()},0)),ua(),!PA){let s=Pa(()=>{R&&(us++,Ot.clear(),Jo(Te,R.getMessages(),wt))});fe.push(s)}A=()=>{R&&(us++,Ot.clear(),Jo(Te,R.getMessages(),wt))},R.getMessages().length>0&&xd(),b=()=>{R&&(us++,Ot.clear(),Jo(Te,R.getMessages(),wt))};let yT=qx(()=>{R&&(us++,Ot.clear(),Jo(Te,R.getMessages(),wt))});fe.push(yT);let bT=eh(()=>{R&&(us++,Ot.clear(),Jo(Te,R.getMessages(),wt),hr()?.updateInlineArtifactBlocks(Te,Yo.artifacts,{suppressTransition:!0}),fn())});return fe.push(bT),Et};var Bw=(e,t)=>{let o=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(o);if(n)return Math.max(0,parseFloat(n[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(o);return r?Math.max(0,t*parseFloat(r[1])/100):420},gL=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},hL=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},yL=(e,t)=>{let o=e.parentElement;if(!o)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",o.appendChild(n);let r=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),!(!r||a)&&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.")},Ow=(e,t)=>{let o=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=o?"":"100%",e.style.display=o?"":"flex",e.style.flexDirection=o?"":"column",e.style.flex=o?"":"1 1 auto",e.style.minHeight=o?"":"0",e.style.minWidth=o?"":"0"},yh=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=""},Dw=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",yh(e)},mh=e=>{e.style.transition=""},gh=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=""},hh=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},$u=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},bL=(e,t,o,n,r)=>{r?o.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(o,n),e.appendChild(t)):o.parentElement===t&&(t.replaceChildren(),e.appendChild(o),e.appendChild(n))},vL=(e,t,o,n,r,a)=>{let i=a?t:e;r==="left"?i.firstElementChild!==n&&i.replaceChildren(n,o):i.lastElementChild!==n&&i.replaceChildren(o,n)},xL=e=>{let t=Kr(e),o=t.components?.panel,n=(r,a)=>r==null||r===""?a:vo(t,r)??r;return{inset:n(o?.inset,nu),canvasBackground:n(o?.canvasBackground,ru)}},_w=(e,t,o,n)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=o,e.style.background=n},CL=(e,t,o,n,r,a,i,d)=>{let c=Do(a),u=c.reveal==="push",p=d!=null,m=d?.inset??"",h=d?.canvasBackground??"";bL(e,t,o,n,u),vL(e,t,o,n,c.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"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",o.style.display="flex",o.style.flexDirection="column",o.style.minHeight="0",o.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let y=e.ownerDocument.defaultView,C=a?.launcher?.mobileFullscreen??!0,A=a?.launcher?.mobileBreakpoint??640,M=y!=null?y.innerWidth<=A:!1;if(C&&M&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),gh(t),mh(n),Dw(n),hh(o),$u(r,n),_w(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",o.style.flex="1 1 auto",o.style.width="100%",o.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??ro),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(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",o.style.flex="1 1 auto",o.style.width="100%",o.style.maxWidth="100%",o.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Dw(n),gL(n,c.maxHeight),_w(n,p&&i,m,h),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",gh(t),mh(n),hh(o),$u(r,n);let T=c.animate?"transform 180ms ease":"none",I=c.side==="right"?"translateX(100%)":"translateX(-100%)",b=i?"translateX(0)":I;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=c.width,n.style.maxWidth=c.width,n.style.minWidth=c.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=T,n.style.transform=b,n.style.pointerEvents=i?"auto":"none",n.style.zIndex="2",c.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(c.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",mh(n),yh(n),$u(r,n);let T=Bw(c.width,e.clientWidth),I=Math.max(0,e.clientWidth),b=c.animate?"margin-left 180ms ease":"none",S=c.side==="right"?i?-T:0:i?0:-T;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${I+T}px`,t.style.transition=b,t.style.marginLeft=`${S}px`,t.style.transform="",o.style.flex="0 0 auto",o.style.flexGrow="0",o.style.flexShrink="0",o.style.width=`${I}px`,o.style.maxWidth=`${I}px`,o.style.minWidth=`${I}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=c.width,n.style.minWidth=c.width,n.style.maxWidth=c.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",gh(t),yh(n),hh(o),$u(r,n);let T=c.reveal==="emerge";T?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=i?c.width:"0px",b=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",S=!i;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${I}`,n.style.width=I,n.style.maxWidth=I,n.style.minWidth=I,n.style.minHeight="0",hL(n,c.maxHeight),n.style.overflow=T||S?"hidden":"visible",n.style.transition=b,T){n.style.alignItems=c.side==="right"?"flex-start":"flex-end";let x=p?`calc(${Bw(c.width,e.clientWidth)}px - (2 * ${m}))`:c.width;r.style.width=x,r.style.minWidth=x,r.style.maxWidth=x,r.style.boxSizing="border-box"}}},SL=(e,t)=>{let o=e.ownerDocument.createElement("div");return Ow(o,t),e.appendChild(o),{mode:"direct",host:o,shell:null,syncWidgetState:()=>{},updateConfig(n){Ow(o,n)},destroy(){o.remove()}}},wL=(e,t)=>{let{ownerDocument:o}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,i=o.createElement("div"),d=o.createElement("div"),c=o.createElement("div"),u=o.createElement("aside"),p=o.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;d.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),n.insertBefore(i,e),c.appendChild(e);let h=null,y=()=>{h?.disconnect(),h=null},C=null,A=()=>{C=t?.launcher?.detachedPanel===!0?xL(t):null};A();let M=()=>{CL(i,d,c,u,p,t,m,C)},E=null,T=()=>{E?.(),E=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(E=za(()=>{A(),M()}))},I=()=>{y(),Do(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{M()}),h.observe(i)))},b=!1,S=()=>{M(),I(),m&&!b&&i.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,yL(i,Do(t)))},x=i.ownerDocument.defaultView,L=()=>{S()};return x?.addEventListener("resize",L),Do(t).reveal==="push"?(d.appendChild(c),d.appendChild(u),i.appendChild(d)):(i.appendChild(c),i.appendChild(u)),S(),T(),{mode:"docked",host:p,shell:i,syncWidgetState(N){let X=N.launcherEnabled?N.open:!0;m!==X&&(m=X,S())},updateConfig(N){t=N,(t?.launcher?.enabled??!0)===!1&&(m=!0),A(),S(),T()},destroy(){x?.removeEventListener("resize",L),E?.(),E=null,y(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),i.remove()}}},Vl=(e,t)=>Ct(t)?wL(e,t):SL(e,t);var AL=e=>{if(typeof window>"u"||typeof document>"u")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},Nw=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let n=o.cloneNode(!0);e.insertBefore(n,e.firstChild)},ju=[],Fw=()=>[...ju],Uw=e=>{let t=AL(e.target),o=e.useShadowDom===!0,n=t.ownerDocument,r=e.config,a=Vl(t,r),i,d=[],c=(M,E)=>{let I=!(E?.launcher?.enabled??!0)||Ct(E),b=n.createElement("div");if(b.setAttribute("data-persona-root","true"),I&&(b.style.height="100%",b.style.display="flex",b.style.flexDirection="column",b.style.flex="1",b.style.minHeight="0",b.style.minWidth="0"),o){let S=M.attachShadow({mode:"open"});S.appendChild(b),Nw(S,n)}else M.appendChild(b),Nw(M,n);return t.id&&b.setAttribute("data-persona-instance",t.id),b},u=()=>{a.syncWidgetState(i.getState())},p=()=>{d.forEach(M=>M()),d=[i.on("widget:opened",u),i.on("widget:closed",u)],u()},m=()=>{let M=c(a.host,r);i=Vu(M,r,{debugTools:e.debugTools}),p()},h=()=>{d.forEach(M=>M()),d=[],i.destroy()};m(),e.onChatReady?.();let y=M=>{h(),a.destroy(),a=Vl(t,M),r=M,m()},C={update(M){let E=Wu(r??{},M),T=Ct(r),I=Ct(E),b=Qr(r),S=Qr(E);if(T!==I||b!==S){y(E);return}r=E,a.updateConfig(r),i.update(M),u()},destroy(){h(),a.destroy();let M=ju.indexOf(A);M!==-1&&ju.splice(M,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},A=new Proxy(C,{get(M,E,T){if(E==="host")return a.host;if(E in M)return Reflect.get(M,E,T);let I=i[E];return typeof I=="function"?I.bind(i):I}});return ju.push(A),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=A),A};var zw=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),ML=new Set(["button","a","input","select","textarea","details","summary"]),TL=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),bh=/\b(product|card|item|listing|result)\b/i,xh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,EL=3e3,PL=100;function Kw(e){let t=typeof e.className=="string"?e.className:"";if(bh.test(t)||e.id&&bh.test(e.id))return!0;for(let o=0;o<e.attributes.length;o++){let n=e.attributes[o];if(n.name.startsWith("data-")&&bh.test(n.value))return!0}return!1}function Gw(e){return xh.test((e.textContent??"").trim())}function Xw(e){let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=t[o].getAttribute("href")??"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function kL(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function qw(e){let t=e.match(xh);return t?t[0]:null}function Vw(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let n=t.getAttribute("href");return{title:t.textContent.trim(),href:n&&n!=="#"?n:null}}let o=e.querySelector("h1, h2, h3, h4, h5, h6");return o?.textContent?.trim()?{title:o.textContent.trim(),href:null}:{title:"",href:null}}function LL(e){let t=[],o=n=>{let r=n.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(n=>o(n.textContent??"")),e.querySelectorAll('[role="button"]').forEach(n=>o(n.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{o(n.value??"")}),t.slice(0,6)}var IL="commerce-card",RL="result-card";function $w(e){return!Kw(e)||!Gw(e)||!Xw(e)&&!kL(e)?0:5200}function jw(e){return!Kw(e)||Gw(e)||!Xw(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Ch=[{id:IL,scoreElement(e){return $w(e)},shouldSuppressDescendant(e,t,o){if(t===e||!e.contains(t))return!1;if(o.interactivity==="static"){let n=o.text.trim();return!!(n.length===0||xh.test(n)&&n.length<32)}return!0},formatSummary(e,t){if($w(e)===0)return null;let{title:o,href:n}=Vw(e),r=qw((e.textContent??"").trim())??qw(t.text)??"",a=LL(e);return[n&&o?`[${o}](${n})${r?`: ${r}`:""}`:o?`${o}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
139
|
+
`)}},{id:RL,scoreElement(e){return jw(e)},formatSummary(e,t){if(jw(e)===0)return null;let{title:o,href:n}=Vw(e);return[n&&o?`[${o}](${n})`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
140
|
+
`)}}];function HL(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function WL(e){let t=e.options??{},o=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,d=t.mode??"structured",c=t.maxCandidates??Math.max(500,o*10),u=e.rules??Ch;return d==="simple"&&e.rules&&e.rules.length>0?(HL(),u=[]):d==="simple"&&(u=[]),{mode:d,maxElements:o,maxCandidates:c,excludeSelector:n,maxTextLength:r,visibleOnly:a,root:i,rules:u}}function vh(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var BL=["data-testid","data-product","data-action","data-id","data-name","data-type"];function OL(e){let t=e.tagName.toLowerCase(),o=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||o==="textbox"||o==="combobox"||o==="listbox"||o==="spinbutton"?"input":t==="button"||o==="button"||ML.has(t)||o&&TL.has(o)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Qw(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 DL(e){let t={},o=e.id;o&&(t.id=o);let n=e.getAttribute("href");n&&(t.href=n);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let a=e.getAttribute("type");a&&(t.type=a);let i=e.getAttribute("value");i&&(t.value=i);let d=e.getAttribute("name");d&&(t.name=d);let c=e.getAttribute("role");c&&(t.role=c);for(let u=0;u<e.attributes.length;u++){let p=e.attributes[u];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Sh(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${vh(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of BL){let a=e.getAttribute(r);if(a){let i=`${t}[${r}="${vh(a)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let o=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(o.length>0){let r=`${t}.${o.map(i=>vh(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let a=e.parentElement;if(a){let d=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(d>=0){let c=`${r}:nth-of-type(${d+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let n=e.parentElement;if(n){let a=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function _L(e){return e==="static"?PL:EL}function Yw(e,t){let o=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:Sh(e),tagName:o,text:n,role:e.getAttribute("role"),interactivity:OL(e),attributes:DL(e)}}function NL(e,t,o,n){let r=_L(t.interactivity),a=null;for(let i of o){let d=i.scoreElement(e,t,n);d>0&&(r+=d,i.formatSummary&&!a&&(a=i))}return{score:r,formattingRule:a}}function FL(e,t){for(let o of e)if(t.el!==o.el&&o.formattingRule?.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function UL(e,t){let o={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,r=[],a=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),d=i.currentNode;for(;d&&r.length<e.maxCandidates;){if(d.nodeType===Node.ELEMENT_NODE){let u=d,p=u.tagName.toLowerCase();if(zw.has(p)){d=i.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){d=i.nextNode();continue}}catch{}if(e.visibleOnly&&!Qw(u)){d=i.nextNode();continue}let m=Yw(u,e.maxTextLength),h=m.text.length>0,y=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(M=>M==="role");if(!h&&!y){d=i.nextNode();continue}if(n.has(m.selector)){d=i.nextNode();continue}n.add(m.selector);let{score:C,formattingRule:A}=NL(u,m,e.rules,o);r.push({el:u,domIndex:a,enriched:m,score:C,formattingRule:A}),a+=1}d=i.nextNode()}r.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex});let c=[];for(let u of r){if(c.length>=e.maxElements)break;FL(c,u)||c.push(u)}return c.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:m===1&&p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex}),c.map(u=>{let p;if(u.formattingRule?.formatSummary){let h=u.formattingRule.formatSummary(u.el,u.enriched,o);h&&(p=h)}let m={...u.enriched};return p&&(m.formattedSummary=p),m})}function qL(e,t){let o=[],n=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&o.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,u=c.tagName.toLowerCase();if(zw.has(u)){a=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Qw(c)){a=r.nextNode();continue}let p=Yw(c,e.maxTextLength),m=p.text.length>0,h=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(y=>y==="role");if(!m&&!h){a=r.nextNode();continue}n.has(p.selector)||(n.add(p.selector),o.push(p))}a=r.nextNode()}let i=[],d=[];for(let c of o)c.interactivity!=="static"?i.push(c):d.push(c);return[...i,...d].slice(0,e.maxElements)}function Jw(e={}){let t=WL(e),o=t.root??document.body;return o?t.mode==="simple"?qL(t,o):UL(t,o):[]}var zu=100;function Zw(e,t={}){if(e.length===0)return"No page elements found.";let o=t.mode??"structured",n=[];if(o==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
|
|
141
141
|
${a.map(i=>`- ${i.split(`
|
|
142
142
|
`).join(`
|
|
143
143
|
`)}`).join(`
|
|
@@ -151,7 +151,7 @@ ${a.join(`
|
|
|
151
151
|
${a.join(`
|
|
152
152
|
`)}`)}return n.join(`
|
|
153
153
|
|
|
154
|
-
`)}var
|
|
154
|
+
`)}var VL={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"}}},eA={components:{panel:{borderRadius:"0",shadow:"none"}}},wh={id:"shop",label:"Shopping Assistant",config:{theme:VL,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Ko},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},Ah={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:eA}},Mh={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:eA}},Th={shop:wh,minimal:Ah,fullscreen:Mh};function tA(e){return Th[e]}var He=typeof document<"u"?document.currentScript?.src??null:null;Iv(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});gv(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});Ox(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});qC(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});VC(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});Sw(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"history-view.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the history-view.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host history-view.js alongside it.`)):import(e)});bS(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"animations-extra.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the animations-extra.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin.`)):import(e)});JS(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"approval-ui.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the approval-ui.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host approval-ui.js alongside it.`)):import(e)});Wx(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"voice-runtime.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the voice-runtime.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host voice-runtime.js alongside it.`)):import(e)});nw(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"artifacts-ui.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the artifacts-ui.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host artifacts-ui.js alongside it.`)):import(e)});fw(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"forms-ui.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the forms-ui.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host forms-ui.js alongside it.`)):import(e)});Fx(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"icons-extra.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the icons-extra.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host icons-extra.js alongside it, or register the icons they use via registerIcons().`)):import(e)});Wv(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"webmcp-runtime.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the webmcp-runtime.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host webmcp-runtime.js alongside it.`)):import(e)});Dx(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"session-reconnect.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the session-reconnect.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host session-reconnect.js alongside it.`)):import(e)});tw(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"event-stream-view.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the event-stream-view.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host event-stream-view.js alongside it.`)):import(e)});return kT($L);})();
|
|
155
155
|
/*! Bundled license information:
|
|
156
156
|
|
|
157
157
|
lucide/dist/esm/icons/activity.mjs:
|