@runtypelabs/persona 4.22.1 → 4.23.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +24 -24
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.global.js +22 -22
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +24 -24
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js.map +1 -1
- package/dist/theme-editor-preview.cjs +30 -30
- package/dist/theme-editor-preview.d.cts +6 -0
- package/dist/theme-editor-preview.d.ts +6 -0
- package/dist/theme-editor-preview.js +20 -20
- package/package.json +1 -1
- package/src/client-session-renewal.test.ts +268 -0
- package/src/client-visitor-history.test.ts +86 -0
- package/src/client.interrupt.test.ts +1 -1
- package/src/client.ts +61 -18
- package/src/launcher-global.ts +1 -1
- package/src/ui.ts +13 -0
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
import{a as mc,b as Jh,c as ou,d as ua,e as hc,f as ga,g as yc,h as fa,i as Zh,j as ma}from"./chunk-CPVD5P5B.js";import{b as Th,c as ac,d as kh,e as Js,f as Ph,g as lc,h as Ih,i as Lh,j as Hh,k as Rh,l as cc,m as dc,n as eu,o as pc,p as pa,q as Wh,r as Bh,s as Dh,t as Oh}from"./chunk-NQLDCJAP.js";import{a as Vh,b as Kh,c as Qo,d as cs,e as Gh,f as Qh,g as Xh,h as nu,i as Yh}from"./chunk-VK6JOIYJ.js";import{a as Tt,b as Ah,c as sc,e as Ys,f as Mh,g as ic,h as Eh,j as Nh,k as Fh,l as ge,m as Nt,n as an,o as uc,p as ey,q as ty,u as ny,v as Zs,w as Xo}from"./chunk-NIKYKSNZ.js";import{a as ls,d as ru}from"./chunk-EFJBUH5F.js";import{a as _h,c as Uh,d as fc,e as tu,f as jh}from"./chunk-UTVLOTWB.js";import{a as $h,c as qh,d as zh}from"./chunk-R2TMIMDI.js";import{a as en}from"./chunk-7NQ4ZTHF.js";import{b as gc}from"./chunk-Q735PSZL.js";import{a as k,c as G,d as _n}from"./chunk-76IELU7F.js";function oy(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function Tn(t){return t?.type==="runtype"||t?.type==="custom"}var dx=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function ry(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:dx()}catch{return!1}}var sy=/^\s*\|?[\s:|-]*-[\s:|-]*$/,iy=t=>t.includes("|"),ay=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},px=t=>`| ${t.join(" | ")} |`,ux=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,gx=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),ly=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
2
2
|
`),n=!1;for(let o=0;o<e.length-1;o++){let s=e[o],i=e[o+1];if(!iy(s)||sy.test(s)||!sy.test(i))continue;let l=ay(s).length;if(l<1)continue;let c=ux(l);e[o+1]!==c&&(e[o+1]=c,n=!0);let d=o+2;for(;d<e.length;d++){let u=e[d];if(u.trim()===""||!iy(u))break;let g=px(gx(ay(u),l));e[d]!==g&&(e[d]=g,n=!0)}o=d-1}return n?e.join(`
|
|
3
|
-
`):t};var cy="var(--persona-md-table-scroll-fade, 24px)",dy=new WeakSet;function uy(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let s=document.createElement("div");s.className="persona-table-scroll",n.replaceWith(s),s.appendChild(n)})}function py(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,s=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":cy),t.style.setProperty("--persona-fade-r",s<=1?"0px":cy)}function su(t){dy.has(t)||(dy.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&py(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(py)}var{setLoader:ok,load:fx}=Tt({fallbackImport:()=>import("./webmcp-runtime-JI7T4QYF.js")});var gy=fx;function Qn(t){return t==="card"?"collapsed":t}function ei(t){return t.split(";",1)[0].trim().toLowerCase()}function mx(t,e){if(!t)return;let n=Object.entries(t);for(let[s,i]of n)if(ei(s)===e)return{mode:Qn(i),selector:ei(s)};let o=`${e.split("/",1)[0]}/*`;for(let[s,i]of n)if(ei(s)===o)return{mode:Qn(i),selector:o}}function hx(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:Qn(o.files),matchedBy:{type:"files"}};let c=e.file.mimeType?ei(e.file.mimeType):void 0,d=c?mx(o.files.byMediaType,c):void 0;if(c&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:c,selector:d.selector}};if(o.files.default)return{mode:Qn(o.files.default),matchedBy:{type:"files"}}}let s=o.byKind?.[e.artifactType];if(s)return{mode:Qn(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let i=o.byType?.[e.artifactType];if(i)return{mode:Qn(i),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let l=e.presentation?.preferredMode;return l?{mode:Qn(l),matchedBy:{type:"preferredMode"}}:o.default?{mode:Qn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Sr(t,e){return hx(t,e).mode}function ha(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var yx="agent_",bx="flow_";function fy(t){return t.startsWith(yx)?{kind:"agentId",agentId:t}:t.startsWith(bx)?{kind:"flowId",flowId:t}:null}function my(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let l=n.slice(0,o),c=n.slice(o+1);if(l==="runtype"){let u=fy(c);if(u)return u;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let d=e?.[l];if(!d)throw new Error(`[Persona] No target provider registered for "${l}". Add a \`targetProviders.${l}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(c).payload}}let s=fy(n);if(s)return s;let i=e?.default;if(i)return{kind:"payload",payload:i(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function bc(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ti(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function hy(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}import{parse as vx,ARR as Cx,OBJ as wx,STR as Sx}from"partial-json";var iu="ask_user_question",ya=8,ni="data-persona-ask-sheet-for",xx="Other",Ax="Other\u2026",by="Type your own answer here",vy="Send",Mx="Next",Ex="Back",Tx="Submit all",kx="Skip",Px=3,au="data-ask-current-index",lu="data-ask-question-count",Cy="data-ask-answers",cu="data-ask-grouped",wy="data-ask-layout",Ix=t=>t.layout==="pills"?"pills":"rows",Lx=t=>t.getAttribute(wy)==="pills"?"pills":"rows",yy=!1,Sy=t=>t.replace(/["\\]/g,"\\$&"),ds=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===iu,du=t=>t?.features?.askUserQuestion??{},oi=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let s=o.join(""),i=vx(s,Sx|wx|Cx);if(i&&typeof i=="object")return{payload:i,complete:n}}catch{}return{payload:null,complete:n}},ba=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>ya&&!yy&&(yy=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${ya}.`)),e.slice(0,ya)},Hx=t=>ba(t)[0]??null,Rx=(t,e)=>ba(t)[e]??null,Wx=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},xy=(t,e,n)=>{if(t!=="rows")return null;let o=k("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let s=k("span","persona-ask-row-check");o.appendChild(s)}else{let s=k("span","persona-ask-row-badge");s.textContent=String(n+1),o.appendChild(s)}return o},Bx=(t,e,n,o)=>{let i=k("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(i.type="button",i.setAttribute("role",o?"checkbox":"button"),i.setAttribute("aria-pressed","false"),i.setAttribute("data-ask-user-action","pick"),i.setAttribute("data-option-index",String(e)),i.setAttribute("data-option-label",t.label),n==="rows"){let l=k("span","persona-ask-row-content"),c=k("span","persona-ask-row-label");if(c.textContent=t.label,l.appendChild(c),t.description){let u=k("span","persona-ask-row-description");u.textContent=t.description,l.appendChild(u)}i.appendChild(l);let d=xy(n,o,e);d&&i.appendChild(d)}else i.textContent=t.label,t.description&&(i.title=t.description);return i},Dx=t=>{let n=k("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Ox=(t,e,n,o)=>{let i=k("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");i.setAttribute("role","group"),i.setAttribute("data-ask-pill-list","true");let l=!!t?.multiSelect,d=(Array.isArray(t?.options)?t.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<Px;g++)i.appendChild(Dx(o));return i}if(d.forEach((g,m)=>{i.appendChild(Bx(g,m,o,l))}),t?.allowFreeText!==!1){let g=o==="rows"?xx:Ax;if(o==="rows"){let m=k("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(d.length)),m.setAttribute("data-ask-other-row","true");let b=k("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=e.freeTextPlaceholder??by,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",e.freeTextLabel??g),b.appendChild(h),m.appendChild(b);let x=xy(o,l,d.length);x&&m.appendChild(x),i.appendChild(m)}else{let m=k("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=e.freeTextLabel??g,i.appendChild(m)}}return i},Ay=(t,e)=>{let o=k("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=t.freeTextPlaceholder??by,s.setAttribute("data-ask-free-text-input","true"),o.appendChild(s),e!=="rows"){let i=k("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=t.submitLabel??vy,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},_x=t=>{let e=k("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=k("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??vy,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},Nx=(t,e,n)=>{let o=k("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let s=k("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=n.backLabel??Ex,s.setAttribute("data-ask-user-action","back"),s.disabled=t===0,o.appendChild(s);let i=k("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),l=k("button","persona-ask-nav-skip persona-pointer-events-auto");l.type="button",l.textContent=n.skipLabel??kx,l.setAttribute("data-ask-user-action","skip"),i.appendChild(l);let c=k("button","persona-ask-nav-next persona-pointer-events-auto");c.type="button";let d=t===e-1;return c.textContent=d?n.submitAllLabel??Tx:n.nextLabel??Mx,c.setAttribute("data-ask-user-action",d?"submit-all":"next"),c.disabled=!0,i.appendChild(c),o.appendChild(i),o},ps=t=>{let e=t.getAttribute(Cy);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},My=(t,e)=>{t.setAttribute(Cy,JSON.stringify(e))},Xn=t=>{let e=Number(t.getAttribute(au)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Fx=(t,e)=>{t.setAttribute(au,String(Math.max(0,Math.floor(e))))},ri=t=>{let e=Number(t.getAttribute(lu)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},xr=t=>t.getAttribute(cu)==="true",Ux=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((s,i)=>{let l=typeof s?.question=="string"?s.question:"";if(l&&Object.prototype.hasOwnProperty.call(n,l)){let c=n[l];(typeof c=="string"||Array.isArray(c))&&(o[i]=c)}}),o},$x=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},vc=(t,e)=>{let{payload:n}=oi(e),o=ba(n),s=ps(t),i={},l=new Set;return o.forEach((c,d)=>{let u=typeof c?.question=="string"?c.question:"";u&&(l.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),l.add(u),Object.prototype.hasOwnProperty.call(s,d)&&(i[u]=s[d]))}),i},Ey=t=>{let e=ps(t),n=Xn(t),o=e[n],s=new Set;typeof o=="string"?s.add(o):Array.isArray(o)&&o.forEach(d=>s.add(d));let i=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');i.forEach(d=>{let u=d.getAttribute("data-option-label")??"",g=s.has(u);d.setAttribute("aria-pressed",g?"true":"false"),d.classList.toggle("persona-ask-pill-selected",g)});let l=new Set(Array.from(i).map(d=>d.getAttribute("data-option-label")??"")),c=t.querySelector('[data-ask-free-text-input="true"]');c&&(typeof o=="string"&&o.length>0&&!l.has(o)?(c.value=o,c.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):c.value="")},Ty=t=>{if(!xr(t))return;let e=ps(t),n=Xn(t),o=e[n],s=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,i=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');i&&(i.disabled=!s);let l=t.querySelector('[data-ask-user-action="submit-multi"]');if(l){let c=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));l.disabled=c.length===0}},pu=(t,e,n)=>{let o=du(n),s=Lx(t),{payload:i,complete:l}=oi(e),c=xr(t),d=Xn(t),u=ri(t),g=c?Rx(i,d):Hx(i),m=!!g?.multiSelect,b=t.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=c?`${d+1}/${u}`:"");let h=t.querySelector('[data-ask-stepper="true"]');h&&h.remove();let x=t.querySelector('[data-ask-question="true"]');if(x){let I=typeof g?.question=="string"?g.question:"";x.textContent=I,x.classList.toggle("persona-ask-question-skeleton",!I&&!l)}let T=t.querySelector('[data-ask-pill-list="true"]');if(T){let I=Ox(g,o,l,s);T.replaceWith(I)}if(s!=="rows"){let I=t.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(Ay(o,s))}let M=t.querySelector('[data-ask-multi-actions="true"]');!c&&m&&!M?t.appendChild(_x(o)):(!m||c)&&M&&M.remove(),t.setAttribute("data-multi-select",m?"true":"false");let O=t.querySelector('[data-ask-nav-row="true"]');if(c){let I=Nx(d,u,o);O?O.replaceWith(I):t.appendChild(I)}else O&&O.remove();Ey(t),Ty(t)},qx=(t,e,n)=>{let o=du(e),s=Ix(o),i=t.toolCall.id,l=ba(n),c=Math.max(1,l.length),d=c>1,u=Ux(t,l),g=d?$x(t,c):0,m=k("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(ni,i),m.setAttribute("data-tool-call-id",i),m.setAttribute("data-message-id",t.id),m.setAttribute(lu,String(c)),m.setAttribute(au,String(g)),m.setAttribute(cu,d?"true":"false"),m.setAttribute(wy,s),My(m,u),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Wx(m,o);let b=k("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=k("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",b.appendChild(h);let x=k("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",b.appendChild(x),m.appendChild(b);let M=k("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),s!=="rows"&&m.appendChild(Ay(o,s)),pu(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},zx=(t,e,n)=>{let{payload:o}=oi(e),s=Math.max(1,ba(o).length);s>ri(t)&&(t.setAttribute(lu,String(s)),s>1&&!xr(t)&&t.setAttribute(cu,"true")),pu(t,e,n)};var Cc=(t,e,n)=>{if(!n||!ds(t)||du(e).enabled===!1)return;let s=t.toolCall.id;n.querySelectorAll(`[${ni}]`).forEach(u=>{u.getAttribute(ni)!==s&&u.remove()});let l=n.querySelector(`[${ni}="${Sy(s)}"]`);if(l){zx(l,t,e);return}let{payload:c}=oi(t),d=qx(t,e,c);n.appendChild(d)},si=(t,e)=>{if(!t)return;let n=e?`[${ni}="${Sy(e)}"]`:`[${ni}]`;t.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let i=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(i)?i:180)})},uu=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),Ar=(t,e)=>{let n=ps(t),o=Xn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,My(t,n),Ey(t),Ty(t)},wc=(t,e,n,o)=>{let s=ri(t),i=Math.max(0,Math.min(s-1,o));Fx(t,i),pu(t,e,n)};var Mr="suggest_replies";var jx={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},Py={name:Mr,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:jx,origin:"sdk",annotations:{readOnlyHint:!0}},Iy=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),va=t=>t.variant==="tool"&&t.toolCall?.name===Mr,Vx=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(s=>{if(typeof s=="string"){let c=s.trim();return c?[c]:[]}if(!s||typeof s!="object")return[];let i=s;if(typeof i.label!="string"||!i.label.trim())return[];let l={label:i.label.trim()};return typeof i.prompt=="string"&&i.prompt.trim()&&(l.prompt=i.prompt.trim()),typeof i.description=="string"&&i.description.trim()&&(l.description=i.description.trim()),[l]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Ly=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!va(n))continue;let o=Vx(n.toolCall?.args);return o.length>0?o:null}return null},ky=new Set,Kx=(t,e,n)=>{let o=`${t}:${e}:${n}`;ky.has(o)||(ky.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Er=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=l=>{let c=e?.[l],d=n?.[l];c===void 0||d===void 0||c!==d&&Kx(l,d,c)};t&&(o("enabled"),o("expose"));let s=e?.enabled??n?.enabled??!0,i=s?e?.expose??n?.expose??!1:!1;return{enabled:s,expose:i}};var Gx={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ya,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},Qx={name:iu,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:Gx,origin:"sdk",annotations:{readOnlyHint:!0}},Sc=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(Qx),Er(t).expose&&e.push(Py),e};var Hy="4.22.1";var us=Hy;var ii="[Image]";function Ry(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function xc(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Ao(t){return{type:"text",text:t}}function Wy(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var By=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Yx=["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"],Yo=[...By,...Yx];function Jx(t){return By.includes(t)||t.startsWith("image/")}function Ac(t){return Jx(t.type)}function Dy(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function Oy(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;Ac(t)?e({type:"image",image:s,mimeType:t.type,alt:t.name}):e({type:"file",data:s,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function _y(t,e=Yo,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function Zx(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Ny(t,e){let n=Zx(e).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"}[t]||n||"FILE"}var eA=["user","assistant","system"],tA=0;function Fy(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function Mc(t){return typeof t=="string"?t:void 0}function nA(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?Ao(e.text):null;case"image":return typeof e.image=="string"?Wy(e.image,{mimeType:Mc(e.mimeType),alt:Mc(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?Dy(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...Mc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...Mc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function oA(t,e){let n=Fy(e),o=t.map(l=>Fy(l.timestamp)),s=new Array(t.length),i=0;for(;i<o.length;){let l=o[i];if(l!==null){s[i]=l,i+=1;continue}let c=i;for(;c+1<o.length&&o[c+1]===null;)c+=1;let d=c-i+1,u=i>0?s[i-1]:null,g=c+1<o.length?o[c+1]:null,m=g!==null&&n!==null?Math.min(g,n):g??n;for(let b=0;b<d;b+=1)s[i+b]=m!==null?m-(d-b):u!==null?u+b+1:tA+b;i=c+1}return s.map(l=>new Date(l).toISOString())}function Uy(t,e){let n=oA(t,e?.beforeCreatedAt),o=[];return t.forEach((s,i)=>{if(typeof s?.id!="string"||s.id===""||!eA.includes(s.role))return;let l=s.role,c=n[i];if(s.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:s.id,role:l,content:"",createdAt:c,agentMetadata:d});return}if(typeof s.displayContent=="string"){o.push({id:s.id,role:l,content:s.displayContent,createdAt:c});return}if(typeof s.content=="string"){o.push({id:s.id,role:l,content:s.content,createdAt:c});return}if(Array.isArray(s.content)){let d=s.content.map(nA).filter(g=>g!==null),u=Ry(d);o.push({id:s.id,role:l,content:u||(xc(d)?ii:""),createdAt:c,...d.length>0&&{contentParts:d}});return}o.push({id:s.id,role:l,content:"",createdAt:c})}),o}function Ca(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function wa(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,s)=>{let i=new Date(o.createdAt).getTime(),l=new Date(s.createdAt).getTime();if(!Number.isNaN(i)&&!Number.isNaN(l)&&i!==l)return i-l;let c=o.sequence??0,d=s.sequence??0;return c!==d?c-d:o.id.localeCompare(s.id)})}var rA="https://api.runtype.com/v1/dispatch",$y="https://api.runtype.com",Oe=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},qy=32768,gu=49152,zy=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},jy=t=>"reason"in t?t.reason:void 0,Vy="The identity proof was not admitted; account history is unavailable",Ky="The identity proof was rejected",Gy="The request carried no visitor credential",Qy="The stored visitor belongs to a different signed-in user",fu=(t,e)=>t instanceof Oe&&t.code===e;function sA(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let s=e.indexOf("/");if(s>0){let i=e.slice(s+1).split(";")[0]?.trim()??"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var mu=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function iA(t){switch(t){case"json":return Dh;case"regex-json":return Bh;case"xml":return Oh;default:return Wh}}var Xy=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function aA(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let s=Xy(n);if(!Xy(o))return t;if(!s||o===n||o.startsWith(n))return e;let l=pa(t);return pa(e)!==null&&l===null?e:t}var Sa=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;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(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??rA,this.headers={"Content-Type":"application/json","X-Persona-Version":us,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??iA(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,e.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(e.webmcp))}createWebMcpBridge(e){return gy().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Th,getToolDisplayTitle:ac,loadPolyfill:Ph});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),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(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.pendingWebMcpConfirmHandler=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(s=>s?s.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:e,flowId:n};let i=my(o,s);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||$y}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let s=n.conversationId,i=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!s||!i)throw new Oe("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),d=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":us,"X-Visitor-Token":i},signal:e.signal});if(d.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(d),null,!0);continue}if(!d.ok)throw await this.historyErrorFor(d,!0);return d}}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 e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.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 e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}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 e=this.historyIdentityStatus;return e?.state==="browser_only"?e: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(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&jy(n)===jy(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.historyIdentitySubscribers])s(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.routing(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,d={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}},u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":us},body:JSON.stringify(d)});if(!u.ok){let m=await u.json().catch(()=>({error:"Session initialization failed"}));if(n&&u.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),c)throw new Oe("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw u.status===403&&m.error==="durable_recovery_disabled"?new Oe("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&u.status===401&&m.error==="visitor_required"?new Oe("visitor_required","Visitor credential no longer resolves"):c&&u.status===404?new Oe("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 g=await u.json();return g.visitor?.token&&await this.historyInternals.visitorStore?.set(g.visitor.token),{sessionId:g.sessionId,expiresAt:new Date(g.expiresAt),flow:g.flow,...g.conversationId?{conversationId:g.conversationId}:{},...g.targetId?{targetId:g.targetId}:{},...g.conversationRevision?{conversationRevision:g.conversationRevision}:{},...g.durableRecovery?{durableRecovery:g.durableRecovery}:{},...g.visitor?{visitor:g.visitor}:{},config:{welcomeMessage:g.config.welcomeMessage,placeholder:g.config.placeholder,theme:g.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.createClientSession({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(s,e,!1)}catch(s){if(!fu(s,"not_found")&&!fu(s,"visitor_required")&&!fu(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.createClientSession({storedSessionId:o}),i=await this.claimFirstConversation(s);return this.finishInit(i,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.createClientSession({storedSessionId:n,identityProof:e}),i=this.finishInit(s,o,!1);return this.clientSession=i,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),i}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let s=e.conversationId;return s&&n&&(o||s!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:s}),this.config.setStoredSessionId?.(e.sessionId),s&&(this.config.setStoredConversationId?.(s),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Oe("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new Oe("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}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(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let s={...e,...this.config.clientToken&&{token:this.config.clientToken}},i=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":us},body:JSON.stringify(s)});if(!i.ok){let l=await i.json().catch(()=>({error:"Feedback submission failed"}));throw i.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[i,l]of Object.entries(n))l===void 0||l===""||o.set(i,String(l));let s=o.toString();return`${this.clientApiBase()}/v1/client/${e}${s?`?${s}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let s;try{s=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Oe("identity_provider_failed","The identity proof provider failed")}if(s)return s;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Oe("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let s=await this.reinitWithProof(n);if(!(s.visitor?.identityStatus==="admitted"&&s.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Oe("proof_not_admitted",Vy);return s}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let s=e.toLowerCase();if(s.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Oe("invalid_identity_proof",Ky);if(s.includes("visitor token required"))throw new Oe("visitor_token_missing",Gy);if(s.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Oe("visitor_identity_mismatch",Qy);return this.reinitWithProof(n)}if(s.includes("expired")||s.includes("not found"))return this.clearClientSession(),this.initSession();throw new Oe("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new Oe("not_found","Conversation not found");if(e.status===429){let s=Number.parseInt(e.headers.get("Retry-After")??"",10);return new Oe("rate_limited","Too many history requests",{...Number.isFinite(s)?{retryAfterSeconds:s}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Oe("proof_not_admitted",Vy);if(e.status===401){let s=o.toLowerCase();return s.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Oe("invalid_identity_proof",Ky)):s.includes("visitor token required")?new Oe("visitor_token_missing",Gy):s.includes("visitor_identity_mismatch")?new Oe("visitor_identity_mismatch",Qy):new Oe("unauthorized",o||"History request was not authorized")}return new Oe("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let s=e?.toLowerCase()??null;if(n){if(s==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),s==="ignored"?new Oe("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Oe("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(s==="admitted")throw new Oe("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,s=await this.initSession(),i=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(i=await this.resolveIdentityProof(s,o),i&&(s=await this.bindIdentity(s,i,o)));let l=this.historyInternals.visitorStore,c=!1;for(;;){let d=l?.revision()??0,u=await this.readVisitorToken();if(!u&&!n.visitorTokenOptional)throw new Oe("visitor_token_missing","No visitor credential is stored for this browser");let g=await fetch(this.historyUrl(e,{...n.query,sessionId:s.sessionId}),{method:n.method,headers:{"X-Persona-Version":us,...u?{"X-Visitor-Token":u}:{},...i?{"X-Identity-Proof":i}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(g.status===401&&!c){c=!0,s=await this.recoverFromUnauthorized(await this.readErrorCode(g),i,o);continue}if(!g.ok)throw await this.historyErrorFor(g,o);let m=g.headers.get("X-History-Identity-Status"),b=await g.json().catch(()=>{});if(l&&l.revision()!==d)throw new Oe("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,i!==null,o),b}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Oe("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(zy),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:zy(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let d of n){let u=d.displayContent.length;if(u>qy)throw new Oe("payload_too_large",`displayContent exceeds the ${qy} character limit`);o+=u}if(o>gu)throw new Oe("payload_too_large",`Display projection batch exceeds the ${gu} character limit`);await this.initSession();let s=this.historyInternals.visitorStore,i=s?.revision()??0,l=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=gu,trackIdentity:!1}),c=typeof l?.conversationRevision=="string"?l.conversationRevision:null;return c&&this.clientSession?.conversationId===e&&(s?.revision()??0)===i&&this.historyInternals.setStoredConversationRevision?.(c),{conversationRevision:c}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.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(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){let o=hy();this.currentClientTurnId=o;let s=()=>this.currentClientTurnId===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=await this.initSession();if(new Date>=new Date(l.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let x=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:x}),x}let c=await this.buildPayload(e.messages),d=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null,u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,g=this.isHistoryCapable(),m={sessionId:l.sessionId,messages:e.messages.filter(mu).map(x=>{let T=g?Ca(x):void 0;return{id:x.id,role:x.role,content:x.contentParts??x.llmContent??x.rawContent??x.content,...T!==void 0&&{displayContent:T}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},{response:b,commit:h}=await this.sendWithClientToolsDiff(l.sessionId,c.clientTools,x=>{let T={...m,...x};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",T),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":us,...d?{"X-Visitor-Token":d}:{}},body:JSON.stringify(T),signal:e.signal})});if(!b.ok){let x=await b.json().catch(()=>({error:"Chat request failed"}));if(b.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let M=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:M}),M}if(b.status===429){let M=new Error(x.hint||"Message limit reached for this session.");throw i({type:"error",error:M}),M}if(b.status===410&&x.error==="conversation_deleted"){let M=new Oe("conversation_deleted","This conversation was deleted");throw i({type:"error",error:M}),M}let T=new Error(x.error||"Failed to send message");throw i({type:"error",error:T}),T}if(!b.body){let x=new Error("No response body received");throw i({type:"error",error:x}),x}h(),i({type:"status",status:"connected"});try{await this.streamResponse(b.body,i,e.assistantMessageId)}finally{i({type:"status",status:"idle"})}}catch(l){let c=l instanceof Error?l:new Error(String(l));throw!(c instanceof Oe)&&!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&i({type:"error",error:c}),c}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,s){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,s){let i=!!(n&&n.length>0),l=i?kh(n):void 0,c=this.clientToolsFingerprintSessionId===e,d=i&&c&&this.lastSentClientToolsFingerprint===l,u=!i&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,g=!1,m;for(let b=0;;b++){if(m=await o({...i&&(g||!d)&&n?{clientTools:n}:{},...u?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),m.status===409&&b===0&&i&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.sentNonEmptyClientToolsSessionId=e:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let s=this.isClientTokenMode(),i=s?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||$y}/resume`,l,c=null;if(s){let g=await this.initSession();l=g.sessionId,g.durableRecovery?.enabled===!0&&(c=await this.readVisitorToken())}let d={"Content-Type":"application/json",...c?{"X-Visitor-Token":c}:{},...this.headers};this.getHeaders&&Object.assign(d,await this.getHeaders());let u={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(l&&(u.sessionId=l),s&&l){let g=[...Sc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:b}=await this.sendWithClientToolsDiff(l,g,h=>{let x={...u,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",x),fetch(i,{method:"POST",headers:d,body:JSON.stringify(x),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&b(),m}return fetch(i,{method:"POST",headers:d,body:JSON.stringify(u),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(i=>i.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=e.slice().filter(mu).filter(u=>u.role==="user"||u.role==="assistant"||u.role==="system").filter(u=>!u.variant||u.variant==="assistant").sort((u,g)=>{let m=new Date(u.createdAt).getTime(),b=new Date(g.createdAt).getTime();return m-b}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),i=this.normalizeComposerOptions(n),l={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},i),messages:s,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};i&&(l.composerOptions=i);let c=[...Sc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let d=await this.buildContextAggregate(e);return d&&(l.context=d),l}async buildPayload(e,n){let o=e.slice().filter(mu).sort((u,g)=>{let m=new Date(u.createdAt).getTime(),b=new Date(g.createdAt).getTime();return m-b}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),s=this.routing(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[u,g]of Object.entries(s.targetPayload))u!=="messages"&&(i[u]=g);let l=[...Sc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.buildContextAggregate(e);c&&(i.context=c);let d=this.normalizeComposerOptions(n);if(d&&(i.composerOptions=d),this.requestMiddleware)try{let u=await this.requestMiddleware({payload:{...i},config:this.config});if(u&&typeof u=="object"){let g=u;return i.clientTools!==void 0&&!("clientTools"in g)&&(g.clientTools=i.clientTools),g}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",u)}return i}async handleCustomSSEEvent(e,n,o,s,i,l){if(!this.parseSSEEvent)return!1;try{let c=await this.parseSSEEvent(e);if(c===null)return!1;let d=g=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:i(),...g!==void 0&&{partId:g}};return o.current=m,s(m),m},u=g=>o.current?o.current:d(g);if(c.text!==void 0){c.partId!==void 0&&l.current!==null&&c.partId!==l.current&&(o.current&&(o.current.streaming=!1,s(o.current)),d(c.partId)),c.partId!==void 0&&(l.current=c.partId);let g=u(c.partId);c.partId!==void 0&&!g.partId&&(g.partId=c.partId),g.content+=c.text,s(g)}return c.done&&(o.current&&(o.current.streaming=!1,s(o.current)),l.current=null,n({type:"status",status:"idle"})),c.error&&(l.current=null,n({type:"error",error:new Error(c.error)})),!0}catch(c){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",c),!1}}async streamResponse(e,n,o,s){let i=e.getReader(),l=new TextDecoder,c="",d=Date.now(),u=0,g=()=>d+u++,m=j=>{let C=j.reasoning?{...j.reasoning,chunks:[...j.reasoning.chunks]}:void 0,_=j.toolCall?{...j.toolCall,chunks:j.toolCall.chunks?[...j.toolCall.chunks]:void 0}:void 0,V=j.tools?j.tools.map(Q=>({...Q,chunks:Q.chunks?[...Q.chunks]:void 0})):void 0;return{...j,reasoning:C,toolCall:_,tools:V}},b=j=>{if(j.role!=="assistant"||j.variant)return!0;let C=Array.isArray(j.contentParts)&&j.contentParts.length>0,_=typeof j.rawContent=="string"&&j.rawContent.trim()!=="";return typeof j.content=="string"&&j.content.trim()!==""||C||_||!!j.stopReason},h=j=>{b(j)&&n({type:"message",message:m(j)})},x=null,T=null,M={current:null},O={current:null},I=null,z="",A=new Map,H=new Map,w=new Map,D=new Map,K=new Map,ie=o,Z=!1,S=()=>{if(x)return x;let j,C="",_=I;return!Z&&ie?(j=ie,Z=!0,C=s??""):ie&&_?j=`${ie}_${_}`:j=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:j,role:"assistant",content:C,createdAt:new Date().toISOString(),streaming:!0,sequence:g()},h(x),x},W=j=>{let C=D.get(j);if(C)return C;let _={id:`reason-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:g(),reasoning:{id:j,status:"streaming",chunks:[]}};return D.set(j,_),h(_),_},R=new Set,L=new Map,J=new Set,U=new Map,ae=j=>{if(!j)return!1;let C=j.replace(/_+/g,"_").replace(/^_|_$/g,"");return C==="emit_artifact_markdown"||C==="emit_artifact_component"},re=j=>{let C=K.get(j);if(C)return C;let _={id:`tool-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:g(),toolCall:{id:j,status:"pending"}};return K.set(j,_),h(_),_},ue=j=>{if(typeof j=="number"&&Number.isFinite(j))return j;if(typeof j=="string"){let C=Number(j);if(!Number.isNaN(C)&&Number.isFinite(C))return C;let _=Date.parse(j);if(!Number.isNaN(_))return _}return Date.now()},Ee=j=>{if(typeof j=="string")return j;if(j==null)return"";try{return JSON.stringify(j)}catch{return String(j)}},he=new Map,ce=new Map,at=(j,C)=>{let _=Ee(C),V=ce.get(j.id),Q=aA(V,_);j.rawContent=Q;let ee=he.get(j.id),me=Ve=>{let $e=j.content??"";Ve.trim()!==""&&($e.trim().length===0||Ve.startsWith($e)||Ve.trimStart().startsWith($e.trim()))&&(j.content=Ve)},Me=()=>{if(ee){let Ve=ee.close?.();Ve instanceof Promise&&Ve.catch(()=>{})}he.delete(j.id),ce.delete(j.id),j.streaming=!1,h(j)};if(!ee){me(_),Me();return}let Pe=pa(Q);if(Pe!==null&&Pe.trim()!==""){me(Pe),Me();return}let Re=Ve=>{let $e=typeof Ve=="string"?Ve:Ve?.text??null;if($e!==null&&$e.trim()!=="")return $e;let gt=ee.getExtractedText();return gt!==null&>.trim()!==""?gt:_},ot;try{ot=ee.processChunk(Q)}catch{me(_),Me();return}if(ot instanceof Promise){ot.then(Ve=>{me(Re(Ve)),Me()}).catch(()=>{me(_),Me()});return}me(Re(ot)),Me()},ye=null,N=(j,C,_,V)=>{j.rawContent=C,he.has(j.id)||he.set(j.id,this.createStreamParser());let Q=he.get(j.id),ee=C.trim().startsWith("{")||C.trim().startsWith("[");if(ee&&ce.set(j.id,C),Q.__isPlainTextParser===!0){j.content=V!==void 0?C:j.content+_,ce.delete(j.id),he.delete(j.id),j.rawContent=void 0,h(j);return}let Me=Q.processChunk(C);if(Me instanceof Promise)Me.then(Pe=>{let Re=typeof Pe=="string"?Pe:Pe?.text??null;Re!==null&&Re.trim()!==""?(j.content=Re,h(j)):!ee&&!C.trim().startsWith("<")&&(j.content=V!==void 0?C:j.content+_,ce.delete(j.id),he.delete(j.id),j.rawContent=void 0,h(j))}).catch(()=>{j.content=V!==void 0?C:j.content+_,ce.delete(j.id),he.delete(j.id),j.rawContent=void 0,h(j)});else{let Pe=typeof Me=="string"?Me:Me?.text??null;Pe!==null&&Pe.trim()!==""?(j.content=Pe,h(j)):!ee&&!C.trim().startsWith("<")&&(j.content=V!==void 0?C:j.content+_,ce.delete(j.id),he.delete(j.id),j.rawContent=void 0,h(j))}},Te=(j,C)=>{let _=C??j.content;if(_==null||_===""){j.streaming=!1,h(j);return}let Q=ce.get(j.id)??Ee(_);j.rawContent=Q;let ee=he.get(j.id),me=null,Me=!1;if(ee&&(me=ee.getExtractedText(),me===null&&(me=pa(Q)),me===null)){let Pe=ee.processChunk(Q);Pe instanceof Promise?(Me=!0,Pe.then(Re=>{let ot=typeof Re=="string"?Re:Re?.text??null;ot!==null&&(j.content=ot,j.streaming=!1,he.delete(j.id),ce.delete(j.id),h(j))}).catch(()=>{})):me=typeof Pe=="string"?Pe:Pe?.text??null}if(!Me){me!==null&&me.trim()!==""?j.content=me:ce.has(j.id)||(j.content=Ee(_));let Pe=he.get(j.id);if(Pe){let Re=Pe.close?.();Re instanceof Promise&&Re.catch(()=>{}),he.delete(j.id)}ce.delete(j.id),j.streaming=!1,h(j)}},Ue=(j,C,_)=>{let V=H.get(j);if(V)return V;let Q={id:`nested-${C}-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g(),..._?{variant:_}:{},..._==="reasoning"?{reasoning:{id:j,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:C}};return H.set(j,Q),h(Q),Q},qt=[],Le,Fe=new Map,ve=0,ln="agent",Jn=!1,ko=null,vt=null,Po=this.config.iterationDisplay??"separate";for(Le=()=>{for(let j=0;j<qt.length;j++){let C=qt[j];if(!Jn&&ln!=="flow"&&typeof C.stepType=="string"&&(ln="flow"),C.type==="reasoning_start"){let _=typeof C.id=="string"?C.id:null,V=typeof C.parentToolCallId=="string"&&C.parentToolCallId?C.parentToolCallId:null;if(_&&V){A.set(_,V),Ue(_,V,"reasoning");continue}let Q=C.id,ee=W(Q);ee.reasoning=ee.reasoning??{id:Q,status:"streaming",chunks:[]},ee.reasoning.startedAt=ee.reasoning.startedAt??Date.now(),ee.reasoning.completedAt=void 0,ee.reasoning.durationMs=void 0,(C.scope==="loop"||C.scope==="turn")&&(ee.reasoning.scope=C.scope),ee.streaming=!0,ee.reasoning.status="streaming",h(ee)}else if(C.type==="reasoning_delta"){let _=typeof C.id=="string"?C.id:null;if(_&&A.has(_)&&H.has(_)){let ee=H.get(_),me=C.delta;me&&ee.reasoning&&(ee.reasoning.chunks.push(String(me)),h(ee));continue}let V=C.id,Q=W(V);Q.reasoning=Q.reasoning??{id:V,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??Date.now(),C.delta&&Q.reasoning.chunks.push(C.delta),Q.reasoning.status="streaming",Q.streaming=!0,h(Q)}else if(C.type==="reasoning_complete"){let _=typeof C.id=="string"?C.id:null;if(_&&A.has(_)&&H.has(_)){let me=H.get(_);if(me.reasoning){let Me=typeof C.text=="string"?C.text:"";Me&&me.reasoning.chunks.length===0&&me.reasoning.chunks.push(Me),me.reasoning.status="complete",me.streaming=!1,h(me)}A.delete(_),H.delete(_);continue}let V=C.id,Q=typeof C.text=="string"?C.text:"";!D.get(V)&&(Q||C.scope==="loop")&&W(V);let ee=D.get(V);if(ee?.reasoning){(C.scope==="loop"||C.scope==="turn")&&(ee.reasoning.scope=C.scope),Q&&ee.reasoning.chunks.length===0&&ee.reasoning.chunks.push(Q),ee.reasoning.status="complete",ee.reasoning.completedAt=Date.now();let me=ee.reasoning.startedAt??Date.now();ee.reasoning.durationMs=Math.max(0,(ee.reasoning.completedAt??Date.now())-me),ee.streaming=!1,h(ee)}}else if(C.type==="tool_start"){x&&(x.streaming=!1,h(x),x=null),typeof C.iteration=="number"&&(ve=C.iteration);let _=C.toolCallId,V=C.toolName;if(ae(V)){R.add(_);continue}let Q=re(_),ee=Q.toolCall??{id:_,status:"pending"};ee.name=V??ee.name,ee.status="running",ee.success=void 0,ee.error=void 0,ee.duration=void 0,C.parameters!==void 0&&(ee.args=C.parameters),ee.startedAt=ee.startedAt??ue(C.startedAt),ee.completedAt=void 0,ee.durationMs=void 0,Q.toolCall=ee,Q.streaming=!0,C.executionId&&(Q.agentMetadata={executionId:C.executionId,iteration:C.iteration}),h(Q)}else if(C.type==="tool_output_delta"){let _=C.toolCallId;if(R.has(_))continue;let V=re(_),Q=V.toolCall??{id:_,status:"running"};Q.startedAt=Q.startedAt??Date.now();let ee=C.delta;ee&&(Q.chunks=Q.chunks??[],Q.chunks.push(String(ee))),Q.status="running",V.toolCall=Q,V.streaming=!0,C.executionId&&(V.agentMetadata=V.agentMetadata??{executionId:C.executionId,iteration:ve}),h(V)}else if(C.type==="tool_complete"){let _=C.toolCallId;if(R.has(_)){R.delete(_);continue}let V=re(_),Q=V.toolCall??{id:_,status:"running"};Q.status="complete",C.result!==void 0&&(Q.result=C.result),Q.name=C.toolName??Q.name,Q.success=C.success,Q.error=C.error,Q.completedAt=Date.now();let ee=C.executionTime;if(typeof ee=="number")Q.durationMs=ee,Q.duration=ee;else{let me=Q.startedAt??Date.now();Q.durationMs=Math.max(0,(Q.completedAt??Date.now())-me)}V.toolCall=Q,V.streaming=!1,C.executionId&&(V.agentMetadata=V.agentMetadata??{executionId:C.executionId,iteration:C.iteration??ve}),h(V)}else if(C.type==="await"&&C.toolName){let _=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,V=_??C.toolId??`local-${g()}`,Q=re(V),ee=C.toolName,me=C.origin==="webmcp"&&!Js(ee)?`webmcp:${ee}`:ee,Me=Js(me),Pe=Q.toolCall??{id:V,status:"pending"};Pe.name=me,Pe.args=C.parameters,Pe.status=Me?"running":"complete",Pe.chunks=Pe.chunks??[],Pe.startedAt=Pe.startedAt??ue(C.awaitedAt),Me?(Pe.completedAt=void 0,Pe.duration=void 0,Pe.durationMs=void 0):Pe.completedAt=Pe.completedAt??Pe.startedAt,Q.toolCall=Pe,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:C.executionId??Q.agentMetadata?.executionId,awaitingLocalTool:!0,..._?{webMcpToolCallId:_}:{}},h(Q)}else if(C.type==="text_start"){let _=typeof C.id=="string"?C.id:null,V=typeof C.parentToolCallId=="string"&&C.parentToolCallId?C.parentToolCallId:null;if(_&&V){A.set(_,V);continue}let Q=x;Q&&(ln==="flow"?(Te(Q),ye=Q):(Q.streaming=!1,h(Q)),x=null),I=typeof C.id=="string"?C.id:I,z=""}else if(C.type==="text_delta"){let _=typeof C.id=="string"?C.id:null,V=_?A.get(_):void 0;if(_&&V){let me=typeof C.delta=="string"?C.delta:"",Me=(w.get(_)??"")+me;if(w.set(_,Me),Me.trim()==="")continue;let Pe=Ue(_,V);Pe.agentMetadata={...Pe.agentMetadata,executionId:C.executionId,parentToolId:V},N(Pe,Me,me,void 0);continue}if(I=typeof C.id=="string"?C.id:I,ln==="flow"){let me=typeof C.delta=="string"?C.delta:"";if(z+=me,z.trim()==="")continue;let Me=S();Me.agentMetadata={executionId:C.executionId,iteration:ve},N(Me,z,me,void 0),T=Me;continue}let Q=typeof C.delta=="string"?C.delta:"";z+=Q;let ee=S();ee.agentMetadata={executionId:C.executionId,iteration:ve,turnId:ko??void 0,agentName:vt?.agentName},N(ee,z,Q,void 0),T=ee}else if(C.type==="text_complete"){let _=typeof C.id=="string"?C.id:null;if(_&&A.has(_)){let Q=H.get(_);Q&&Te(Q),A.delete(_),w.delete(_),H.delete(_);continue}let V=x;V&&(ln==="flow"?(Te(V),ye=V):((V.content??"")===""&&typeof C.text=="string"&&(V.content=C.text),V.streaming=!1,h(V)),x=null),I=null,z=""}else if(C.type==="step_complete"){if(C.stepType==="tool")continue;if(C.success===!1){let _=C.error||"Step failed";n({type:"error",error:new Error(_)});let V=x;V&&V.streaming&&(V.streaming=!1,h(V)),n({type:"status",status:"idle"});continue}{let _=ye;ye=null;let V=C.stopReason,ee=(C.result&&typeof C.result=="object"?C.result:null)?.response;if(_)V&&(_.stopReason=V),ee!=null?at(_,ee):_.streaming!==!1&&(he.delete(_.id),ce.delete(_.id),_.streaming=!1,h(_));else{let me=ee!=null&&ee!=="";if(me||V){let Me=S();V&&(Me.stopReason=V),me?Te(Me,ee):(Me.streaming=!1,h(Me))}}continue}}else if(C.type==="execution_start")ln=C.kind==="flow"?"flow":"agent",Jn=!0,ln==="agent"&&(vt={executionId:C.executionId,agentId:C.agentId??"virtual",agentName:C.agentName??""});else if(C.type==="turn_start"){let _=typeof C.iteration=="number"?C.iteration:ve;if(_!==ve){if(Po==="separate"&&_>1){let V=x;V&&(V.streaming=!1,h(V),x=null)}ve=_}ko=typeof C.id=="string"?C.id:null,T=null}else if(C.type==="tool_input_delta"){let _=C.toolCallId;if(_){let V=K.get(_);V?.toolCall&&(V.toolCall.chunks=V.toolCall.chunks??[],V.toolCall.chunks.push(C.delta??""),h(V))}}else if(C.type==="tool_input_complete"){if(R.has(C.toolCallId))continue;let _=re(C.toolCallId),V=_.toolCall;V.args=C.parameters,V.name=C.toolName??V.name,h(_)}else if(C.type==="turn_complete"){let _=C.stopReason,V=x??T;if(_&&V!==null){let Q=C.id;(!Q||V.agentMetadata?.turnId===Q)&&(V.stopReason=_,h(V))}ko===C.id&&(ko=null)}else if(C.type==="media_start"){let _=String(C.id);Fe.set(_,{mediaType:typeof C.mediaType=="string"?C.mediaType:void 0,toolCallId:C.toolCallId,parts:[]})}else if(C.type==="media_delta"){let _=Fe.get(String(C.id));_&&typeof C.delta=="string"&&_.parts.push(C.delta)}else if(C.type==="media_complete"){let _=String(C.id),V=Fe.get(_);Fe.delete(_);let Q=(typeof C.mediaType=="string"?C.mediaType:void 0)??V?.mediaType??"application/octet-stream",ee=typeof C.data=="string"?C.data:void 0,me=typeof C.url=="string"?C.url:V&&V.parts.length>0?V.parts.join(""):void 0,Me=null;if(ee)Me={type:"media",data:ee,mediaType:Q};else if(me){let Ve=Q.toLowerCase();Me={type:Ve==="image"||Ve.startsWith("image/")?"image-url":"file-url",url:me,mediaType:Q}}let Pe=C.toolCallId??V?.toolCallId,Re=Me?[Me]:[],ot=[];for(let Ve of Re){if(!Ve||typeof Ve!="object")continue;let $e=Ve,gt=typeof $e.type=="string"?$e.type:void 0,zt=typeof $e.mediaType=="string"?$e.mediaType.toLowerCase():"",kt=null,tn="";if(gt==="media"){let hn=typeof $e.data=="string"?$e.data:void 0;if(!hn)continue;tn=zt.length>0?zt:"application/octet-stream",kt=`data:${tn};base64,${hn}`}else if(gt==="image-url"){let hn=typeof $e.url=="string"?$e.url:void 0;if(!hn)continue;tn=zt,kt=hn}else if(gt==="file-url"){let hn=typeof $e.url=="string"?$e.url:void 0;if(!hn)continue;tn=zt,kt=hn}else continue;if(kt)if(gt==="image-url"||tn.startsWith("image/"))ot.push({type:"image",image:kt,...tn.includes("/")?{mimeType:tn}:{}});else if(tn.startsWith("audio/"))ot.push({type:"audio",audio:kt,mimeType:tn});else if(tn.startsWith("video/"))ot.push({type:"video",video:kt,mimeType:tn});else{let hn=tn||"application/octet-stream";ot.push({type:"file",data:kt,mimeType:hn,filename:sA(hn)})}}if(ot.length>0){let Ve=g(),$e=Pe,zt={id:`agent-media-${typeof $e=="string"&&$e.length>0?`${$e}-${Ve}`:String(Ve)}`,role:"assistant",content:"",contentParts:ot,createdAt:new Date().toISOString(),streaming:!1,sequence:Ve,agentMetadata:{executionId:C.executionId,iteration:ve}};h(zt);let kt=x;kt&&(kt.streaming=!1,h(kt)),x=null,M.current=null}}else if(C.type==="execution_complete"){let _=x;_&&(C.kind==="flow"&&_.streaming!==!1?Te(_):(_.streaming=!1,h(_)),x=null),I=null,z="",ye=null,n({type:"status",status:"idle",terminal:!0})}else if(C.type==="execution_error"){let _=typeof C.error=="string"?C.error:C.error?.message??"Execution error";n({type:"error",error:new Error(_)})}else if(C.type!=="ping"){if(C.type==="approval_start"){let _=C.approvalId??`approval-${g()}`,V={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:g(),approval:{id:_,status:"pending",agentId:vt?.agentId??"virtual",executionId:C.executionId??vt?.executionId??"",toolName:C.toolName??"",toolType:C.toolType,description:C.description??`Execute ${C.toolName??"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};h(V)}else if(C.type==="approval_complete"){let _=C.approvalId;if(_){let Q={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:g(),approval:{id:_,status:C.decision??"approved",agentId:vt?.agentId??"virtual",executionId:C.executionId??vt?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(Q)}}else if(C.type==="artifact_start"||C.type==="artifact_delta"||C.type==="artifact_update"||C.type==="artifact_complete"){if(C.type==="artifact_start"){let _=C.artifactType,V=String(C.id),Q=typeof C.title=="string"?C.title:void 0,ee=C.file,me;if(ee&&typeof ee=="object"&&!Array.isArray(ee)&&typeof ee.path=="string"&&typeof ee.mimeType=="string"&&(me={path:ee.path,mimeType:ee.mimeType,...typeof ee.language=="string"?{language:ee.language}:{}}),n({type:"artifact_start",id:V,artifactType:_,title:Q,component:typeof C.component=="string"?C.component:void 0,...me?{file:me}:{}}),U.set(V,{markdown:"",title:Q,file:me}),!J.has(V)){J.add(V);let Me=Sr(this.config.features?.artifacts,{artifactType:_,...me?{file:me}:{}}),Pe=typeof C.component=="string"?C.component:void 0,Re={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g(),rawContent:ha(Me,{artifactId:V,title:Q,artifactType:_,status:"streaming",...me?{file:me}:{},...Pe?{component:Pe}:{}})};L.set(V,Re),h(Re)}}else if(C.type==="artifact_delta"){let _=String(C.id),V=typeof C.delta=="string"?C.delta:String(C.delta??"");n({type:"artifact_delta",id:_,artDelta:V});let Q=U.get(_);Q&&(Q.markdown+=V)}else if(C.type==="artifact_update"){let _=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:_,component:typeof C.component=="string"?C.component:void 0});let V=U.get(String(C.id));V&&(V.props={...V.props??{},..._})}else if(C.type==="artifact_complete"){let _=String(C.id);n({type:"artifact_complete",id:_});let V=L.get(_);if(V){V.streaming=!1;try{let Q=JSON.parse(V.rawContent??"{}");if(Q.props){Q.props.status="complete";let ee=U.get(_);ee?.markdown&&(Q.props.markdown=ee.markdown),ee?.file&&(Q.props.file=ee.file),Q.component==="PersonaArtifactInline"&&ee?.props&&Object.keys(ee.props).length>0&&(Q.props.componentProps=ee.props)}V.rawContent=JSON.stringify(Q)}catch{}U.delete(_),h(V),L.delete(_)}}}else if(C.type==="error"&&C.recoverable===!1&&C.error!=null&&C.error!==""){let _=typeof C.error=="string"?C.error:C.error?.message!=null?String(C.error.message):"Execution error";n({type:"error",error:new Error(_)});let V=x;V&&V.streaming&&(V.streaming=!1,h(V)),n({type:"status",status:"idle"})}}}qt.length=0};;){let{done:j,value:C}=await i.read();if(j)break;c+=l.decode(C,{stream:!0});let _=c.split(`
|
|
3
|
+
`):t};var cy="var(--persona-md-table-scroll-fade, 24px)",dy=new WeakSet;function uy(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let s=document.createElement("div");s.className="persona-table-scroll",n.replaceWith(s),s.appendChild(n)})}function py(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,s=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":cy),t.style.setProperty("--persona-fade-r",s<=1?"0px":cy)}function su(t){dy.has(t)||(dy.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&py(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(py)}var{setLoader:ok,load:fx}=Tt({fallbackImport:()=>import("./webmcp-runtime-JI7T4QYF.js")});var gy=fx;function Xn(t){return t==="card"?"collapsed":t}function ei(t){return t.split(";",1)[0].trim().toLowerCase()}function mx(t,e){if(!t)return;let n=Object.entries(t);for(let[s,i]of n)if(ei(s)===e)return{mode:Xn(i),selector:ei(s)};let o=`${e.split("/",1)[0]}/*`;for(let[s,i]of n)if(ei(s)===o)return{mode:Xn(i),selector:o}}function hx(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:Xn(o.files),matchedBy:{type:"files"}};let c=e.file.mimeType?ei(e.file.mimeType):void 0,d=c?mx(o.files.byMediaType,c):void 0;if(c&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:c,selector:d.selector}};if(o.files.default)return{mode:Xn(o.files.default),matchedBy:{type:"files"}}}let s=o.byKind?.[e.artifactType];if(s)return{mode:Xn(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let i=o.byType?.[e.artifactType];if(i)return{mode:Xn(i),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let l=e.presentation?.preferredMode;return l?{mode:Xn(l),matchedBy:{type:"preferredMode"}}:o.default?{mode:Xn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Sr(t,e){return hx(t,e).mode}function ha(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var yx="agent_",bx="flow_";function fy(t){return t.startsWith(yx)?{kind:"agentId",agentId:t}:t.startsWith(bx)?{kind:"flowId",flowId:t}:null}function my(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let l=n.slice(0,o),c=n.slice(o+1);if(l==="runtype"){let u=fy(c);if(u)return u;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let d=e?.[l];if(!d)throw new Error(`[Persona] No target provider registered for "${l}". Add a \`targetProviders.${l}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(c).payload}}let s=fy(n);if(s)return s;let i=e?.default;if(i)return{kind:"payload",payload:i(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function bc(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ti(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function hy(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}import{parse as vx,ARR as Cx,OBJ as wx,STR as Sx}from"partial-json";var iu="ask_user_question",ya=8,ni="data-persona-ask-sheet-for",xx="Other",Ax="Other\u2026",by="Type your own answer here",vy="Send",Mx="Next",Ex="Back",Tx="Submit all",kx="Skip",Px=3,au="data-ask-current-index",lu="data-ask-question-count",Cy="data-ask-answers",cu="data-ask-grouped",wy="data-ask-layout",Ix=t=>t.layout==="pills"?"pills":"rows",Lx=t=>t.getAttribute(wy)==="pills"?"pills":"rows",yy=!1,Sy=t=>t.replace(/["\\]/g,"\\$&"),ds=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===iu,du=t=>t?.features?.askUserQuestion??{},oi=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let s=o.join(""),i=vx(s,Sx|wx|Cx);if(i&&typeof i=="object")return{payload:i,complete:n}}catch{}return{payload:null,complete:n}},ba=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>ya&&!yy&&(yy=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${ya}.`)),e.slice(0,ya)},Hx=t=>ba(t)[0]??null,Rx=(t,e)=>ba(t)[e]??null,Wx=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},xy=(t,e,n)=>{if(t!=="rows")return null;let o=k("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let s=k("span","persona-ask-row-check");o.appendChild(s)}else{let s=k("span","persona-ask-row-badge");s.textContent=String(n+1),o.appendChild(s)}return o},Bx=(t,e,n,o)=>{let i=k("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(i.type="button",i.setAttribute("role",o?"checkbox":"button"),i.setAttribute("aria-pressed","false"),i.setAttribute("data-ask-user-action","pick"),i.setAttribute("data-option-index",String(e)),i.setAttribute("data-option-label",t.label),n==="rows"){let l=k("span","persona-ask-row-content"),c=k("span","persona-ask-row-label");if(c.textContent=t.label,l.appendChild(c),t.description){let u=k("span","persona-ask-row-description");u.textContent=t.description,l.appendChild(u)}i.appendChild(l);let d=xy(n,o,e);d&&i.appendChild(d)}else i.textContent=t.label,t.description&&(i.title=t.description);return i},Dx=t=>{let n=k("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Ox=(t,e,n,o)=>{let i=k("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");i.setAttribute("role","group"),i.setAttribute("data-ask-pill-list","true");let l=!!t?.multiSelect,d=(Array.isArray(t?.options)?t.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<Px;g++)i.appendChild(Dx(o));return i}if(d.forEach((g,m)=>{i.appendChild(Bx(g,m,o,l))}),t?.allowFreeText!==!1){let g=o==="rows"?xx:Ax;if(o==="rows"){let m=k("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(d.length)),m.setAttribute("data-ask-other-row","true");let v=k("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=e.freeTextPlaceholder??by,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",e.freeTextLabel??g),v.appendChild(h),m.appendChild(v);let T=xy(o,l,d.length);T&&m.appendChild(T),i.appendChild(m)}else{let m=k("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=e.freeTextLabel??g,i.appendChild(m)}}return i},Ay=(t,e)=>{let o=k("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=t.freeTextPlaceholder??by,s.setAttribute("data-ask-free-text-input","true"),o.appendChild(s),e!=="rows"){let i=k("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=t.submitLabel??vy,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},_x=t=>{let e=k("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=k("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??vy,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},Nx=(t,e,n)=>{let o=k("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let s=k("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=n.backLabel??Ex,s.setAttribute("data-ask-user-action","back"),s.disabled=t===0,o.appendChild(s);let i=k("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),l=k("button","persona-ask-nav-skip persona-pointer-events-auto");l.type="button",l.textContent=n.skipLabel??kx,l.setAttribute("data-ask-user-action","skip"),i.appendChild(l);let c=k("button","persona-ask-nav-next persona-pointer-events-auto");c.type="button";let d=t===e-1;return c.textContent=d?n.submitAllLabel??Tx:n.nextLabel??Mx,c.setAttribute("data-ask-user-action",d?"submit-all":"next"),c.disabled=!0,i.appendChild(c),o.appendChild(i),o},ps=t=>{let e=t.getAttribute(Cy);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},My=(t,e)=>{t.setAttribute(Cy,JSON.stringify(e))},Yn=t=>{let e=Number(t.getAttribute(au)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Fx=(t,e)=>{t.setAttribute(au,String(Math.max(0,Math.floor(e))))},ri=t=>{let e=Number(t.getAttribute(lu)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},xr=t=>t.getAttribute(cu)==="true",Ux=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((s,i)=>{let l=typeof s?.question=="string"?s.question:"";if(l&&Object.prototype.hasOwnProperty.call(n,l)){let c=n[l];(typeof c=="string"||Array.isArray(c))&&(o[i]=c)}}),o},$x=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},vc=(t,e)=>{let{payload:n}=oi(e),o=ba(n),s=ps(t),i={},l=new Set;return o.forEach((c,d)=>{let u=typeof c?.question=="string"?c.question:"";u&&(l.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),l.add(u),Object.prototype.hasOwnProperty.call(s,d)&&(i[u]=s[d]))}),i},Ey=t=>{let e=ps(t),n=Yn(t),o=e[n],s=new Set;typeof o=="string"?s.add(o):Array.isArray(o)&&o.forEach(d=>s.add(d));let i=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');i.forEach(d=>{let u=d.getAttribute("data-option-label")??"",g=s.has(u);d.setAttribute("aria-pressed",g?"true":"false"),d.classList.toggle("persona-ask-pill-selected",g)});let l=new Set(Array.from(i).map(d=>d.getAttribute("data-option-label")??"")),c=t.querySelector('[data-ask-free-text-input="true"]');c&&(typeof o=="string"&&o.length>0&&!l.has(o)?(c.value=o,c.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):c.value="")},Ty=t=>{if(!xr(t))return;let e=ps(t),n=Yn(t),o=e[n],s=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,i=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');i&&(i.disabled=!s);let l=t.querySelector('[data-ask-user-action="submit-multi"]');if(l){let c=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));l.disabled=c.length===0}},pu=(t,e,n)=>{let o=du(n),s=Lx(t),{payload:i,complete:l}=oi(e),c=xr(t),d=Yn(t),u=ri(t),g=c?Rx(i,d):Hx(i),m=!!g?.multiSelect,v=t.querySelector('[data-ask-step-inline="true"]');v&&(v.textContent=c?`${d+1}/${u}`:"");let h=t.querySelector('[data-ask-stepper="true"]');h&&h.remove();let T=t.querySelector('[data-ask-question="true"]');if(T){let P=typeof g?.question=="string"?g.question:"";T.textContent=P,T.classList.toggle("persona-ask-question-skeleton",!P&&!l)}let M=t.querySelector('[data-ask-pill-list="true"]');if(M){let P=Ox(g,o,l,s);M.replaceWith(P)}if(s!=="rows"){let P=t.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Ay(o,s))}let E=t.querySelector('[data-ask-multi-actions="true"]');!c&&m&&!E?t.appendChild(_x(o)):(!m||c)&&E&&E.remove(),t.setAttribute("data-multi-select",m?"true":"false");let I=t.querySelector('[data-ask-nav-row="true"]');if(c){let P=Nx(d,u,o);I?I.replaceWith(P):t.appendChild(P)}else I&&I.remove();Ey(t),Ty(t)},qx=(t,e,n)=>{let o=du(e),s=Ix(o),i=t.toolCall.id,l=ba(n),c=Math.max(1,l.length),d=c>1,u=Ux(t,l),g=d?$x(t,c):0,m=k("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(ni,i),m.setAttribute("data-tool-call-id",i),m.setAttribute("data-message-id",t.id),m.setAttribute(lu,String(c)),m.setAttribute(au,String(g)),m.setAttribute(cu,d?"true":"false"),m.setAttribute(wy,s),My(m,u),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Wx(m,o);let v=k("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=k("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",v.appendChild(h);let T=k("span","persona-ask-sheet-step-inline");T.setAttribute("data-ask-step-inline","true"),T.textContent="",v.appendChild(T),m.appendChild(v);let E=k("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),m.appendChild(E),s!=="rows"&&m.appendChild(Ay(o,s)),pu(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},zx=(t,e,n)=>{let{payload:o}=oi(e),s=Math.max(1,ba(o).length);s>ri(t)&&(t.setAttribute(lu,String(s)),s>1&&!xr(t)&&t.setAttribute(cu,"true")),pu(t,e,n)};var Cc=(t,e,n)=>{if(!n||!ds(t)||du(e).enabled===!1)return;let s=t.toolCall.id;n.querySelectorAll(`[${ni}]`).forEach(u=>{u.getAttribute(ni)!==s&&u.remove()});let l=n.querySelector(`[${ni}="${Sy(s)}"]`);if(l){zx(l,t,e);return}let{payload:c}=oi(t),d=qx(t,e,c);n.appendChild(d)},si=(t,e)=>{if(!t)return;let n=e?`[${ni}="${Sy(e)}"]`:`[${ni}]`;t.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let i=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(i)?i:180)})},uu=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),Ar=(t,e)=>{let n=ps(t),o=Yn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,My(t,n),Ey(t),Ty(t)},wc=(t,e,n,o)=>{let s=ri(t),i=Math.max(0,Math.min(s-1,o));Fx(t,i),pu(t,e,n)};var Mr="suggest_replies";var jx={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},Py={name:Mr,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:jx,origin:"sdk",annotations:{readOnlyHint:!0}},Iy=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),va=t=>t.variant==="tool"&&t.toolCall?.name===Mr,Vx=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(s=>{if(typeof s=="string"){let c=s.trim();return c?[c]:[]}if(!s||typeof s!="object")return[];let i=s;if(typeof i.label!="string"||!i.label.trim())return[];let l={label:i.label.trim()};return typeof i.prompt=="string"&&i.prompt.trim()&&(l.prompt=i.prompt.trim()),typeof i.description=="string"&&i.description.trim()&&(l.description=i.description.trim()),[l]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Ly=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!va(n))continue;let o=Vx(n.toolCall?.args);return o.length>0?o:null}return null},ky=new Set,Kx=(t,e,n)=>{let o=`${t}:${e}:${n}`;ky.has(o)||(ky.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Er=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=l=>{let c=e?.[l],d=n?.[l];c===void 0||d===void 0||c!==d&&Kx(l,d,c)};t&&(o("enabled"),o("expose"));let s=e?.enabled??n?.enabled??!0,i=s?e?.expose??n?.expose??!1:!1;return{enabled:s,expose:i}};var Gx={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ya,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},Qx={name:iu,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:Gx,origin:"sdk",annotations:{readOnlyHint:!0}},Sc=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(Qx),Er(t).expose&&e.push(Py),e};var Hy="4.23.1";var us=Hy;var ii="[Image]";function Ry(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function xc(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Mo(t){return{type:"text",text:t}}function Wy(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var By=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Yx=["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"],Yo=[...By,...Yx];function Jx(t){return By.includes(t)||t.startsWith("image/")}function Ac(t){return Jx(t.type)}function Dy(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function Oy(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;Ac(t)?e({type:"image",image:s,mimeType:t.type,alt:t.name}):e({type:"file",data:s,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function _y(t,e=Yo,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function Zx(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Ny(t,e){let n=Zx(e).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"}[t]||n||"FILE"}var eA=["user","assistant","system"],tA=0;function Fy(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function Mc(t){return typeof t=="string"?t:void 0}function nA(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?Mo(e.text):null;case"image":return typeof e.image=="string"?Wy(e.image,{mimeType:Mc(e.mimeType),alt:Mc(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?Dy(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...Mc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...Mc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function oA(t,e){let n=Fy(e),o=t.map(l=>Fy(l.timestamp)),s=new Array(t.length),i=0;for(;i<o.length;){let l=o[i];if(l!==null){s[i]=l,i+=1;continue}let c=i;for(;c+1<o.length&&o[c+1]===null;)c+=1;let d=c-i+1,u=i>0?s[i-1]:null,g=c+1<o.length?o[c+1]:null,m=g!==null&&n!==null?Math.min(g,n):g??n;for(let v=0;v<d;v+=1)s[i+v]=m!==null?m-(d-v):u!==null?u+v+1:tA+v;i=c+1}return s.map(l=>new Date(l).toISOString())}function Uy(t,e){let n=oA(t,e?.beforeCreatedAt),o=[];return t.forEach((s,i)=>{if(typeof s?.id!="string"||s.id===""||!eA.includes(s.role))return;let l=s.role,c=n[i];if(s.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:s.id,role:l,content:"",createdAt:c,agentMetadata:d});return}if(typeof s.displayContent=="string"){o.push({id:s.id,role:l,content:s.displayContent,createdAt:c});return}if(typeof s.content=="string"){o.push({id:s.id,role:l,content:s.content,createdAt:c});return}if(Array.isArray(s.content)){let d=s.content.map(nA).filter(g=>g!==null),u=Ry(d);o.push({id:s.id,role:l,content:u||(xc(d)?ii:""),createdAt:c,...d.length>0&&{contentParts:d}});return}o.push({id:s.id,role:l,content:"",createdAt:c})}),o}function Ca(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function wa(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,s)=>{let i=new Date(o.createdAt).getTime(),l=new Date(s.createdAt).getTime();if(!Number.isNaN(i)&&!Number.isNaN(l)&&i!==l)return i-l;let c=o.sequence??0,d=s.sequence??0;return c!==d?c-d:o.id.localeCompare(s.id)})}var rA="https://api.runtype.com/v1/dispatch",$y="https://api.runtype.com",Oe=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},qy=32768,gu=49152,zy=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},jy=t=>"reason"in t?t.reason:void 0,Vy="The identity proof was not admitted; account history is unavailable",Ky="The identity proof was rejected",Gy="The request carried no visitor credential",Qy="The stored visitor belongs to a different signed-in user",fu=(t,e)=>t instanceof Oe&&t.code===e;function sA(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let s=e.indexOf("/");if(s>0){let i=e.slice(s+1).split(";")[0]?.trim()??"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var mu=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function iA(t){switch(t){case"json":return Dh;case"regex-json":return Bh;case"xml":return Oh;default:return Wh}}var Xy=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function aA(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let s=Xy(n);if(!Xy(o))return t;if(!s||o===n||o.startsWith(n))return e;let l=pa(t);return pa(e)!==null&&l===null?e:t}var Sa=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;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(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??rA,this.headers={"Content-Type":"application/json","X-Persona-Version":us,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??iA(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,e.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(e.webmcp))}createWebMcpBridge(e){return gy().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Th,getToolDisplayTitle:ac,loadPolyfill:Ph});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),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(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.pendingWebMcpConfirmHandler=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(s=>s?s.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:e,flowId:n};let i=my(o,s);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||$y}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let s=n.conversationId,i=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!s||!i)throw new Oe("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),d=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":us,"X-Visitor-Token":i},signal:e.signal});if(d.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(d),null,!0);continue}if(!d.ok)throw await this.historyErrorFor(d,!0);return d}}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 e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.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 e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}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 e=this.historyIdentityStatus;return e?.state==="browser_only"?e: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(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&jy(n)===jy(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.historyIdentitySubscribers])s(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.routing(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,d={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":us},body:JSON.stringify(d),signal:e.signal});if(!u.ok){let m=await u.json().catch(()=>({error:"Session initialization failed"}));if(n&&u.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),c)throw new Oe("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw u.status===403&&m.error==="durable_recovery_disabled"?new Oe("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&u.status===401&&m.error==="visitor_required"?new Oe("visitor_required","Visitor credential no longer resolves"):c&&u.status===404?new Oe("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 g=await u.json();return g.visitor?.token&&await this.historyInternals.visitorStore?.set(g.visitor.token),{sessionId:g.sessionId,expiresAt:new Date(g.expiresAt),flow:g.flow,...g.conversationId?{conversationId:g.conversationId}:{},...g.targetId?{targetId:g.targetId}:{},...g.conversationRevision?{conversationRevision:g.conversationRevision}:{},...g.durableRecovery?{durableRecovery:g.durableRecovery}:{},...g.visitor?{visitor:g.visitor}:{},config:{welcomeMessage:g.config.welcomeMessage,placeholder:g.config.placeholder,theme:g.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.createClientSession({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(s,e,!1)}catch(s){if(!fu(s,"not_found")&&!fu(s,"visitor_required")&&!fu(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.createClientSession({storedSessionId:o}),i=await this.claimFirstConversation(s);return this.finishInit(i,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.createClientSession({storedSessionId:n,identityProof:e}),i=this.finishInit(s,o,!1);return this.clientSession=i,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),i}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let s=e.conversationId;return s&&n&&(o||s!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:s}),this.config.setStoredSessionId?.(e.sessionId),s&&(this.config.setStoredConversationId?.(s),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Oe("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new Oe("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}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(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let s={...e,...this.config.clientToken&&{token:this.config.clientToken}},i=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":us},body:JSON.stringify(s)});if(!i.ok){let l=await i.json().catch(()=>({error:"Feedback submission failed"}));throw i.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[i,l]of Object.entries(n))l===void 0||l===""||o.set(i,String(l));let s=o.toString();return`${this.clientApiBase()}/v1/client/${e}${s?`?${s}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let s;try{s=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Oe("identity_provider_failed","The identity proof provider failed")}if(s)return s;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Oe("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let s=await this.reinitWithProof(n);if(!(s.visitor?.identityStatus==="admitted"&&s.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Oe("proof_not_admitted",Vy);return s}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let s=e.toLowerCase();if(s.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Oe("invalid_identity_proof",Ky);if(s.includes("visitor token required"))throw new Oe("visitor_token_missing",Gy);if(s.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Oe("visitor_identity_mismatch",Qy);return this.reinitWithProof(n)}if(s.includes("expired")||s.includes("not found"))return this.clearClientSession(),this.initSession();throw new Oe("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new Oe("not_found","Conversation not found");if(e.status===429){let s=Number.parseInt(e.headers.get("Retry-After")??"",10);return new Oe("rate_limited","Too many history requests",{...Number.isFinite(s)?{retryAfterSeconds:s}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Oe("proof_not_admitted",Vy);if(e.status===401){let s=o.toLowerCase();return s.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Oe("invalid_identity_proof",Ky)):s.includes("visitor token required")?new Oe("visitor_token_missing",Gy):s.includes("visitor_identity_mismatch")?new Oe("visitor_identity_mismatch",Qy):new Oe("unauthorized",o||"History request was not authorized")}return new Oe("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let s=e?.toLowerCase()??null;if(n){if(s==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),s==="ignored"?new Oe("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Oe("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(s==="admitted")throw new Oe("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,s=await this.initSession(),i=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(i=await this.resolveIdentityProof(s,o),i&&(s=await this.bindIdentity(s,i,o)));let l=this.historyInternals.visitorStore,c=!1;for(;;){let d=l?.revision()??0,u=await this.readVisitorToken();if(!u&&!n.visitorTokenOptional)throw new Oe("visitor_token_missing","No visitor credential is stored for this browser");let g=await fetch(this.historyUrl(e,{...n.query,sessionId:s.sessionId}),{method:n.method,headers:{"X-Persona-Version":us,...u?{"X-Visitor-Token":u}:{},...i?{"X-Identity-Proof":i}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(g.status===401&&!c){c=!0,s=await this.recoverFromUnauthorized(await this.readErrorCode(g),i,o);continue}if(!g.ok)throw await this.historyErrorFor(g,o);let m=g.headers.get("X-History-Identity-Status"),v=await g.json().catch(()=>{});if(l&&l.revision()!==d)throw new Oe("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,i!==null,o),v}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Oe("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(zy),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:zy(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let d of n){let u=d.displayContent.length;if(u>qy)throw new Oe("payload_too_large",`displayContent exceeds the ${qy} character limit`);o+=u}if(o>gu)throw new Oe("payload_too_large",`Display projection batch exceeds the ${gu} character limit`);await this.initSession();let s=this.historyInternals.visitorStore,i=s?.revision()??0,l=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=gu,trackIdentity:!1}),c=typeof l?.conversationRevision=="string"?l.conversationRevision:null;return c&&this.clientSession?.conversationId===e&&(s?.revision()??0)===i&&this.historyInternals.setStoredConversationRevision?.(c),{conversationRevision:c}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.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(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){let o=hy();this.currentClientTurnId=o;let s=()=>this.currentClientTurnId===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=()=>{if(e.signal?.throwIfAborted(),!s())throw new DOMException("Turn superseded","AbortError")},c=this.clientSession??await this.initSession();l();let d=async()=>{l();let I=c,P=I.durableRecovery?.enabled===!0;if(P&&(!I.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");l();let N=await this.createClientSession({...P||this.isHistoryCapable()?{conversationId:I.conversationId,durableResume:P}:{storedSessionId:I.sessionId},signal:e.signal});if(l(),I.conversationId&&N.conversationId!==I.conversationId||P&&N.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");c=this.finishInit(N,I.conversationId??null,!1),this.clientSession=c,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await d();let u=await this.buildPayload(e.messages),g=u.metadata?Object.fromEntries(Object.entries(u.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,m=this.isHistoryCapable(),v={sessionId:c.sessionId,messages:e.messages.filter(mu).map(I=>{let P=m?Ca(I):void 0;return{id:I.id,role:I.role,content:I.contentParts??I.llmContent??I.rawContent??I.content,...P!==void 0&&{displayContent:P}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...u.inputs&&Object.keys(u.inputs).length>0&&{inputs:u.inputs},...u.context&&{context:u.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},h=async()=>{l();let I=c.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return l(),this.sendWithClientToolsDiff(c.sessionId,u.clientTools,P=>{let N={...v,sessionId:c.sessionId,...P};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",N),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":us,...I?{"X-Visitor-Token":I}:{}},body:JSON.stringify(N),signal:e.signal})})},T=await h();if(l(),T.response.status===401){let I=await T.response.clone().json().catch(()=>null);l(),I?.error==="Session not found or expired"&&(await d(),T=await h(),l())}let{response:M,commit:E}=T;if(!M.ok){let I=await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let N=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:N}),N}if(M.status===429){let N=new Error(I.hint||"Message limit reached for this session.");throw i({type:"error",error:N}),N}if(M.status===410&&I.error==="conversation_deleted"){let N=new Oe("conversation_deleted","This conversation was deleted");throw i({type:"error",error:N}),N}let P=new Error(I.error||"Failed to send message");throw i({type:"error",error:P}),P}if(!M.body){let I=new Error("No response body received");throw i({type:"error",error:I}),I}E(),i({type:"status",status:"connected"});try{await this.streamResponse(M.body,i,e.assistantMessageId)}finally{i({type:"status",status:"idle"})}}catch(l){let c=l instanceof Error?l:new Error(String(l));throw!(c instanceof Oe)&&!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&i({type:"error",error:c}),c}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,s){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,s){let i=!!(n&&n.length>0),l=i?kh(n):void 0,c=this.clientToolsFingerprintSessionId===e,d=i&&c&&this.lastSentClientToolsFingerprint===l,u=!i&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,g=!1,m;for(let v=0;;v++){if(m=await o({...i&&(g||!d)&&n?{clientTools:n}:{},...u?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),m.status===409&&v===0&&i&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.sentNonEmptyClientToolsSessionId=e:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let s=this.isClientTokenMode(),i=s?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||$y}/resume`,l,c=null;if(s){let g=await this.initSession();l=g.sessionId,g.durableRecovery?.enabled===!0&&(c=await this.readVisitorToken())}let d={"Content-Type":"application/json",...c?{"X-Visitor-Token":c}:{},...this.headers};this.getHeaders&&Object.assign(d,await this.getHeaders());let u={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(l&&(u.sessionId=l),s&&l){let g=[...Sc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:v}=await this.sendWithClientToolsDiff(l,g,h=>{let T={...u,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",T),fetch(i,{method:"POST",headers:d,body:JSON.stringify(T),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&v(),m}return fetch(i,{method:"POST",headers:d,body:JSON.stringify(u),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(i=>i.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=e.slice().filter(mu).filter(u=>u.role==="user"||u.role==="assistant"||u.role==="system").filter(u=>!u.variant||u.variant==="assistant").sort((u,g)=>{let m=new Date(u.createdAt).getTime(),v=new Date(g.createdAt).getTime();return m-v}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),i=this.normalizeComposerOptions(n),l={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},i),messages:s,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};i&&(l.composerOptions=i);let c=[...Sc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let d=await this.buildContextAggregate(e);return d&&(l.context=d),l}async buildPayload(e,n){let o=e.slice().filter(mu).sort((u,g)=>{let m=new Date(u.createdAt).getTime(),v=new Date(g.createdAt).getTime();return m-v}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),s=this.routing(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[u,g]of Object.entries(s.targetPayload))u!=="messages"&&(i[u]=g);let l=[...Sc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.buildContextAggregate(e);c&&(i.context=c);let d=this.normalizeComposerOptions(n);if(d&&(i.composerOptions=d),this.requestMiddleware)try{let u=await this.requestMiddleware({payload:{...i},config:this.config});if(u&&typeof u=="object"){let g=u;return i.clientTools!==void 0&&!("clientTools"in g)&&(g.clientTools=i.clientTools),g}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",u)}return i}async handleCustomSSEEvent(e,n,o,s,i,l){if(!this.parseSSEEvent)return!1;try{let c=await this.parseSSEEvent(e);if(c===null)return!1;let d=g=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:i(),...g!==void 0&&{partId:g}};return o.current=m,s(m),m},u=g=>o.current?o.current:d(g);if(c.text!==void 0){c.partId!==void 0&&l.current!==null&&c.partId!==l.current&&(o.current&&(o.current.streaming=!1,s(o.current)),d(c.partId)),c.partId!==void 0&&(l.current=c.partId);let g=u(c.partId);c.partId!==void 0&&!g.partId&&(g.partId=c.partId),g.content+=c.text,s(g)}return c.done&&(o.current&&(o.current.streaming=!1,s(o.current)),l.current=null,n({type:"status",status:"idle"})),c.error&&(l.current=null,n({type:"error",error:new Error(c.error)})),!0}catch(c){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",c),!1}}async streamResponse(e,n,o,s){let i=e.getReader(),l=new TextDecoder,c="",d=Date.now(),u=0,g=()=>d+u++,m=j=>{let C=j.reasoning?{...j.reasoning,chunks:[...j.reasoning.chunks]}:void 0,_=j.toolCall?{...j.toolCall,chunks:j.toolCall.chunks?[...j.toolCall.chunks]:void 0}:void 0,V=j.tools?j.tools.map(Q=>({...Q,chunks:Q.chunks?[...Q.chunks]:void 0})):void 0;return{...j,reasoning:C,toolCall:_,tools:V}},v=j=>{if(j.role!=="assistant"||j.variant)return!0;let C=Array.isArray(j.contentParts)&&j.contentParts.length>0,_=typeof j.rawContent=="string"&&j.rawContent.trim()!=="";return typeof j.content=="string"&&j.content.trim()!==""||C||_||!!j.stopReason},h=j=>{v(j)&&n({type:"message",message:m(j)})},T=null,M=null,E={current:null},I={current:null},P=null,N="",x=new Map,R=new Map,w=new Map,O=new Map,K=new Map,ie=o,Z=!1,S=()=>{if(T)return T;let j,C="",_=P;return!Z&&ie?(j=ie,Z=!0,C=s??""):ie&&_?j=`${ie}_${_}`:j=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,T={id:j,role:"assistant",content:C,createdAt:new Date().toISOString(),streaming:!0,sequence:g()},h(T),T},B=j=>{let C=O.get(j);if(C)return C;let _={id:`reason-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:g(),reasoning:{id:j,status:"streaming",chunks:[]}};return O.set(j,_),h(_),_},W=new Set,H=new Map,J=new Set,$=new Map,ae=j=>{if(!j)return!1;let C=j.replace(/_+/g,"_").replace(/^_|_$/g,"");return C==="emit_artifact_markdown"||C==="emit_artifact_component"},re=j=>{let C=K.get(j);if(C)return C;let _={id:`tool-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:g(),toolCall:{id:j,status:"pending"}};return K.set(j,_),h(_),_},ue=j=>{if(typeof j=="number"&&Number.isFinite(j))return j;if(typeof j=="string"){let C=Number(j);if(!Number.isNaN(C)&&Number.isFinite(C))return C;let _=Date.parse(j);if(!Number.isNaN(_))return _}return Date.now()},Ee=j=>{if(typeof j=="string")return j;if(j==null)return"";try{return JSON.stringify(j)}catch{return String(j)}},he=new Map,ce=new Map,at=(j,C)=>{let _=Ee(C),V=ce.get(j.id),Q=aA(V,_);j.rawContent=Q;let ee=he.get(j.id),me=Ve=>{let $e=j.content??"";Ve.trim()!==""&&($e.trim().length===0||Ve.startsWith($e)||Ve.trimStart().startsWith($e.trim()))&&(j.content=Ve)},Me=()=>{if(ee){let Ve=ee.close?.();Ve instanceof Promise&&Ve.catch(()=>{})}he.delete(j.id),ce.delete(j.id),j.streaming=!1,h(j)};if(!ee){me(_),Me();return}let Pe=pa(Q);if(Pe!==null&&Pe.trim()!==""){me(Pe),Me();return}let Re=Ve=>{let $e=typeof Ve=="string"?Ve:Ve?.text??null;if($e!==null&&$e.trim()!=="")return $e;let gt=ee.getExtractedText();return gt!==null&>.trim()!==""?gt:_},ot;try{ot=ee.processChunk(Q)}catch{me(_),Me();return}if(ot instanceof Promise){ot.then(Ve=>{me(Re(Ve)),Me()}).catch(()=>{me(_),Me()});return}me(Re(ot)),Me()},ye=null,F=(j,C,_,V)=>{j.rawContent=C,he.has(j.id)||he.set(j.id,this.createStreamParser());let Q=he.get(j.id),ee=C.trim().startsWith("{")||C.trim().startsWith("[");if(ee&&ce.set(j.id,C),Q.__isPlainTextParser===!0){j.content=V!==void 0?C:j.content+_,ce.delete(j.id),he.delete(j.id),j.rawContent=void 0,h(j);return}let Me=Q.processChunk(C);if(Me instanceof Promise)Me.then(Pe=>{let Re=typeof Pe=="string"?Pe:Pe?.text??null;Re!==null&&Re.trim()!==""?(j.content=Re,h(j)):!ee&&!C.trim().startsWith("<")&&(j.content=V!==void 0?C:j.content+_,ce.delete(j.id),he.delete(j.id),j.rawContent=void 0,h(j))}).catch(()=>{j.content=V!==void 0?C:j.content+_,ce.delete(j.id),he.delete(j.id),j.rawContent=void 0,h(j)});else{let Pe=typeof Me=="string"?Me:Me?.text??null;Pe!==null&&Pe.trim()!==""?(j.content=Pe,h(j)):!ee&&!C.trim().startsWith("<")&&(j.content=V!==void 0?C:j.content+_,ce.delete(j.id),he.delete(j.id),j.rawContent=void 0,h(j))}},Te=(j,C)=>{let _=C??j.content;if(_==null||_===""){j.streaming=!1,h(j);return}let Q=ce.get(j.id)??Ee(_);j.rawContent=Q;let ee=he.get(j.id),me=null,Me=!1;if(ee&&(me=ee.getExtractedText(),me===null&&(me=pa(Q)),me===null)){let Pe=ee.processChunk(Q);Pe instanceof Promise?(Me=!0,Pe.then(Re=>{let ot=typeof Re=="string"?Re:Re?.text??null;ot!==null&&(j.content=ot,j.streaming=!1,he.delete(j.id),ce.delete(j.id),h(j))}).catch(()=>{})):me=typeof Pe=="string"?Pe:Pe?.text??null}if(!Me){me!==null&&me.trim()!==""?j.content=me:ce.has(j.id)||(j.content=Ee(_));let Pe=he.get(j.id);if(Pe){let Re=Pe.close?.();Re instanceof Promise&&Re.catch(()=>{}),he.delete(j.id)}ce.delete(j.id),j.streaming=!1,h(j)}},Ue=(j,C,_)=>{let V=R.get(j);if(V)return V;let Q={id:`nested-${C}-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g(),..._?{variant:_}:{},..._==="reasoning"?{reasoning:{id:j,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:C}};return R.set(j,Q),h(Q),Q},qt=[],Le,Fe=new Map,ve=0,ln="agent",Zn=!1,Po=null,vt=null,Io=this.config.iterationDisplay??"separate";for(Le=()=>{for(let j=0;j<qt.length;j++){let C=qt[j];if(!Zn&&ln!=="flow"&&typeof C.stepType=="string"&&(ln="flow"),C.type==="reasoning_start"){let _=typeof C.id=="string"?C.id:null,V=typeof C.parentToolCallId=="string"&&C.parentToolCallId?C.parentToolCallId:null;if(_&&V){x.set(_,V),Ue(_,V,"reasoning");continue}let Q=C.id,ee=B(Q);ee.reasoning=ee.reasoning??{id:Q,status:"streaming",chunks:[]},ee.reasoning.startedAt=ee.reasoning.startedAt??Date.now(),ee.reasoning.completedAt=void 0,ee.reasoning.durationMs=void 0,(C.scope==="loop"||C.scope==="turn")&&(ee.reasoning.scope=C.scope),ee.streaming=!0,ee.reasoning.status="streaming",h(ee)}else if(C.type==="reasoning_delta"){let _=typeof C.id=="string"?C.id:null;if(_&&x.has(_)&&R.has(_)){let ee=R.get(_),me=C.delta;me&&ee.reasoning&&(ee.reasoning.chunks.push(String(me)),h(ee));continue}let V=C.id,Q=B(V);Q.reasoning=Q.reasoning??{id:V,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??Date.now(),C.delta&&Q.reasoning.chunks.push(C.delta),Q.reasoning.status="streaming",Q.streaming=!0,h(Q)}else if(C.type==="reasoning_complete"){let _=typeof C.id=="string"?C.id:null;if(_&&x.has(_)&&R.has(_)){let me=R.get(_);if(me.reasoning){let Me=typeof C.text=="string"?C.text:"";Me&&me.reasoning.chunks.length===0&&me.reasoning.chunks.push(Me),me.reasoning.status="complete",me.streaming=!1,h(me)}x.delete(_),R.delete(_);continue}let V=C.id,Q=typeof C.text=="string"?C.text:"";!O.get(V)&&(Q||C.scope==="loop")&&B(V);let ee=O.get(V);if(ee?.reasoning){(C.scope==="loop"||C.scope==="turn")&&(ee.reasoning.scope=C.scope),Q&&ee.reasoning.chunks.length===0&&ee.reasoning.chunks.push(Q),ee.reasoning.status="complete",ee.reasoning.completedAt=Date.now();let me=ee.reasoning.startedAt??Date.now();ee.reasoning.durationMs=Math.max(0,(ee.reasoning.completedAt??Date.now())-me),ee.streaming=!1,h(ee)}}else if(C.type==="tool_start"){T&&(T.streaming=!1,h(T),T=null),typeof C.iteration=="number"&&(ve=C.iteration);let _=C.toolCallId,V=C.toolName;if(ae(V)){W.add(_);continue}let Q=re(_),ee=Q.toolCall??{id:_,status:"pending"};ee.name=V??ee.name,ee.status="running",ee.success=void 0,ee.error=void 0,ee.duration=void 0,C.parameters!==void 0&&(ee.args=C.parameters),ee.startedAt=ee.startedAt??ue(C.startedAt),ee.completedAt=void 0,ee.durationMs=void 0,Q.toolCall=ee,Q.streaming=!0,C.executionId&&(Q.agentMetadata={executionId:C.executionId,iteration:C.iteration}),h(Q)}else if(C.type==="tool_output_delta"){let _=C.toolCallId;if(W.has(_))continue;let V=re(_),Q=V.toolCall??{id:_,status:"running"};Q.startedAt=Q.startedAt??Date.now();let ee=C.delta;ee&&(Q.chunks=Q.chunks??[],Q.chunks.push(String(ee))),Q.status="running",V.toolCall=Q,V.streaming=!0,C.executionId&&(V.agentMetadata=V.agentMetadata??{executionId:C.executionId,iteration:ve}),h(V)}else if(C.type==="tool_complete"){let _=C.toolCallId;if(W.has(_)){W.delete(_);continue}let V=re(_),Q=V.toolCall??{id:_,status:"running"};Q.status="complete",C.result!==void 0&&(Q.result=C.result),Q.name=C.toolName??Q.name,Q.success=C.success,Q.error=C.error,Q.completedAt=Date.now();let ee=C.executionTime;if(typeof ee=="number")Q.durationMs=ee,Q.duration=ee;else{let me=Q.startedAt??Date.now();Q.durationMs=Math.max(0,(Q.completedAt??Date.now())-me)}V.toolCall=Q,V.streaming=!1,C.executionId&&(V.agentMetadata=V.agentMetadata??{executionId:C.executionId,iteration:C.iteration??ve}),h(V)}else if(C.type==="await"&&C.toolName){let _=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,V=_??C.toolId??`local-${g()}`,Q=re(V),ee=C.toolName,me=C.origin==="webmcp"&&!Js(ee)?`webmcp:${ee}`:ee,Me=Js(me),Pe=Q.toolCall??{id:V,status:"pending"};Pe.name=me,Pe.args=C.parameters,Pe.status=Me?"running":"complete",Pe.chunks=Pe.chunks??[],Pe.startedAt=Pe.startedAt??ue(C.awaitedAt),Me?(Pe.completedAt=void 0,Pe.duration=void 0,Pe.durationMs=void 0):Pe.completedAt=Pe.completedAt??Pe.startedAt,Q.toolCall=Pe,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:C.executionId??Q.agentMetadata?.executionId,awaitingLocalTool:!0,..._?{webMcpToolCallId:_}:{}},h(Q)}else if(C.type==="text_start"){let _=typeof C.id=="string"?C.id:null,V=typeof C.parentToolCallId=="string"&&C.parentToolCallId?C.parentToolCallId:null;if(_&&V){x.set(_,V);continue}let Q=T;Q&&(ln==="flow"?(Te(Q),ye=Q):(Q.streaming=!1,h(Q)),T=null),P=typeof C.id=="string"?C.id:P,N=""}else if(C.type==="text_delta"){let _=typeof C.id=="string"?C.id:null,V=_?x.get(_):void 0;if(_&&V){let me=typeof C.delta=="string"?C.delta:"",Me=(w.get(_)??"")+me;if(w.set(_,Me),Me.trim()==="")continue;let Pe=Ue(_,V);Pe.agentMetadata={...Pe.agentMetadata,executionId:C.executionId,parentToolId:V},F(Pe,Me,me,void 0);continue}if(P=typeof C.id=="string"?C.id:P,ln==="flow"){let me=typeof C.delta=="string"?C.delta:"";if(N+=me,N.trim()==="")continue;let Me=S();Me.agentMetadata={executionId:C.executionId,iteration:ve},F(Me,N,me,void 0),M=Me;continue}let Q=typeof C.delta=="string"?C.delta:"";N+=Q;let ee=S();ee.agentMetadata={executionId:C.executionId,iteration:ve,turnId:Po??void 0,agentName:vt?.agentName},F(ee,N,Q,void 0),M=ee}else if(C.type==="text_complete"){let _=typeof C.id=="string"?C.id:null;if(_&&x.has(_)){let Q=R.get(_);Q&&Te(Q),x.delete(_),w.delete(_),R.delete(_);continue}let V=T;V&&(ln==="flow"?(Te(V),ye=V):((V.content??"")===""&&typeof C.text=="string"&&(V.content=C.text),V.streaming=!1,h(V)),T=null),P=null,N=""}else if(C.type==="step_complete"){if(C.stepType==="tool")continue;if(C.success===!1){let _=C.error||"Step failed";n({type:"error",error:new Error(_)});let V=T;V&&V.streaming&&(V.streaming=!1,h(V)),n({type:"status",status:"idle"});continue}{let _=ye;ye=null;let V=C.stopReason,ee=(C.result&&typeof C.result=="object"?C.result:null)?.response;if(_)V&&(_.stopReason=V),ee!=null?at(_,ee):_.streaming!==!1&&(he.delete(_.id),ce.delete(_.id),_.streaming=!1,h(_));else{let me=ee!=null&&ee!=="";if(me||V){let Me=S();V&&(Me.stopReason=V),me?Te(Me,ee):(Me.streaming=!1,h(Me))}}continue}}else if(C.type==="execution_start")ln=C.kind==="flow"?"flow":"agent",Zn=!0,ln==="agent"&&(vt={executionId:C.executionId,agentId:C.agentId??"virtual",agentName:C.agentName??""});else if(C.type==="turn_start"){let _=typeof C.iteration=="number"?C.iteration:ve;if(_!==ve){if(Io==="separate"&&_>1){let V=T;V&&(V.streaming=!1,h(V),T=null)}ve=_}Po=typeof C.id=="string"?C.id:null,M=null}else if(C.type==="tool_input_delta"){let _=C.toolCallId;if(_){let V=K.get(_);V?.toolCall&&(V.toolCall.chunks=V.toolCall.chunks??[],V.toolCall.chunks.push(C.delta??""),h(V))}}else if(C.type==="tool_input_complete"){if(W.has(C.toolCallId))continue;let _=re(C.toolCallId),V=_.toolCall;V.args=C.parameters,V.name=C.toolName??V.name,h(_)}else if(C.type==="turn_complete"){let _=C.stopReason,V=T??M;if(_&&V!==null){let Q=C.id;(!Q||V.agentMetadata?.turnId===Q)&&(V.stopReason=_,h(V))}Po===C.id&&(Po=null)}else if(C.type==="media_start"){let _=String(C.id);Fe.set(_,{mediaType:typeof C.mediaType=="string"?C.mediaType:void 0,toolCallId:C.toolCallId,parts:[]})}else if(C.type==="media_delta"){let _=Fe.get(String(C.id));_&&typeof C.delta=="string"&&_.parts.push(C.delta)}else if(C.type==="media_complete"){let _=String(C.id),V=Fe.get(_);Fe.delete(_);let Q=(typeof C.mediaType=="string"?C.mediaType:void 0)??V?.mediaType??"application/octet-stream",ee=typeof C.data=="string"?C.data:void 0,me=typeof C.url=="string"?C.url:V&&V.parts.length>0?V.parts.join(""):void 0,Me=null;if(ee)Me={type:"media",data:ee,mediaType:Q};else if(me){let Ve=Q.toLowerCase();Me={type:Ve==="image"||Ve.startsWith("image/")?"image-url":"file-url",url:me,mediaType:Q}}let Pe=C.toolCallId??V?.toolCallId,Re=Me?[Me]:[],ot=[];for(let Ve of Re){if(!Ve||typeof Ve!="object")continue;let $e=Ve,gt=typeof $e.type=="string"?$e.type:void 0,zt=typeof $e.mediaType=="string"?$e.mediaType.toLowerCase():"",kt=null,tn="";if(gt==="media"){let hn=typeof $e.data=="string"?$e.data:void 0;if(!hn)continue;tn=zt.length>0?zt:"application/octet-stream",kt=`data:${tn};base64,${hn}`}else if(gt==="image-url"){let hn=typeof $e.url=="string"?$e.url:void 0;if(!hn)continue;tn=zt,kt=hn}else if(gt==="file-url"){let hn=typeof $e.url=="string"?$e.url:void 0;if(!hn)continue;tn=zt,kt=hn}else continue;if(kt)if(gt==="image-url"||tn.startsWith("image/"))ot.push({type:"image",image:kt,...tn.includes("/")?{mimeType:tn}:{}});else if(tn.startsWith("audio/"))ot.push({type:"audio",audio:kt,mimeType:tn});else if(tn.startsWith("video/"))ot.push({type:"video",video:kt,mimeType:tn});else{let hn=tn||"application/octet-stream";ot.push({type:"file",data:kt,mimeType:hn,filename:sA(hn)})}}if(ot.length>0){let Ve=g(),$e=Pe,zt={id:`agent-media-${typeof $e=="string"&&$e.length>0?`${$e}-${Ve}`:String(Ve)}`,role:"assistant",content:"",contentParts:ot,createdAt:new Date().toISOString(),streaming:!1,sequence:Ve,agentMetadata:{executionId:C.executionId,iteration:ve}};h(zt);let kt=T;kt&&(kt.streaming=!1,h(kt)),T=null,E.current=null}}else if(C.type==="execution_complete"){let _=T;_&&(C.kind==="flow"&&_.streaming!==!1?Te(_):(_.streaming=!1,h(_)),T=null),P=null,N="",ye=null,n({type:"status",status:"idle",terminal:!0})}else if(C.type==="execution_error"){let _=typeof C.error=="string"?C.error:C.error?.message??"Execution error";n({type:"error",error:new Error(_)})}else if(C.type!=="ping"){if(C.type==="approval_start"){let _=C.approvalId??`approval-${g()}`,V={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:g(),approval:{id:_,status:"pending",agentId:vt?.agentId??"virtual",executionId:C.executionId??vt?.executionId??"",toolName:C.toolName??"",toolType:C.toolType,description:C.description??`Execute ${C.toolName??"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};h(V)}else if(C.type==="approval_complete"){let _=C.approvalId;if(_){let Q={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:g(),approval:{id:_,status:C.decision??"approved",agentId:vt?.agentId??"virtual",executionId:C.executionId??vt?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(Q)}}else if(C.type==="artifact_start"||C.type==="artifact_delta"||C.type==="artifact_update"||C.type==="artifact_complete"){if(C.type==="artifact_start"){let _=C.artifactType,V=String(C.id),Q=typeof C.title=="string"?C.title:void 0,ee=C.file,me;if(ee&&typeof ee=="object"&&!Array.isArray(ee)&&typeof ee.path=="string"&&typeof ee.mimeType=="string"&&(me={path:ee.path,mimeType:ee.mimeType,...typeof ee.language=="string"?{language:ee.language}:{}}),n({type:"artifact_start",id:V,artifactType:_,title:Q,component:typeof C.component=="string"?C.component:void 0,...me?{file:me}:{}}),$.set(V,{markdown:"",title:Q,file:me}),!J.has(V)){J.add(V);let Me=Sr(this.config.features?.artifacts,{artifactType:_,...me?{file:me}:{}}),Pe=typeof C.component=="string"?C.component:void 0,Re={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g(),rawContent:ha(Me,{artifactId:V,title:Q,artifactType:_,status:"streaming",...me?{file:me}:{},...Pe?{component:Pe}:{}})};H.set(V,Re),h(Re)}}else if(C.type==="artifact_delta"){let _=String(C.id),V=typeof C.delta=="string"?C.delta:String(C.delta??"");n({type:"artifact_delta",id:_,artDelta:V});let Q=$.get(_);Q&&(Q.markdown+=V)}else if(C.type==="artifact_update"){let _=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:_,component:typeof C.component=="string"?C.component:void 0});let V=$.get(String(C.id));V&&(V.props={...V.props??{},..._})}else if(C.type==="artifact_complete"){let _=String(C.id);n({type:"artifact_complete",id:_});let V=H.get(_);if(V){V.streaming=!1;try{let Q=JSON.parse(V.rawContent??"{}");if(Q.props){Q.props.status="complete";let ee=$.get(_);ee?.markdown&&(Q.props.markdown=ee.markdown),ee?.file&&(Q.props.file=ee.file),Q.component==="PersonaArtifactInline"&&ee?.props&&Object.keys(ee.props).length>0&&(Q.props.componentProps=ee.props)}V.rawContent=JSON.stringify(Q)}catch{}$.delete(_),h(V),H.delete(_)}}}else if(C.type==="error"&&C.recoverable===!1&&C.error!=null&&C.error!==""){let _=typeof C.error=="string"?C.error:C.error?.message!=null?String(C.error.message):"Execution error";n({type:"error",error:new Error(_)});let V=T;V&&V.streaming&&(V.streaming=!1,h(V)),n({type:"status",status:"idle"})}}}qt.length=0};;){let{done:j,value:C}=await i.read();if(j)break;c+=l.decode(C,{stream:!0});let _=c.split(`
|
|
4
4
|
|
|
5
5
|
`);c=_.pop()??"";for(let V of _){let Q=V.split(`
|
|
6
|
-
`),ee="message",me="",Me=null;for(let $e of Q)$e.startsWith("event:")?ee=$e.replace("event:","").trim():$e.startsWith("data:")?me+=$e.replace("data:","").trim():$e.startsWith("id:")&&(Me=$e.slice(3).trim());let Pe=()=>{Me!==null&&Me!==""&&n({type:"cursor",id:Me})};if(!me){Pe();continue}let Re;try{Re=JSON.parse(me)}catch($e){n({type:"error",error:$e instanceof Error?$e:new Error("Failed to parse chat stream payload")});continue}let ot=Re!==null&&typeof Re=="object"&&!Array.isArray(Re)?Re:null,Ve=ee!=="message"?ee:typeof ot?.type=="string"?ot.type:"message";if(this.onSSEEvent?.(Ve,Re),this.parseSSEEvent){
|
|
6
|
+
`),ee="message",me="",Me=null;for(let $e of Q)$e.startsWith("event:")?ee=$e.replace("event:","").trim():$e.startsWith("data:")?me+=$e.replace("data:","").trim():$e.startsWith("id:")&&(Me=$e.slice(3).trim());let Pe=()=>{Me!==null&&Me!==""&&n({type:"cursor",id:Me})};if(!me){Pe();continue}let Re;try{Re=JSON.parse(me)}catch($e){n({type:"error",error:$e instanceof Error?$e:new Error("Failed to parse chat stream payload")});continue}let ot=Re!==null&&typeof Re=="object"&&!Array.isArray(Re)?Re:null,Ve=ee!=="message"?ee:typeof ot?.type=="string"?ot.type:"message";if(this.onSSEEvent?.(Ve,Re),this.parseSSEEvent){E.current=T;let $e=await this.handleCustomSSEEvent(Re,n,E,h,g,I);if(E.current&&E.current!==T&&(T=E.current),$e){Pe();continue}}ot&&(qt.push({...ot,type:Ve}),Le()),Pe()}}Le()}};var lA=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function cA(t){let e=t?.text?.trim()??"";return e?_h(lA(t),e):""}function Yy(t){let e=cA(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[Mo(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
|
|
7
7
|
|
|
8
8
|
`)}:{}}function Ec(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function Jy(t,e){let n=t.findIndex(s=>s.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function hu(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function Zy(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return hu(t,n.id)?n.id:null}return null}function yu(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}function bu(t){let e=["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 n of e){let o=t.find(s=>s.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var xa=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(e.text),i=o.getVoices();if(e.voice){let l=i.find(c=>c.name===e.voice);l&&(s.voice=l)}else i.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(i):bu(i));e.rate!==void 0&&(s.rate=e.rate),e.pitch!==void 0&&(s.pitch=e.pitch),s.onend=()=>n.onEnd?.(),s.onerror=l=>{let c=l.error;c==="canceled"||c==="interrupted"?n.onEnd?.():n.onError?.(new Error(c||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var Tc=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(o!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};var Aa=class{constructor(){this.cancelled=!1}start(e){this.turnId=e,this.cancelled=!1}cancel(){this.cancelled=!0}accepts(e){return!this.cancelled&&(!e||!this.turnId||e===this.turnId)}};var{setLoader:Nk,load:dA}=Tt({fallbackImport:()=>import("./voice-runtime-EFR3R5ES.js")});var vu=dA;function Cu(t){if(!t)return"";let e=pA(t);return eb(e!==null?e:t)}function pA(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function eb(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
9
9
|
`),e=e.replace(/\n{2,}/g,`
|
|
10
|
-
`),e.trim()}var tb=null;var wu=()=>tb?tb():import("./runtype-tts-entry-UJAEF7NZ.js");var{setLoader:zk,load:uA}=Tt({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var nb=uA;var gA=["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 fA(t,e){return gA.some(n=>t[n]!==e[n])}var
|
|
10
|
+
`),e.trim()}var tb=null;var wu=()=>tb?tb():import("./runtype-tts-entry-UJAEF7NZ.js");var{setLoader:zk,load:uA}=Tt({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var nb=uA;var gA=["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 fA(t,e){return gA.some(n=>t[n]!==e[n])}var Eo=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function Su(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
11
11
|
|
|
12
|
-
_Details: ${n.message}_`:o}var xu=t=>({isError:!0,content:[{type:"text",text:t}]}),mA=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,ob=t=>Js(t)||t===Mr,kc=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;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 Aa;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Tc(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(Js(n.name)||n.name===Mr&&Er(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.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?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(s=>({...s,sequence:s.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Sa(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let s of e.initialArtifacts??[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.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&&vu().catch(()=>{})}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||wu().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return ry(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 e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=xa.isSupported()?new xa({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,s=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,l=e.browserFallback!==!1;if(o&&s&&i)return wu().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:d})=>{let u=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new d(u,n,{onFallback:g=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${g.message}`)}):u});if(l&&n)return i&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,s=++this.voiceSetupGeneration;this.voiceSetupPromise=vu().then(async i=>{await o,s===this.voiceSetupGeneration&&this.wireVoiceProvider(i.createVoiceProvider(n))}).catch(i=>{console.error("Failed to setup voice:",i)}).finally(()=>{s===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===e&&n===this.voiceSetupGeneration,i=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(l=>{o()&&l.provider!=="runtype"&&l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((l,c,d,u)=>{if(o())if(l==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let g=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=g.id}if(d){this.voiceTurns.start(u?.turnId),this.pendingVoiceUserMessageId=null;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(u?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let g=this.injectMessage({role:"assistant",content:c,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=g.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(l=>{o()&&(this.voiceLevel=Number.isFinite(l)?Math.max(0,Math.min(1,l)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(l=>{o()&&this.config.voiceRecognition?.onMetrics?.(l)}),this.voiceProvider.onError(l=>{o()&&(console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(l=>{o()&&(this.voiceStatus=l,this.voiceActive=l==="listening",(l==="listening"||l==="idle"||l==="disconnected")&&this.settlePendingVoiceTurn(l!=="listening"),this.callbacks.onVoiceStatusChanged?.(l))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){let e=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new Aa,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(e){let n=e?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),e&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(s=>s.id!==n&&s.id!==o?[s]:s.id===o&&!s.content.trim()?[]:[{...s,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.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 e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){this.clientSession=e,this.injectWelcomeMessage(e)}injectWelcomeMessage(e){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new Mo("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,s=this.config.getIdentityProof?"verified-user":"browser",i=o??(n.capabilities.scopes.includes(s)?s:n.capabilities.scopes[0]??s);if(!n.capabilities.scopes.includes(i))throw new ls("unsupported_scope","This history scope is not supported.");return{scope:i}}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(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Mo("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let s=this.historyContext(n?.scope);await this.awaitHistorySettled();let i=++this.historyOpenEpoch,l=await o.getPage(e,{context:s});if(i!==this.historyOpenEpoch)throw new Mo("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.historyOpenEpoch)throw c.discard(),new Mo("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(c)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=c.conversationId||e,this.activeConversationRevision=c.conversationRevision||l.conversationRevision||null,this.historyNextMessageCursor=l.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of l.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(l.messages),this.emitHistoryState(),{summary:l.summary,nextMessageCursor:l.nextCursor}}loadOlderMessages(e,n,o){let s=this.requireHistoryProvider(),i=this.historyContext(o?.scope),l=n??this.historyNextMessageCursor;if(!l)return Promise.resolve({messages:[],nextMessageCursor:null});let c=`${e} ${l}`,d=this.olderPageRequests.get(c);if(d)return d;let u=this.fetchOlderPage(s,e,l,i).finally(()=>{this.olderPageRequests.delete(c)});return this.olderPageRequests.set(c,u),u}async fetchOlderPage(e,n,o,s){let i=this.messages[0]?.createdAt,l=await e.getPage(n,{cursor:o,...i?{beforeCreatedAt:i}:{},context:s});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:l.nextCursor};let c=wa(this.messages,l.messages);this.messages=this.sortMessages(c.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=l.nextCursor;for(let d of l.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(l.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:l.messages,nextMessageCursor:l.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,i=await n.prepareStartNew({context:o});if(s!==this.historyOpenEpoch)throw i.discard(),new Mo("superseded","A later action won");await this.installFreshConversation(i)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),s=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:s}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(s)}async updateConversation(e,n,o){let s=this.requireHistoryProvider();if(!s.update)throw new Mo("history_unavailable","This history provider cannot update conversations");let i=this.historyContext(o?.scope);return await this.awaitHistorySettled(),s.update(e,n,{context:i})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let s=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),s}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new Mo("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){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(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}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 Mo("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}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(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.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 e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||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(),n&&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(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let s=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let i=this.runBootReconciliation(n,o,s).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===i&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=i,i}async runBootReconciliation(e,n,o){this.activeConversationId=n;let s=this.clientSession?.conversationRevision??this.activeConversationRevision??null,i=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),s&&i&&s===i){this.activeConversationRevision=s;return}let l=await e.getPage(n,{context:o}),c=new Set(l.messages.map(m=>m.id)),d=this.messages.some(m=>c.has(m.id)),u=l.messages[0]?.createdAt,g;if(!d)g=l.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,b=this.messages.filter(h=>c.has(h.id)||h.id===m?!0:u!==void 0&&h.createdAt<u);g=wa(b,l.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=l.nextCursor,this.activeConversationRevision=l.conversationRevision||s||null,this.acknowledgedProjections.clear();for(let m of l.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(g),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=Ca(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let s=Ca(o);s!==void 0&&this.acknowledgedProjections.get(o.id)!==s&&n.push({id:o.id,displayContent:s})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let s=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===s&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=s}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let s=n.filter(i=>this.acknowledgedProjections.get(i.id)!==i.displayContent);if(s.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:i}=await this.client.finalizeDisplayProjections(e,s);for(let l of s)this.acknowledgedProjections.set(l.id,l.displayContent);this.activeConversationId===e&&i&&(this.activeConversationRevision=i),this.clearFinalizedMarker(e,n)}catch(i){if(!o&&this.isTransientProjectionError(i)){await this.finalizeProjections(e,s,!0);return}if(i instanceof Oe&&(i.code==="not_found"||i.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof Oe?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let s=new Set(n.map(l=>l.id)),i=o.messageIds.filter(l=>!s.has(l));this.setPendingProjections(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let s=this.messages.find(i=>i.id===o);!s||typeof s.content!="string"||n.push({id:o,displayContent:s.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),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(e){return e instanceof Oe&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,s,i){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions,interrupt:i?.interrupt},this.handleEvent);return}catch(l){if(!t.isConversationDeleted(l))throw l;let c=await this.recoverFromDeletedConversation(s);if(!c)throw l;this.recordDispatchedProjections([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(s=>s.id===e);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let s=this.historyProvider;if(s){let i=await s.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(i)}else{this.client.clearClientSession();let i=await this.client.initSession();this.bindActivatedSession(i)}}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(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(s=>s.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},s=oy(this.config,o),i=fA(this.config,o);this.config=o,s&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Tn(o.voiceRecognition.provider)&&this.setupVoice());let l=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!i){this.client.updateConfig(o),l&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let c=this.client.getSSEEventCallback();this.client=new Sa(this.config,this.historyInternals),l&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),c&&this.client.setSSEEventCallback(c)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:s,contentParts:i,id:l,createdAt:c,sequence:d,streaming:u=!1,voiceProcessing:g,rawContent:m}=e,h={id:l??(n==="user"?bc():n==="assistant"?ti():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:s,content:i,llmContent:l,contentParts:c,id:d,createdAt:u,sequence:g,streaming:m=!1,voiceProcessing:b,rawContent:h}=o,T={id:d??(s==="user"?bc():s==="assistant"?ti():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:u??new Date().toISOString(),sequence:g??this.nextSequence(),streaming:m,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...b!==void 0&&{voiceProcessing:b},...h!==void 0&&{rawContent:h}};n.push(T)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:s="",llmContent:i,id:l,createdAt:c,sequence:d}=e,u={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(u),...i!==void 0&&{llmContent:i},...l!==void 0&&{id:l},...c!==void 0&&{createdAt:c},...d!==void 0&&{sequence:d}})}async applyMentionBundle(e,n,o){let s;try{s=await o()}catch{return}let i=s.blocks.join(`
|
|
12
|
+
_Details: ${n.message}_`:o}var xu=t=>({isError:!0,content:[{type:"text",text:t}]}),mA=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,ob=t=>Js(t)||t===Mr,kc=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;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 Aa;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Tc(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(Js(n.name)||n.name===Mr&&Er(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.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?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(s=>({...s,sequence:s.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Sa(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let s of e.initialArtifacts??[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.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&&vu().catch(()=>{})}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||wu().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return ry(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 e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=xa.isSupported()?new xa({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,s=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,l=e.browserFallback!==!1;if(o&&s&&i)return wu().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:d})=>{let u=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new d(u,n,{onFallback:g=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${g.message}`)}):u});if(l&&n)return i&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,s=++this.voiceSetupGeneration;this.voiceSetupPromise=vu().then(async i=>{await o,s===this.voiceSetupGeneration&&this.wireVoiceProvider(i.createVoiceProvider(n))}).catch(i=>{console.error("Failed to setup voice:",i)}).finally(()=>{s===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===e&&n===this.voiceSetupGeneration,i=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(l=>{o()&&l.provider!=="runtype"&&l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((l,c,d,u)=>{if(o())if(l==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let g=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=g.id}if(d){this.voiceTurns.start(u?.turnId),this.pendingVoiceUserMessageId=null;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(u?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let g=this.injectMessage({role:"assistant",content:c,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=g.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(l=>{o()&&(this.voiceLevel=Number.isFinite(l)?Math.max(0,Math.min(1,l)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(l=>{o()&&this.config.voiceRecognition?.onMetrics?.(l)}),this.voiceProvider.onError(l=>{o()&&(console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(l=>{o()&&(this.voiceStatus=l,this.voiceActive=l==="listening",(l==="listening"||l==="idle"||l==="disconnected")&&this.settlePendingVoiceTurn(l!=="listening"),this.callbacks.onVoiceStatusChanged?.(l))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){let e=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new Aa,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(e){let n=e?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),e&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(s=>s.id!==n&&s.id!==o?[s]:s.id===o&&!s.content.trim()?[]:[{...s,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.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 e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){this.clientSession=e,this.injectWelcomeMessage(e)}injectWelcomeMessage(e){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new Eo("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,s=this.config.getIdentityProof?"verified-user":"browser",i=o??(n.capabilities.scopes.includes(s)?s:n.capabilities.scopes[0]??s);if(!n.capabilities.scopes.includes(i))throw new ls("unsupported_scope","This history scope is not supported.");return{scope:i}}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(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Eo("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let s=this.historyContext(n?.scope);await this.awaitHistorySettled();let i=++this.historyOpenEpoch,l=await o.getPage(e,{context:s});if(i!==this.historyOpenEpoch)throw new Eo("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.historyOpenEpoch)throw c.discard(),new Eo("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(c)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=c.conversationId||e,this.activeConversationRevision=c.conversationRevision||l.conversationRevision||null,this.historyNextMessageCursor=l.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of l.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(l.messages),this.emitHistoryState(),{summary:l.summary,nextMessageCursor:l.nextCursor}}loadOlderMessages(e,n,o){let s=this.requireHistoryProvider(),i=this.historyContext(o?.scope),l=n??this.historyNextMessageCursor;if(!l)return Promise.resolve({messages:[],nextMessageCursor:null});let c=`${e} ${l}`,d=this.olderPageRequests.get(c);if(d)return d;let u=this.fetchOlderPage(s,e,l,i).finally(()=>{this.olderPageRequests.delete(c)});return this.olderPageRequests.set(c,u),u}async fetchOlderPage(e,n,o,s){let i=this.messages[0]?.createdAt,l=await e.getPage(n,{cursor:o,...i?{beforeCreatedAt:i}:{},context:s});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:l.nextCursor};let c=wa(this.messages,l.messages);this.messages=this.sortMessages(c.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=l.nextCursor;for(let d of l.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(l.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:l.messages,nextMessageCursor:l.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,i=await n.prepareStartNew({context:o});if(s!==this.historyOpenEpoch)throw i.discard(),new Eo("superseded","A later action won");await this.installFreshConversation(i)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),s=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:s}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(s)}async updateConversation(e,n,o){let s=this.requireHistoryProvider();if(!s.update)throw new Eo("history_unavailable","This history provider cannot update conversations");let i=this.historyContext(o?.scope);return await this.awaitHistorySettled(),s.update(e,n,{context:i})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let s=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),s}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new Eo("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){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(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}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 Eo("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}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(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.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 e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||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(),n&&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(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let s=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let i=this.runBootReconciliation(n,o,s).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===i&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=i,i}async runBootReconciliation(e,n,o){this.activeConversationId=n;let s=this.clientSession?.conversationRevision??this.activeConversationRevision??null,i=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),s&&i&&s===i){this.activeConversationRevision=s;return}let l=await e.getPage(n,{context:o}),c=new Set(l.messages.map(m=>m.id)),d=this.messages.some(m=>c.has(m.id)),u=l.messages[0]?.createdAt,g;if(!d)g=l.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,v=this.messages.filter(h=>c.has(h.id)||h.id===m?!0:u!==void 0&&h.createdAt<u);g=wa(v,l.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=l.nextCursor,this.activeConversationRevision=l.conversationRevision||s||null,this.acknowledgedProjections.clear();for(let m of l.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(g),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=Ca(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let s=Ca(o);s!==void 0&&this.acknowledgedProjections.get(o.id)!==s&&n.push({id:o.id,displayContent:s})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let s=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===s&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=s}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let s=n.filter(i=>this.acknowledgedProjections.get(i.id)!==i.displayContent);if(s.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:i}=await this.client.finalizeDisplayProjections(e,s);for(let l of s)this.acknowledgedProjections.set(l.id,l.displayContent);this.activeConversationId===e&&i&&(this.activeConversationRevision=i),this.clearFinalizedMarker(e,n)}catch(i){if(!o&&this.isTransientProjectionError(i)){await this.finalizeProjections(e,s,!0);return}if(i instanceof Oe&&(i.code==="not_found"||i.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof Oe?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let s=new Set(n.map(l=>l.id)),i=o.messageIds.filter(l=>!s.has(l));this.setPendingProjections(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let s=this.messages.find(i=>i.id===o);!s||typeof s.content!="string"||n.push({id:o,displayContent:s.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),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(e){return e instanceof Oe&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,s,i){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions,interrupt:i?.interrupt},this.handleEvent);return}catch(l){if(!t.isConversationDeleted(l))throw l;let c=await this.recoverFromDeletedConversation(s);if(!c)throw l;this.recordDispatchedProjections([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(s=>s.id===e);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let s=this.historyProvider;if(s){let i=await s.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(i)}else{this.client.clearClientSession();let i=await this.client.initSession();this.bindActivatedSession(i)}}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(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(s=>s.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},s=oy(this.config,o),i=fA(this.config,o);this.config=o,s&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Tn(o.voiceRecognition.provider)&&this.setupVoice());let l=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!i){this.client.updateConfig(o),l&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let c=this.client.getSSEEventCallback();this.client=new Sa(this.config,this.historyInternals),l&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),c&&this.client.setSSEEventCallback(c)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:s,contentParts:i,id:l,createdAt:c,sequence:d,streaming:u=!1,voiceProcessing:g,rawContent:m}=e,h={id:l??(n==="user"?bc():n==="assistant"?ti():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:s,content:i,llmContent:l,contentParts:c,id:d,createdAt:u,sequence:g,streaming:m=!1,voiceProcessing:v,rawContent:h}=o,M={id:d??(s==="user"?bc():s==="assistant"?ti():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:u??new Date().toISOString(),sequence:g??this.nextSequence(),streaming:m,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...v!==void 0&&{voiceProcessing:v},...h!==void 0&&{rawContent:h}};n.push(M)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:s="",llmContent:i,id:l,createdAt:c,sequence:d}=e,u={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(u),...i!==void 0&&{llmContent:i},...l!==void 0&&{id:l},...c!==void 0&&{createdAt:c},...d!==void 0&&{sequence:d}})}async applyMentionBundle(e,n,o){let s;try{s=await o()}catch{return}let i=s.blocks.join(`
|
|
13
13
|
|
|
14
14
|
`),l=[i,n].filter(Boolean).join(`
|
|
15
15
|
|
|
16
|
-
`),c=Array.isArray(e.contentParts)&&e.contentParts.length>0,d=s.contentParts.length>0;if(c){let u=[];i&&u.push(Ao(i)),u.push(...s.contentParts),u.push(...e.contentParts),e.contentParts=u}else if(d){let u=[];l&&u.push(Ao(l)),u.push(...s.contentParts),e.contentParts=u}else i&&(e.llmContent=l);Object.keys(s.context).length>0&&(e.mentionContext=s.context)}async sendMessage(e,n){let o=e.trim(),s=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!s)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let i=bc(),l=ti();this.activeAssistantMessageId=null;let c=n?.contentParts&&xc(n.contentParts)?ii:"",d={id:i,role:"user",content:o||c,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(d),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,n?.mentions){let m=this.messages.find(b=>b.id===i)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(h=>h.id===i)??d,b=Yy({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});b.contentParts&&(m.contentParts=b.contentParts),b.llmContent!==void 0&&(m.llmContent=b.llmContent),(b.contentParts||b.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let g=[...this.messages];try{await this.dispatchWithDeletedRecovery(g,u,l,i,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let b=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!b){let h=Su(m,this.config.errorMessage);if(h){let x={id:l,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(x)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(e,n){let o=Jy(this.messages,e);if(!o)return!1;let s=this.messages[o.start],i=n.replacement,l=i?i.text:s.content,c=i?i.contentParts:s.contentParts;if(!(!!l?.trim()||(c?.length??0)>0||!i&&(s.llmContent?.trim()?.length??0)>0))return!1;let u=i?void 0:{...s.llmContent!==void 0&&{llmContent:s.llmContent},...s.rawContent!==void 0&&{rawContent:s.rawContent},...s.mentionContext&&{mentionContext:s.mentionContext},...s.contextMentions&&{contextMentions:s.contextMentions},...s.quote&&{quote:s.quote}},g=i?this.toComposerOptionsPayload(i.options):s.composerOptions,m=i?i.contentSegments:s.contentSegments,b=i?i.options?.quote:void 0,h=i?i.viaVoice:s.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(l??"",{...c?.length?{contentParts:[...c]}:{},...m?.length?{contentSegments:[...m]}:{},...g?{composerOptions:g}:{},...b?{quote:b}:{},...u&&Object.keys(u).length>0?{replayFields:u}:{},viaVoice:h===!0}),!0}toComposerOptionsPayload(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n: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 e=ti();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;let i=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!i){let l=Su(s,this.config.errorMessage);if(l){let c={id:e,role:"assistant",createdAt:new Date().toISOString(),content:l,sequence:this.nextSequence()};this.appendMessage(c)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,i||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(i){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let s=this.messages.find(i=>i.id===e);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let s=`approval-${e.id}`,i={...e,status:n,resolvedAt:Date.now()},l=this.messages.find(g=>g.id===s),c={id:s,role:"assistant",content:"",createdAt:l?.createdAt??new Date().toISOString(),...l?.sequence!==void 0?{sequence:l.sequence}:{},streaming:!1,variant:"approval",approval:i};this.upsertMessage(c),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,u=d&&typeof d=="object"?d.onDecision:void 0;try{let g;if(u?g=await u({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):g=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),g){let m=null;if(g instanceof Response){if(!g.ok){let b=await g.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${g.status}`)}m=g.body}else g instanceof ReadableStream&&(m=g);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.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(g){let m=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(g=>g.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let s=e.agentMetadata?.executionId,i=e.toolCall?.name;if(!s||!i){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let l=typeof n=="string"?void 0:n;if(l===void 0&&typeof n=="string"){let g=e.toolCall?.args,m=Array.isArray(g?.questions)?g.questions:[];if(m.length===1){let b=typeof m[0]?.question=="string"?m[0].question:"";b&&(l={[b]:n})}}this.markAskUserQuestionResolved(e,l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=e.toolCall.id,d=e.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===0){let g=typeof n=="string"?n:Object.entries(n).map(([m,b])=>`${m}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${c}`,role:"user",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let g=l??{};u.forEach((m,b)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let x=g[h],T=Array.isArray(x)?x.join(", "):typeof x=="string"?x:"";this.appendMessage({id:`ask-user-q-${c}-${b}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${c}-${b}`,role:"user",content:T||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let g=await this.client.resumeFlow(s,{[i]:n},{after:this.resumable?.executionId===s?this.resumable.lastEventId:void 0});if(!g.ok){let m=await g.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${g.status}`)}g.body?await this.connectStream(g.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(g){let m=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(g instanceof Error?g:new Error(String(g)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(o)&&(s.seen.add(o),s.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(s=>s.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==Mr?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,s=Date.now(),i){this.messages.some(l=>l.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...i},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:s,duration:void 0,durationMs:Math.max(0,s-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let i=async d=>{let u=d.toolCall?.name,g=d.toolCall?.id;if(!u||!g)return null;let m=`${e}:${g}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(m),o.push(m);let b=this.markWebMcpToolRunning(d),h=d.agentMetadata?.webMcpToolCallId??u;if(u===Mr)return{dedupeKey:m,resumeKey:h,output:Iy(),toolMessage:d,startedAt:b,completedAt:Date.now()};let x=this.client.executeWebMcpToolCall(u,d.toolCall?.args,s.signal),T;if(!x)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await x}catch(M){let O=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));return O||this.callbacks.onError?.(M instanceof Error?M:new Error(String(M))),this.markWebMcpToolComplete(d,xu(O?"Aborted by cancel()":mA(M)),b),this.webMcpInflightKeys.delete(m),null}return s.signal.aborted?(this.markWebMcpToolComplete(d,xu("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:T,toolMessage:d,startedAt:b,completedAt:Date.now()}},l;if(this.config.webmcp?.execution==="sequential"){l=[];for(let d of n)l.push(await i(d))}else l=await Promise.all(n.map(i));let c=[];try{if(c=l.filter(g=>g!==null),c.length===0)return;let d={};for(let g of c)d[g.resumeKey]=g.output;let u=await this.client.resumeFlow(e,d,{signal:s.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!u.ok){let g=await u.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${u.status}`)}for(let g of c)this.webMcpResolvedKeys.add(g.dedupeKey),this.markWebMcpToolComplete(g.toolMessage,g.output,g.startedAt,g.completedAt,g.toolMessage.toolCall?.name===Mr?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let g of c)this.markWebMcpToolComplete(g.toolMessage,xu("Aborted by cancel()"),g.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,s=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!s){let l=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(l)||this.webMcpResolvedKeys.has(l))return;this.webMcpInflightKeys.add(l);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(l)}catch(c){this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}finally{this.webMcpInflightKeys.delete(l)}return}let i=`${n}:${s}`;if(!(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i)||this.isSuggestRepliesAlreadyResolved(e)))return this.resolveWebMcpToolCallBatch(n,[e])}async resumeWithToolOutput(e,n,o,s){let i=await this.client.resumeFlow(e,{[n]:o},{signal:s?.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!i.ok){let l=await i.json().catch(()=>null);throw new Error(l?.error??`Resume failed: ${i.status}`)}s?.onHttpOk?.(),i.body?await this.connectStream(i.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=Sr(this.config.features?.artifacts,e),s=ha(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),i=this.messages.find(l=>l.id===n);if(i){i.rawContent=s,i.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:s})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(l=>l.id===`artifact-ref-${n.id}`);if(!o)continue;let s=Sr(this.config.features?.artifacts,n),i=ha(s,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==i&&(o.rawContent=i,o.streaming=n.status==="streaming",e=!0)}e&&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(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}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(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.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(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=nb().then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,s)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>Su(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=ti(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let s=Cu(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return bu(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=Cu(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,i)=>{if(i!==o)return s;let l={...s,...n};if(s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(l.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(l.agentMetadata={...l.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let g=s.approval,m=n.approval;l.approval={...g,...m,executionId:m.executionId||g.executionId,toolName:m.toolName||g.toolName,description:m.description||g.description,toolType:m.toolType??g.toolType,reason:m.reason??g.reason,parameters:m.parameters??g.parameters}}let c=n.toolCall?.name,d=n.agentMetadata?.executionId,u=n.toolCall?.id;if(c&&ob(c)&&d&&u&&n.agentMetadata?.awaitingLocalTool===!0){let g=`${d}:${u}`,m=this.webMcpInflightKeys.has(g),b=this.webMcpResolvedKeys.has(g),h=s.toolCall?.name,x=s.agentMetadata?.executionId===d&&s.toolCall?.id===u&&h!==void 0&&ob(h)&&s.toolCall?.status==="complete";(m||b||x)&&(l.agentMetadata={...l.agentMetadata??{},awaitingLocalTool:!1},l.toolCall=s.toolCall,l.streaming=s.streaming)}return l}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),i=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=n.sequence??0,c=o.sequence??0;return l!==c?l-c:n.id.localeCompare(o.id)})}};import{File as hA,FileCode as yA,FileSpreadsheet as bA,FileText as Au,X as vA}from"lucide";var CA={add:t=>Oy(t)},wA=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Pc={allowedTypes:Yo,maxFileSize:10*1024*1024,maxFiles:4};function SA(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xA(t){return t==="application/pdf"?Au:t.startsWith("text/")?Au:t.includes("word")?Au:t.includes("excel")||t.includes("spreadsheet")?bA:t==="application/json"?yA:hA}var Ma=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Pc.allowedTypes,maxFileSize:e.maxFileSize??Pc.maxFileSize,maxFiles:e.maxFiles??Pc.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:CA}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Pc.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.destroyed)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let s=_y(o,this.config.allowedTypes,this.config.maxFileSize);if(!s.valid){let l=s.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,l);continue}let i={id:SA(),file:o,previewUrl:Ac(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(i),this.renderPreview(i),n.push(i)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(e){let n=new AbortController;this.pendingAdds.set(e.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(e.id)!==n||!this.attachments.includes(e);try{let s=await this.adapter().add(e.file,{signal:n.signal,onProgress:i=>{o()||e.status!=="uploading"||(e.progress=wA(i),this.updatePreview(e),this.notify())}});if(o())return;e.contentPart=s,e.status="ready",e.progress=void 0,e.error=void 0}catch(s){if(o())return;e.status="error",e.progress=void 0,e.error=s instanceof Error?s.message:String(s??"Upload failed")}finally{this.pendingAdds.get(e.id)===n&&this.pendingAdds.delete(e.id)}this.updatePreview(e),this.notify()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(e){let n=this.pendingAdds.get(e);n&&(this.pendingAdds.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(i=>i.id===e);if(n===-1)return;let o=this.attachments[n];this.abortAdd(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);s&&s.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(s=>{console.error("[AttachmentManager] adapter.remove failed:",s)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.abortAdd(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.pendingAdds.values())e.abort();this.pendingAdds.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=Ac(e.file),o=k("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let g=k("img");g.src=e.previewUrl,g.alt=e.file.name,g.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",g.style.width="48px",g.style.height="48px",g.style.objectFit="cover",g.style.borderRadius="8px",o.appendChild(g)}else{let g=k("div");g.style.width="48px",g.style.height="48px",g.style.borderRadius="8px",g.style.backgroundColor="var(--persona-container, #f3f4f6)",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.display="flex",g.style.flexDirection="column",g.style.alignItems="center",g.style.justifyContent="center",g.style.gap="2px",g.style.overflow="hidden";let m=xA(e.file.type),b=en(m,20,"var(--persona-muted, #6b7280)",1.5);b&&g.appendChild(b);let h=k("span");h.textContent=Ny(e.file.type,e.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",g.appendChild(h),o.appendChild(g)}let s=G("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),i=k("div","persona-attachment-progress");i.appendChild(k("div","persona-attachment-progress__bar"));let l=G("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=ge("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);c?l.appendChild(c):l.textContent="\u21BB",l.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.retryAttachment(e.id)}),s.append(i,l),o.appendChild(s);let d=k("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let u=en(vA,10,"var(--persona-text-inverse, #ffffff)",2);u?d.appendChild(u):(d.textContent="\xD7",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(d),this.previewsContainer.appendChild(o),this.applyPreviewState(o,e)}updatePreview(e){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.applyPreviewState(n,e)}applyPreviewState(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let s=e.querySelector(".persona-attachment-progress__bar");if(s){let i=n.progress;s.style.width=typeof i=="number"?`${Math.round(i*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var rb=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),AA=(t,e)=>t.length===e.length&&t.every((n,o)=>{let s=e[o];return n.id===s.id&&n.name===s.name&&n.mimeType===s.mimeType&&n.size===s.size&&n.status===s.status&&n.progress===s.progress&&n.error===s.error});function sb(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,s=!1,i=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",l=()=>{let g=i();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:g,inputDisabled:t.inputDisabled,sendDisabled:g!=="idle"||t.sendDisabled||t.inputDisabled})},c=()=>(n||(n=l()),n),d=()=>{if(o=!1,s||e.size===0)return;let g=c();for(let m of[...e])try{m(g)}catch(b){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",b)}},u=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(d))};return{getState:c,subscribe:g=>(e.add(g),()=>e.delete(g)),setText:g=>{t.text!==g&&(t.text=g,u())},setAttachments:g=>{AA(t.attachments,g)||(t.attachments=[...g],u())},setMentionRefs:g=>{rb(t.mentionRefs,g)||(t.mentionRefs=[...g],u())},setSelectedModelId:g=>{t.selectedModelId!==g&&(t.selectedModelId=g,u())},setActiveModeIds:g=>{rb(t.activeModeIds,g)||(t.activeModeIds=[...g],u())},setQuote:g=>{let m=t.quote;m?.text===g?.text&&m?.messageId===g?.messageId&&m?.sourceLabel===g?.sourceLabel||(t.quote=g?{...g}:void 0,u())},setPendingSubmission:g=>{t.pendingSubmission!==g&&(t.pendingSubmission=g,u())},setPreparing:g=>{t.preparing!==g&&(t.preparing=g,u())},setStreaming:g=>{t.streaming!==g&&(t.streaming=g,u())},setInputDisabled:g=>{t.inputDisabled!==g&&(t.inputDisabled=g,u())},setSendDisabled:g=>{t.sendDisabled!==g&&(t.sendDisabled=g,u())},flush:()=>{o&&d()},destroy:()=>{s=!0,o=!1,e.clear()}}}var kn=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},ib=(t,e)=>{let n=k("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function ab(t,e={}){let n=kn(t,"[data-persona-composer-form]"),o=kn(t,"[data-persona-composer-input]");if(!n||!o){let O=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(O);return typeof console<"u"&&console.warn(O),null}let s={header:kn(t,"[data-persona-composer-header]"),body:kn(t,"[data-persona-composer-body]"),actionsStart:kn(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:kn(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:kn(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:kn(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:kn(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=ib("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(l,n):t.appendChild(l));let c=s.body??o.parentElement??n,d=(M,O,I,z,A)=>{if(O)return O;i.add(M);let H=ib(I,z);return A.appendChild(H),H},u=d("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),g=d("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",s.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),b=d("status",s.status,"persona-widget-composer__status","data-persona-composer-status",t),h=[],x=(M,O)=>M.target===O.target&&M.type===O.type&&M.handler===O.handler,T=kn(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:l,body:c,actionsStart:u,actionsEnd:g,suggestions:m,status:b,attachmentInput:T,attachmentPreviews:kn(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:kn(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:kn(t,"[data-persona-composer-submit]")??void 0,micButton:kn(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(M,O,I,z)=>{M.addEventListener(O,I,z),h.push({target:M,type:O,handler:I,options:z})},removeListener:(M,O,I,z)=>{M.removeEventListener(O,I,z),h=h.filter(A=>!x(A,{target:M,type:O,handler:I}))},destroy:()=>{for(let M of h)M.target.removeEventListener(M.type,M.handler,M.options);h=[]}}}var MA=8,EA=8,Mu=10,lb=200,cb=300,db=0,Lc=t=>Math.max(0,t);function pb(t){t.delayMs!==void 0&&(lb=Lc(t.delayMs)),t.skipDelayMs!==void 0&&(cb=Lc(t.skipDelayMs))}var TA=()=>Date.now()<db,kA=t=>{db=t>0?Date.now()+t:0},Ic=new WeakMap,Tu="data-persona-tooltip-suppressed",PA=t=>typeof t.closest=="function"&&t.closest(`[${Tu}]`)!==null;function ub(t){Ic.get(t)?.hide()}var gb=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,IA=t=>{let e=t.getRootNode?.();return gb(e)?e:t.ownerDocument.body},Eu=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),LA=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(t=>`--persona-tooltip-${t}`),"--persona-font-family","--persona-radius-sm"];function Qt(t){Ic.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:s,enabled:i=!0,gap:l=MA,viewportPadding:c=EA}=t,d=()=>e.ownerDocument,u=()=>d().defaultView??window,g=null,m=null,b=null,h=null,x,T=!1,M=!1,O=!1,I=()=>(typeof o=="function"?o():o).trim(),z=()=>(typeof s=="function"?s():s??"").trim(),A=()=>Lc(t.delayMs??lb),H=()=>Lc(t.skipDelayMs??cb),w=()=>{x!==void 0&&(u().clearTimeout(x),x=void 0)},D=()=>{w();let ue=g!==null;h?.(),h=null,g?.remove(),g=null,m=null,b=null,ue&&kA(H())},K=()=>{if(!g)return;let ue=d(),Ee=u(),he=e.getBoundingClientRect(),ce=g.getBoundingClientRect(),at=ue.documentElement.clientWidth||Ee.innerWidth,ye=ue.documentElement.clientHeight||Ee.innerHeight,N=at-c-ce.width,Te=he.left+he.width/2-ce.width/2,Ue=Eu(Te,c,N),qt=he.top-c,Le=ye-c-he.bottom,Fe=ce.height+l,ve=qt>=Fe||qt>=Le?"top":"bottom",ln=ve==="top"?he.top-l-ce.height:he.bottom+l,Jn=ye-c-ce.height,ko=Eu(ln,c,Jn),vt=he.left+he.width/2,Po=Math.max(Mu,ce.width-Mu),j=Eu(vt-Ue,Mu,Po);g.dataset.placement=ve,g.style.left=`${Ue}px`,g.style.top=`${ko}px`,g.style.setProperty("--persona-tooltip-arrow-x",`${j}px`)},ie=()=>{if(O||!i||g||!e.isConnected||PA(e))return;let ue=I(),Ee=IA(e);if(!ue||!Ee)return;let he=d(),ce=u();g=he.createElement("div"),g.className="persona-control-tooltip",g.setAttribute("role","tooltip"),g.dataset.state="measuring",g.style.zIndex=String(uc);let at=ce.getComputedStyle?.(e);if(at){for(let Fe of LA){let ve=at.getPropertyValue(Fe).trim();ve&&g.style.setProperty(Fe,ve)}at.fontFamily&&(g.style.fontFamily=at.fontFamily)}m=he.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ue,g.appendChild(m);let ye=z();ye&&(b=he.createElement("span"),b.className="persona-control-tooltip__hint",b.textContent=ye,g.appendChild(b));let N=he.createElement("span");N.className="persona-control-tooltip__arrow",g.appendChild(N),Ee.appendChild(g),K(),g.dataset.state="open";let Te=()=>{if(!e.isConnected){D();return}m&&(m.textContent=I()),b&&(b.textContent=z()),K()};ce.addEventListener("scroll",Te,!0),ce.addEventListener("resize",Te);let Ue=e.getRootNode(),qt=gb(Ue)?Ue:he.documentElement,Le=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||D()});Le?.observe(qt,{childList:!0,subtree:!0}),h=()=>{ce.removeEventListener("scroll",Te,!0),ce.removeEventListener("resize",Te),Le?.disconnect()}},Z=ue=>{if(!(O||g)){if(w(),ue||A()<=0||TA()){ie();return}x=u().setTimeout(()=>{x=void 0,ie()},A())}},S=()=>{T||M?Z(M):D()},W=()=>{let ue=u();(!ue.matchMedia||!ue.matchMedia("(hover: none)").matches)&&(T=!0,S())},R=()=>{T=!1,S()},L=()=>{try{M=e.matches(":focus-visible")}catch{M=!0}S()},J=()=>{M=!1,S()},U=()=>{T=!1,M=!1,D()},ae=ue=>{ue.key==="Escape"&&U()};n.addEventListener("mouseenter",W),n.addEventListener("mouseleave",R),e.addEventListener("focus",L),e.addEventListener("blur",J),e.addEventListener("keydown",ae),e.addEventListener("click",U);let re={get isOpen(){return g!==null},show:ie,hide:D,reposition:K,destroy:()=>{O||(O=!0,D(),n.removeEventListener("mouseenter",W),n.removeEventListener("mouseleave",R),e.removeEventListener("focus",L),e.removeEventListener("blur",J),e.removeEventListener("keydown",ae),e.removeEventListener("click",U),Ic.delete(e))}};return Ic.set(e,re),re}var fb=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ai(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];fb(i)&&fb(s)?n[o]=ai(i,s):n[o]=s}return n}var Jo="min(440px, calc(100vw - 24px))",hb="440px",ku="How can I help...",HA={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:Jo,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)"},nt={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:HA,copy:{inputPlaceholder:ku,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 mb(t,e){if(!(!t&&!e))return t?e?ai(t,e):t:e}function Hc(t){return t?{...nt,...t,theme:mb(nt.theme,t.theme),darkTheme:mb(nt.darkTheme,t.darkTheme),launcher:{...nt.launcher,...t.launcher,dock:{...nt.launcher?.dock,...t.launcher?.dock},clearChat:{...nt.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...nt.tooltip,...t.tooltip},copy:{...nt.copy,...t.copy},sendButton:{...nt.sendButton,...t.sendButton},statusIndicator:{...nt.statusIndicator,...t.statusIndicator},voiceRecognition:{...nt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=nt.features?.artifacts,n=t.features?.artifacts,o=nt.features?.scrollToBottom,s=t.features?.scrollToBottom,i=nt.features?.scrollBehavior,l=t.features?.scrollBehavior,c=nt.features?.streamAnimation,d=t.features?.streamAnimation,u=nt.features?.askUserQuestion,g=t.features?.askUserQuestion,m=nt.features?.history,b=t.features?.history,h=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},x=o===void 0&&s===void 0?void 0:{...o,...s},T=i===void 0&&l===void 0?void 0:{...i,...l},M=c===void 0&&d===void 0?void 0:{...c,...d},O=u===void 0&&g===void 0?void 0:{...u,...g,styles:{...u?.styles,...g?.styles}},I=m===void 0&&b===void 0?void 0:{...m,...b,copy:{...m?.copy,...b?.copy}};return{...nt.features,...t.features,...x!==void 0?{scrollToBottom:x}:{},...T!==void 0?{scrollBehavior:T}:{},...h!==void 0?{artifacts:h}:{},...M!==void 0?{streamAnimation:M}:{},...O!==void 0?{askUserQuestion:O}:{},...I!==void 0?{history:I}:{}}})(),suggestionChips:t.suggestionChips??nt.suggestionChips,suggestionChipsConfig:{...nt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...nt.layout,...t.layout,header:{...nt.layout?.header,...t.layout?.header},messages:{...nt.layout?.messages,...t.layout?.messages,avatar:{...nt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...nt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...nt.layout?.slots,...t.layout?.slots}},markdown:{...nt.markdown,...t.markdown,options:{...nt.markdown?.options,...t.markdown?.options}},messageActions:{...nt.messageActions,...t.messageActions}}:nt}function Pu(t){let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return 20;let n=e.getComputedStyle(t).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function Rc(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function yb(t,e){t.style.maxHeight=`${e*Pu(t)}px`,t.style.overflowY="auto"}function ka(t){let e=t?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!e||typeof e.matchMedia!="function")return!1;try{return e.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function bb(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function vb(t,e){if(t.key!=="Enter"||t.shiftKey||t.isComposing)return!1;let n=t.metaKey===!0||t.ctrlKey===!0,o=e.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!bb(e)}function RA(t){return(t.submitKey??"enter")!=="enter"||bb(t)?"enter":"send"}function Wc(t,e){t.setAttribute("enterkeyhint",RA(e))}function Bc(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(s,i)=>{i===void 0?t.removeAttribute(s):t.setAttribute(s,i)};o("autocapitalize",typeof e?.autocapitalize=="string"?e.autocapitalize:void 0),o("spellcheck",typeof e?.spellcheck=="boolean"?String(e.spellcheck):void 0),o("inputmode",typeof e?.inputmode=="string"&&e.inputmode?e.inputmode:void 0),o("aria-label",typeof e?.ariaLabel=="string"&&e.ariaLabel?e.ariaLabel:void 0)}function Iu(t){return t===!0?{disabled:!0}:!t||typeof t!="object"?{disabled:!1}:{disabled:!0,reason:typeof t.reason=="string"&&t.reason?t.reason:void 0}}var Nn="persona-composer-control",co="persona-composer-control--glyph",Hu=40,pn=24,Dc=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let s=o.getComputedStyle(t);for(let i of n){let l=s.getPropertyValue(i).trim();l?e.style.setProperty(i,l):e.style.removeProperty(i)}},Oc=(t,e)=>{let n=k("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??ku,n.dir="auto",Wc(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:ka(n)}),Bc(n,t?.composer?.inputAttributes),n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=Rc(t?.composer?.maxLines,e?.defaultMaxLines??3),s=`${o*20}px`;n.style.maxHeight=s,n.style.overflowY="auto";let i=()=>{let c=n.style.maxHeight;if(c!==s){let u=parseFloat(c);if(Number.isFinite(u)&&u>0)return u}let d=o*Pu(n);return s=`${d}px`,n.style.maxHeight=s,d},l=()=>{n.addEventListener("input",()=>{n.style.height="auto";let c=Math.min(n.scrollHeight,i());n.style.height=`${c}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:l}},BA="[data-persona-glyph-stack]",Ru=(t,e,n="send")=>{let o=G("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return t.setAttribute("data-glyph","send"),e.setAttribute("data-glyph","stop"),o.append(t,e),o},_c=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",s=e.iconName,i=e.stopIconName??"square",l=e.tooltipText??"Send message",c=e.stopTooltipText??"Stop generating",d=t?.copy?.sendButtonLabel??"Send",u=t?.copy?.stopButtonLabel??"Stop",g=e.showTooltip??!1,m=e.size,b=parseFloat(m??"")||Hu,h=e.backgroundColor,x=e.textColor,T=k("div","persona-send-button-wrapper"),M=G("button",{className:_n("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Nn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!x&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?x||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":x||void 0,backgroundColor:n&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),O=null,I=null,z=null;if(n){let w=parseFloat(e.iconSize??"")||Math.round(b*.5),D=e.iconStrokeWidth??2,K=x?.trim()||"currentColor";s&&(O=ge(s,w,K,D)),I=ge(i,w,K,D),O&&I?(z=Ru(O,I),M.appendChild(z)):O?M.appendChild(O):(M.textContent=o,I=null)}else M.textContent=d;M.setAttribute("aria-label",l),T.appendChild(M),Qt({anchor:M,trigger:T,text:()=>M.getAttribute("aria-label")??"",enabled:g});let A="send";return{button:M,wrapper:T,setMode:w=>{if(w===A)return;A=w;let D=w==="stop"?c:l;M.setAttribute("aria-label",D),M.setAttribute("data-persona-send-mode",w),n?(M.querySelector(BA)??z)?.setAttribute("data-mode",w):M.textContent=w==="stop"?u:d},glyphStack:z}},li=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),s=e.provider?.type==="runtype",i=e.provider?.type==="custom";if(!(o||s||i))return null;let c=e.iconName??"mic",d=e.iconSize,u=parseFloat(d??"")||pn,g=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,b=k("div","persona-send-button-wrapper"),h=G("button",{className:_n("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nn,!d&&co),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),T=ge(c,u,m||"currentColor",1.5);T?h.appendChild(T):h.textContent="\u{1F3A4}",b.appendChild(h);let M=e.tooltipText??"Start voice recognition",O=e.showTooltip??!1;return Qt({anchor:h,trigger:b,text:()=>h.getAttribute("aria-label")??M,enabled:O}),{button:h,wrapper:b}},Nc=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=k("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(e.allowedTypes??Yo).join(","),o.multiple=(e.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",i=k("div","persona-send-button-wrapper"),l=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Nn} ${co}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),c=ge(s,pn,"currentColor",1.5);c?l.appendChild(c):l.textContent="\u{1F4CE}",l.addEventListener("click",u=>{u.preventDefault(),o.click()}),i.appendChild(l);let d=e.buttonTooltipText??"Attach file";return Qt({anchor:l,trigger:i,text:()=>l.getAttribute("aria-label")??d}),{button:l,wrapper:i,input:o,previewsContainer:n}},Fc=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=k("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let s=e.visible??!0;o.style.display=s?"":"none";let i=e.idleText??"Online";if(e.idleLink){let l=k("a");l.href=e.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=i,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=i;return o},Uc=()=>G("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var DA='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',OA=["--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"],Wu="data-persona-menu-focus",_A=new Set(["ArrowDown","ArrowUp","Home","End"]);function Cb(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(DA)??t}var NA=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function wb(t){let e=t.label,n=!1,o=k("div","persona-send-button-wrapper"),s=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Nn} ${co}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=G("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),l=()=>{let L=t.getButtonSize?.()??"";s.style.width=L,s.style.height=L,s.style.minWidth=L,s.style.minHeight=L,s.style.lineHeight="1",s.replaceChildren();let J=ge("plus",pn,"currentColor",1.5);J?s.appendChild(J):s.textContent="+"},c=()=>{s.setAttribute("aria-label",e),s.setAttribute("title",e),i.setAttribute("aria-label",e)};c(),l();let d=[],u=-1,g=!1,m=()=>{let J=i.getRootNode().activeElement;return J instanceof HTMLElement?J:null},b=()=>{let L=m();for(let J of d){let U=!!L&&Cb(J)===L;J.toggleAttribute(Wu,U&&g)}},h=()=>d.filter(L=>L.isConnected||i.contains(L)).map(Cb).filter(L=>!NA(L)),x=(L,J)=>{L.forEach((U,ae)=>{U.setAttribute("tabindex",ae===J?"0":"-1")})},T=L=>{let J=h();if(J.length===0)return;let U=(L%J.length+J.length)%J.length;u=U,x(J,U),J[U].focus(),b()},M=()=>o.ownerDocument??document,O=null,I=null,z=null,A=()=>{O&&(M().removeEventListener("focusin",O,!0),O=null)},H=()=>{I&&(i.removeEventListener("focusin",I),I=null),z&&(i.removeEventListener("pointerdown",z,!0),z=null)},w=null,D=()=>(w||(w=gc({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),A()}})),w),K=()=>w?.isOpen===!0,ie=(L=!1)=>{if(K()){w?.close(),s.setAttribute("aria-expanded","false"),A(),H(),u=-1,g=!1;for(let J of d)J.removeAttribute(Wu);L&&s.focus()}},Z=(L=0,J=!1)=>{if(n||K())return;g=J,Dc(s,i,OA),D().open(),s.setAttribute("aria-expanded","true");let U=h();x(U,-1),T(L<0?U.length-1:L),O=ae=>{let re=typeof ae.composedPath=="function"?ae.composedPath():[];re.includes(i)||re.includes(o)||ie()},M().addEventListener("focusin",O,!0),I=()=>b(),i.addEventListener("focusin",I),z=()=>{g=!1},i.addEventListener("pointerdown",z,!0)},S=L=>{L.preventDefault(),L.stopPropagation(),K()?ie(!0):Z(0)},W=L=>{if(L.key==="ArrowDown"||L.key==="Enter"||L.key===" "){L.preventDefault(),g=!0,K()?T(0):Z(0,!0);return}L.key==="ArrowUp"&&(L.preventDefault(),g=!0,K()?T(-1):Z(-1,!0))},R=L=>{switch(_A.has(L.key)&&(g=!0),L.key){case"ArrowDown":L.preventDefault(),T(u+1);return;case"ArrowUp":L.preventDefault(),T(u-1);return;case"Home":L.preventDefault(),T(0);return;case"End":L.preventDefault(),T(h().length-1);return;case"Escape":L.preventDefault(),L.stopPropagation(),ie(!0);return;case"Tab":ie(!0);return;default:}};return s.addEventListener("click",S),s.addEventListener("keydown",W),i.addEventListener("keydown",R),{trigger:o,triggerButton:s,panel:i,setItems:L=>{for(let U of d)L.includes(U)||U.removeAttribute(Wu);if(d=[...L],!K())return;let J=h();x(J,Math.min(u,J.length-1)),b()},isOpen:K,open:()=>Z(0),close:ie,setLabel:L=>{L!==e&&(e=L,c())},applyButtonSize:l,destroy:()=>{n=!0,A(),H(),s.removeEventListener("click",S),s.removeEventListener("keydown",W),i.removeEventListener("keydown",R),w?.destroy(),w=null,o.remove(),i.remove(),d=[]}}}var Eo={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Sb="data-persona-composer-action",Bu="data-persona-composer-disable-when-streaming",FA="core:overflow",UA=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function $A(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=k("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let s=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(s)&&s>0?s:Number.isFinite(n)?n:null}function Du(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),s=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-s)}var xb=(t,e)=>{!t||typeof console>"u"||console.warn(e)},qA=(t,e)=>e.includes(":")?e:`${t}:${e}`;function zA(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let d=o.get(c.id);if(d){xb(e,`[Persona] composer action "${c.id}" is already contributed by ${Ab(d)}; the ${Ab(c)} copy is ignored.`);return}o.set(c.id,c),n.push(c)};for(let c of t.builtIns)i({id:c.id,placement:c.placement,presentation:"bar",order:c.order,sequence:s++,source:"core",builtIn:c});let l=(c,d,u)=>{let g=u?qA(u,c.id):c.id,m=c.order??Eo.custom;c.placement==="end"&&m>=Eo.send&&(xb(e,`[Persona] composer action "${g}" ordered at ${m} would render after send; clamped to ${Eo.send-1}.`),m=Eo.send-1),i({id:g,placement:c.placement,presentation:c.presentation??"bar",order:m,sequence:s++,source:d,pluginId:u,action:c})};for(let c of t.configActions??[])l(c,"config");for(let c of t.plugins){if(!c.contributeComposerActions)continue;let d;try{d=c.contributeComposerActions(t.contributionContext)}catch(u){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,u);continue}for(let u of d??[])l(u,"plugin",c.id)}return n.sort((c,d)=>c.order===d.order?c.sequence-d.sequence:c.order-d.order)}var Ab=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",Mb=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,jA=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function VA(t,e){if(!t||t==="always")return!0;let n=jA(e);return t==="when-text"?n:!n}var Tr=t=>t.kind==="custom",Ou=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,KA=t=>{let e=Ou(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},GA='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function QA(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let s=o;typeof s.matches=="function"&&s.matches(GA)||o.childNodes.forEach(n)};return n(t),e.trim()}var XA=t=>QA(t).length===0;function Eb(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(S,W)=>{let R=S.button;if(!R)return;R.setAttribute("role","menuitem"),R.setAttribute("tabindex","-1"),R.className="persona-composer-overflow-menu__item";for(let U of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])R.style[U]="";R.style.lineHeight="1",W.tooltipText?R.setAttribute("title",W.tooltipText):R.removeAttribute("title"),R.replaceChildren();let L=k("span","persona-composer-overflow-menu__icon");if(W.iconName){let U=ge(W.iconName,16,"currentColor",1.5);U&&L.appendChild(U)}let J=k("span","persona-composer-overflow-menu__label");J.textContent=W.shortLabel??W.label,R.append(L,J)},l=(S,W)=>{let R=S.button;if(!R)return;if(R.setAttribute("aria-label",W.label),W.pressed===void 0?R.removeAttribute("aria-pressed"):R.setAttribute("aria-pressed",W.pressed?"true":"false"),R.toggleAttribute(Bu,W.disableWhenStreaming===!0),S.mode==="menu"){S.tooltip?.destroy(),S.tooltip=void 0,i(S,W);return}R.removeAttribute("role"),R.removeAttribute("tabindex"),R.removeAttribute("title");let L=s(),J=!!W.shortLabel;if(R.className=_n("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Nn,co,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),R.style.width=L&&!J?L:"",R.style.height=L??"",R.style.minWidth=L&&!J?L:"",R.style.minHeight=L??"",R.style.fontSize=J?"":"18px",R.style.lineHeight="1",R.style.color=W.iconColor??"",R.style.backgroundColor=W.backgroundColor??"",R.replaceChildren(),W.iconName){let U=ge(W.iconName,pn,"currentColor",1.5);U&&R.appendChild(U)}if(J){let U=k("span","persona-composer-action-button__label");U.textContent=W.shortLabel,R.appendChild(U)}else R.firstChild||(R.textContent=W.label);S.tooltip?.destroy(),S.tooltip=Qt({anchor:R,trigger:S.element,text:()=>W.tooltipText??W.label,enabled:!!W.tooltipText})},c=(S,W)=>{let R=S.action,L=G("button",{attrs:{type:"button"}}),J=L;if(W==="bar"){let re=k("div","persona-send-button-wrapper");re.appendChild(L),J=re}J.setAttribute(Sb,S.id);let U={resolved:S,element:J,button:L,owned:!0,managed:!0,busy:!1,visible:!0,mode:W},ae=re=>{if(re.preventDefault(),re.stopPropagation(),U.busy||L.disabled)return;let ue=U.resolved.action;U.mode==="menu"&&h?.close(!0);let Ee;try{Ee=ue.onSelect(t.actionContext,re)}catch(he){t.reportError(he,{actionId:U.resolved.id});return}!Ee||typeof Ee.then!="function"||(U.busy=!0,L.setAttribute("aria-busy","true"),Ee.catch(he=>{t.reportError(he,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,L.removeAttribute("aria-busy")}))};return L.addEventListener("click",ae),U.detach=()=>L.removeEventListener("click",ae),l(U,R),U},d=S=>{let W=S.action,R;try{R=W.render({...t.actionContext,id:S.id,action:W})}catch(L){return t.reportError(L,{actionId:S.id}),null}return R?.element?(R.element.setAttribute(Sb,S.id),R.element.toggleAttribute(Bu,W.disableWhenStreaming===!0),{resolved:S,element:R.element,owned:!0,managed:!0,destroy:R.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(S,W)=>{if(S.builtIn){let L=S.builtIn.element;return L?{resolved:S,element:L,owned:!1,managed:S.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let R=S.action;return R?Tr(R)?d(S):c(S,W):null},g=S=>{if(S.detach?.(),S.tooltip?.destroy(),S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0,S.owned){try{S.destroy?.()}catch(W){t.reportError(W,{actionId:S.resolved.id})}S.element.remove()}},m=(S,W)=>{for(let R=0;R<W.length;R++){let L=W[R];if(!L.managed)continue;let J=null;for(let U=R+1;U<W.length;U++){let ae=W[U];if(!ae.managed&&ae.element.parentElement===S){J=ae.element;break}}J?(L.element.parentElement!==S||L.element.nextSibling!==J)&&S.insertBefore(L.element,J):S.lastChild!==L.element&&S.appendChild(L.element)}},b=(S,W)=>{if(S.button){S.button.disabled=W;return}if(!S.owned)return;let R=S.element;R.toggleAttribute("data-disabled",W),R.setAttribute("aria-disabled",W?"true":"false");let L=R instanceof HTMLButtonElement||R instanceof HTMLSelectElement||R instanceof HTMLInputElement||R instanceof HTMLTextAreaElement?R:R.querySelector("button, select, input, textarea");L&&(L.disabled=W)},h=null,x=null,T=null,M=0,O=()=>{let S=t.getOverflow?.();return S?.enabled===!0?S:void 0},I=()=>(h?h.setLabel(t.getOverflowLabel?.()??"More actions"):h=wb({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),h),z=S=>{x!==S&&(T?.disconnect(),x=S,M=Du(S),!(typeof ResizeObserver>"u")&&(T=new ResizeObserver(W=>{let L=W[W.length-1]?.contentRect?.width??Du(S);L!==M&&(M=L,ie())}),T.observe(S)))},A=(S,W)=>{let R=$A(S.collapseAutoActionsBelow,W);if(R===null)return!1;let L=M||Du(W);return L>0&&L<R},H=(S,W,R)=>{if(!W)return"bar";if(S.resolved.builtIn){let J=UA(S.resolved.id);return J&&W.includeBuiltIns?.includes(J)?"menu":"bar"}let L=S.resolved.presentation;return L==="overflow"||L==="auto"&&R?"menu":"bar"},w=S=>{let W=S.menuSlot;if(!W)return;if(!XA(S.element)){S.menuLabel?.remove(),S.menuLabel=void 0;return}let R=KA(S.element);if(!R){S.menuLabel?.remove(),S.menuLabel=void 0;return}S.menuLabel||(S.menuLabel=k("span","persona-composer-overflow-menu__label")),S.menuLabel.textContent!==R&&(S.menuLabel.textContent=R),S.menuLabel.parentElement!==W&&W.appendChild(S.menuLabel)},D=(S,W)=>{if(S.mode===W)return S;let R=S.resolved.action;if(R&&!Tr(R)){g(S),e.delete(S.resolved.id);let L=c(S.resolved,W);return e.set(S.resolved.id,L),L}if(W==="menu"){let L=G("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Tu]:""}});L.appendChild(S.element),ub(Ou(S.element)),S.menuSlot=L;let J=U=>{let ae=Ou(S.element);if(ae.disabled)return;let re=U.target===ae||ae.contains(U.target);h?.close(!0),re||ae.click()};L.addEventListener("click",J,!0),S.detachMenuSlot=()=>L.removeEventListener("click",J,!0),S.managed=!0,w(S)}else S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0;return S.mode=W,S},K=(S,W)=>{let R=W.map(L=>L.menuSlot??L.element);for(R.forEach((L,J)=>{let U=S.children[J];U!==L&&(U?S.insertBefore(L,U):S.appendChild(L))});S.children.length>R.length;)S.lastElementChild?.remove()},ie=()=>{if(o)return;let S=t.getBindings();if(!S)return;let W=t.getState(),R=W.phase==="streaming",L=O();L&&z(S.footer);let J=L?A(L,S.footer):!1,U={start:[],end:[]},ae=[];for(let re of n){let ue=e.get(re.id);if(!ue)continue;let Ee=re.action,he=Ee?Mb(Ee.visible,W,!0)&&VA(Ee.visibility,W):!0;if(ue.visible!==he&&(ue.visible=he,!he&&ue.managed&&(ue.menuSlot??ue.element).remove()),!!he){if(ue=D(ue,H(ue,L,J)),Ee){let ce=Mb(Ee.disabled,W,!1)||Ee.disableWhenStreaming===!0&&R;b(ue,ce),!Tr(Ee)&&Ee.pressed!==void 0&&ue.button?.setAttribute("aria-pressed",Ee.pressed?"true":"false")}ue.mode==="menu"?(w(ue),ae.push(ue)):U[re.placement].push(ue)}}if(ae.length>0){let re=I();K(re.panel,ae),re.setItems(ae.map(ce=>ce.menuSlot??ce.element)),re.applyButtonSize();let ue=Number.isFinite(L?.order)?L?.order:Eo.overflow,Ee=U.start.findIndex(ce=>ce.resolved.order>ue),he={resolved:{id:FA,placement:"start",presentation:"bar",order:ue,sequence:-1,source:"core"},element:re.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(Ee<0?U.start.length:Ee,0,he)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(S.actionsStart,U.start),m(S.actionsEnd,U.end)};return{resolve:()=>{if(o)return;let S=zA(t.collect()),W=new Set(S.map(R=>R.id));for(let[R,L]of e)W.has(R)||(g(L),e.delete(R));for(let R of S){let L=e.get(R.id);if(!L){let re=u(R,"bar");re&&e.set(R.id,re);continue}let J=L.resolved.action,U=R.action;if(!!J!=!!U||J&&U&&Tr(J)!==Tr(U)||J&&U&&Tr(J)&&Tr(U)&&J.render!==U.render){g(L),e.delete(R.id);let re=u(R,L.mode);re&&e.set(R.id,re);continue}L.resolved=R,R.builtIn?(L.managed=R.builtIn.managed===!0||L.mode==="menu",R.builtIn.element&&L.mode==="bar"&&(L.element=R.builtIn.element)):U&&!Tr(U)?l(L,U):U&&L.element.toggleAttribute(Bu,U.disableWhenStreaming===!0)}n=S,ie()},sync:ie,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,T?.disconnect(),T=null,x=null;for(let S of e.values())g(S);e.clear(),h?.destroy(),h=null,n=[]}}}}var YA="core:model",JA=700,Tb=16,ZA=["--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"],kb=()=>{let t=G("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=G("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Pb(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=d=>{let u=t.getSelectedModelId();return d.find(g=>g.id===u)??d[0]},i=()=>{let d=G("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),u="",g=()=>{let T=t.getModels(),M=T.map(O=>`${O.id}:${O.label}`).join("|");M!==u&&(u=M,d.replaceChildren(...T.map(O=>{let I=G("option",{attrs:{value:O.id}});return I.textContent=O.label,I}))),d.value=s(T)?.id??""};g(),o=g;let m=()=>{d.value&&t.onSelect(d.value)};d.addEventListener("change",m);let b=T=>T.stopPropagation();d.addEventListener("click",b);let{wrapper:h,chevron:x}=kb();return h.append(d,x),{element:h,destroy:()=>{o===g&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",b)}}},l=()=>{let d=G("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=k("span","persona-composer-model-picker-label"),g=k("span","persona-composer-model-picker-suffix");d.append(u,g);let m=G("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),b=new Map,h="",x=null,T=()=>x?.isOpen===!0,M=(W=!1)=>{T()&&(x?.close(),d.setAttribute("aria-expanded","false"),W&&d.focus())},O=W=>{let R=[...b.values()];if(R.length===0)return;let L=(W%R.length+R.length)%R.length;R[L].focus()},I=W=>{if(T())return;x||(x=gc({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),Dc(d,m,ZA),x.open(),d.setAttribute("aria-expanded","true");let L=[...b.keys()].indexOf(s(t.getModels())?.id??"");O(W??(L>=0?L:0))},z=W=>{M(!0),t.onSelect(W)},A=W=>{W.preventDefault(),W.stopPropagation();let R=W.currentTarget.getAttribute("data-persona-model-option");R&&z(R)},H=W=>{let R=G("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":W.id}});if(W.icon){let re=ge(W.icon,Tb,"currentColor",1.5);if(re){let ue=k("span","persona-composer-model-option-icon");ue.appendChild(re),R.appendChild(ue)}}let L=k("span","persona-composer-model-option-body"),J=k("span","persona-composer-model-option-label");if(J.textContent=W.label,L.appendChild(J),W.description){let re=k("span","persona-composer-model-option-description");re.textContent=W.description,L.appendChild(re)}R.appendChild(L);let U=k("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let ae=ge("check",Tb,"currentColor",2);return ae&&U.appendChild(ae),R.appendChild(U),R.addEventListener("click",A),R},w=()=>{let W=t.getModels(),R=W.map(U=>`${U.id}:${U.label}:${U.icon??""}:${U.description??""}`).join("|");if(R!==h){h=R;for(let U of b.values())U.removeEventListener("click",A);b.clear(),m.replaceChildren(...W.map(U=>{let ae=H(U);return b.set(U.id,ae),ae}))}let L=s(W);for(let[U,ae]of b)ae.setAttribute("aria-selected",String(U===L?.id));u.textContent=L?.label??"";let J=t.getSuffix?.()??"";g.textContent=J,d.setAttribute("aria-label",[e,[L?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};w(),o=w;let D=W=>{W.preventDefault(),W.stopPropagation(),T()?M(!0):I()},K=W=>{if(W.key==="ArrowDown"){W.preventDefault(),T()?O(0):I(0);return}W.key==="ArrowUp"&&(W.preventDefault(),T()?O(-1):I(-1))},ie=W=>{let R=[...b.values()],L=R.indexOf(W.target?.closest?.(".persona-composer-model-option"));switch(W.key){case"ArrowDown":W.preventDefault(),O(L+1);return;case"ArrowUp":W.preventDefault(),O(L-1);return;case"Home":W.preventDefault(),O(0);return;case"End":W.preventDefault(),O(R.length-1);return;case"Escape":W.preventDefault(),W.stopPropagation(),M(!0);return;case"Tab":M(!0);return;default:}};d.addEventListener("click",D),d.addEventListener("keydown",K),m.addEventListener("keydown",ie);let{wrapper:Z,chevron:S}=kb();return Z.append(d,S),{element:Z,destroy:()=>{o===w&&(o=null),d.removeEventListener("click",D),d.removeEventListener("keydown",K),m.removeEventListener("keydown",ie);for(let W of b.values())W.removeEventListener("click",A);b.clear(),x?.destroy(),x=null,m.remove()}}};return{action:{id:YA,kind:"custom",placement:"end",order:JA,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var eM=":scope > [data-persona-composer-mode]";function Ib(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=u=>{let g=G("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let x=k("span","persona-mention-chip-icon"),T=ge(u.iconName,12,"currentColor",1.5);T&&x.appendChild(T),g.appendChild(x)}let m=k("span","persona-mention-chip-label");m.textContent=u.shortLabel??u.label,g.appendChild(m);let b=G("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),h=ge("x",12,"currentColor",2);return h?b.appendChild(h):b.textContent="\xD7",b.addEventListener("click",x=>{x.preventDefault(),x.stopPropagation(),t.onRemove(u.id)}),g.appendChild(b),g},l=()=>Array.from(e.querySelectorAll(eM)),c=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let g=()=>{u.remove(),fc(e)},m=e.ownerDocument.defaultView,b=typeof m?.getComputedStyle=="function"?m.getComputedStyle(u).animationName:"";if(!b||b==="none"){g();return}u.addEventListener("animationend",g,{once:!0}),u.addEventListener("animationcancel",g,{once:!0})},d=()=>{for(let u of l())u.remove()};return{element:e,render:(u,g)=>{if(o)return;let m=g.filter(T=>u.includes(T.id)),b=m.map(T=>`${T.id}:${T.shortLabel??T.label}`).join("|");if(b===n)return;n=b;let h=new Map;for(let T of l()){let M=T.getAttribute("data-persona-composer-mode");M&&m.some(I=>I.id===M)&&!T.hasAttribute("data-persona-chip-exit")?h.set(M,T):T.hasAttribute("data-persona-chip-exit")||c(T)}let x=e.firstChild;for(let T of m){let M=h.get(T.id);M||(M=i(T),s.has(T.id)||(M.setAttribute("data-persona-chip-enter",""),M.addEventListener("animationend",()=>M?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(T.id),M!==x&&e.insertBefore(M,x),x=M.nextSibling}fc(e)},destroy:()=>{o=!0,d(),fc(e)}}}var Lb=t=>`core:mode:${t}`;var _u=t=>Math.min(300+t,499),Hb=t=>`core:mode-group:${t}`;function $c(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function tM(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Rb(t,e){return t?.length?t.filter(n=>!$c(n.groupId,e)&&!tM(n.groupId,e)):[]}var nM=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Wb(t,e,n,o){let s=n.find(c=>c.id===e);if(!s)return[...t];let i=t.includes(e),l=new Set(t);if(i)l.delete(e);else{if(nM(s,o)==="single"){let c=n.filter(d=>d.groupId===s.groupId).map(d=>d.id);l=new Set([...l].filter(d=>!c.includes(d)))}l.add(e)}return n.filter(c=>l.has(c.id)).map(c=>c.id)}function qc(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Bb(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Db(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var oM=16;function Ob(t){let e=null;return{action:{id:Hb(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=G("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=u=>{u.preventDefault(),u.stopPropagation();let m=u.currentTarget.getAttribute("data-persona-composer-mode");!m||t.getActiveIds().includes(m)&&t.getGroup()?.selection==="single"||t.onSelect(m)},c=u=>{let g=G("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let b=ge(u.iconName,oM,"currentColor",1.5);b&&g.appendChild(b)}let m=k("span","persona-composer-segmented-label");return m.textContent=u.shortLabel??u.label,g.appendChild(m),g.addEventListener("click",l),g},d=()=>{let u=t.getGroup();u?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",u.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let g=t.getModes(),m=g.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==i){i=m;for(let x of s.values())x.removeEventListener("click",l);s.clear();let h=g.map(x=>{let T=c(x);return s.set(x.id,T),T});o.replaceChildren(...h)}let b=t.getActiveIds();for(let[h,x]of s)x.setAttribute("aria-pressed",String(b.includes(h)))};return d(),e=d,{element:o,destroy:()=>{e===d&&(e=null);for(let u of s.values())u.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function _b(t){let e=G("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,s=i=>{let l=k("span","persona-composer-quote-bar"),c=k("div","persona-composer-quote-content");if(i.sourceLabel){let m=k("div","persona-composer-quote-source");m.textContent=i.sourceLabel,c.appendChild(m)}let d=G("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=Ec(i.text),c.appendChild(d);let u=G("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),g=ge("x",12,"currentColor",2);g?u.appendChild(g):u.textContent="\xD7",u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),t.onDismiss()}),e.replaceChildren(l,c,u)};return{element:e,render:i=>{if(o)return;let l=i?`${i.sourceLabel??""}\0${i.text}`:"";if(l!==n){if(n=l,!i){e.replaceChildren(),e.style.display="none";return}s(i),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function Nb(t){let e=G("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,d,u)=>{let g=G("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[d]:""}}),m=ge(l,12,"currentColor",2);return m?g.appendChild(m):g.textContent=c,g.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),u()}),g},i=l=>{let c=Ec(l.text??"",90);if(c)return c;let d=l.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(l.mentionRefs?.length??0)>0?l.mentionRefs.map(g=>g.label).join(", "):"Queued message"};return{element:e,render:l=>{if(o||l===n)return;if(n=l,!l){e.replaceChildren(),e.style.display="none";return}let c=k("span","persona-composer-pending-badge");c.textContent=t.label??"Sends next";let d=G("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});d.textContent=i(l),e.replaceChildren(c,d,s("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),s("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function Fb(t){let e=G("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=G("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let s=k("div","persona-message-edit-actions"),i=(c,d,u,g)=>{let m=G("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[u]:""},text:c});return m.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),g()}),m},l=()=>{let c=n.value.trim();c&&t.onSave(c)};return s.append(i(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),i(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",l)),n.addEventListener("keydown",c=>{if(c.key==="Escape"){c.preventDefault(),c.stopPropagation(),t.onCancel();return}c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),l())}),e.append(n,s),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let c=n.value.length;n.setSelectionRange(c,c),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function Ub(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function $b(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(d=>n.has(d.sourceId)),s=o.length===(t.mentionRefs?.length??0)&&o.length>0,i=new Set(e.modes.map(d=>d.id)),l=(t.activeModeIds??[]).filter(d=>i.has(d)),c=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...s?{mentionRefs:o}:{},...s&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...c?{selectedModelId:c}:{},...l.length?{activeModeIds:l}:{},...t.quote?.text?{quote:t.quote}:{}}}function qb(t){let e=t.delay??500,n=null,o=!1,s=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(s(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(s(),t.write())},cancel:s,destroy:()=>{o=!0,s()}}}function zb(t){return t.wrapped||t.text.includes(`
|
|
17
|
-
`)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function jb(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function Vb(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),s=Number.parseFloat(n.fontSize),i=Number.isFinite(o)&&o>0?o:Number.isFinite(s)&&s>0?s*1.4:0;if(!i)return!1;let l=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-l>i*1.5}function Nu(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function Gb(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var rM=t=>typeof t?.then=="function";function Kb(t,e){return e===!1?{status:"canceled"}:!e||typeof e!="object"?{status:"proceed"}:(typeof e.text=="string"&&(t.text=e.text),e.options&&(t.options={...t.options,...e.options}),{status:"proceed"})}function Qb(t,e,n){let o;try{o=t(Nu(e),{signal:n})}catch(s){return{status:"error",error:s}}return rM(o)?Promise.resolve(o).then(s=>n.aborted?{status:"aborted"}:Kb(e,s),s=>n.aborted?{status:"aborted"}:{status:"error",error:s}):Kb(e,o)}function Xb(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",s=e.buttonTooltipText??"Add context",i=k("div","persona-send-button-wrapper"),l=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Nn} ${
|
|
18
|
-
`).some(
|
|
19
|
-
`)[0]).startsWith(H.trigger):!1),i=(A,H)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:H}))}catch{}},l=!t.chipRow,c=t.chipRow??G("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,u=null,g=t.textarea,m=null,b=null,h=null,x=null,T=()=>{if(d)return Promise.resolve(d);if(u)return u;let A=Fu().then(H=>(H.setMentionIconRenderer(ge),d=H.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:m??void 0,anchor:t.anchor,contextRow:c,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:z,emit:i}),d)).catch(H=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",H),u===A&&(u=null),null));return u=A,A},M=()=>{Yb().then(A=>{let H=A.mountInlineComposer({textarea:t.textarea,renderToken:D=>Pa(D,{render:e.renderMentionToken}),onMentionRemoved:D=>d?.untrackMention(D)});m=H.input,b=H.destroy;let w=g;w.replaceWith(H.element),g=H.element,x={next:H.element,prev:w},h?.(H.element,w),d?d.rebindComposer(H.input):u&&u.then(D=>D?.rebindComposer(H.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&M();let O=[],I=new Map;for(let A of n){if(!A.showButton)continue;let H=Xb({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{T().then(w=>w?.openMenu(A.trigger))}});O.push(H),I.set(A.trigger,H.button)}let z=(A,H,w)=>{let D=I.get(H);D&&(D.setAttribute("aria-expanded",A?"true":"false"),A?D.setAttribute("aria-controls",w):D.removeAttribute("aria-controls"))};return{affordanceButtons:O.map(A=>A.wrapper),contextRow:c,handleInput:A=>{if(d){d.handleInput();return}if(!zh(A))return;let H=g,w=H.selectionStart??0;qh(H.value,w,n)&&T().then(D=>D?.handleInput())},handleKeydown:A=>{if(d?.isMenuOpen())return d.handleKeydown(A);if(A.key==="Backspace"&&d?.hasMentions()&&!x){let H=g,w=H.selectionStart===0&&H.selectionEnd===0;if((H.value.length===0||w)&&d.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async A=>s(A)?(d??await T())?.dispatchInlineCommand(A)??null:null,clear:()=>d?.clear(),prefetch:()=>{Fu().catch(()=>{})},onComposerSwap:A=>{h=A,x&&A(x.next,x.prev)},destroy:()=>{d?.destroy(),b?.();for(let A of O)A.wrapper.remove();l&&c.remove()}}}var zc="16px",jc="transparent",aM=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),lM={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:aM,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"}},cM={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"}},dM={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:Jo,maxWidth:hb,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:zc,canvasBackground:jc},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 un(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let s of n){if(o==null)return;o=o[s]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?un(t,o):o}function ev(t){let e={};function n(o,s){for(let[i,l]of Object.entries(o)){let c=`${s}.${i}`;if(typeof l=="string"){let d=un(t,l);d!==void 0&&(e[c]={path:c,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof l=="object"&&l!==null&&n(l,c)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function pM(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function tv(t,e){let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];i&&typeof i=="object"&&!Array.isArray(i)&&s&&typeof s=="object"&&!Array.isArray(s)?n[o]=tv(i,s):n[o]=s}return n}function uM(t,e){return e?tv(t,e):t}function ci(t,e={}){let n={palette:lM,semantic:cM,components:dM},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:uM(n.components,t?.components)};if(e.validate!==!1){let s=pM(o);if(!s.valid)throw new Error(`Theme validation failed: ${s.errors.map(i=>i.message).join(", ")}`)}if(e.plugins)for(let s of e.plugins)o=s.transform(o);return o}var Uu=t=>t.trim()==="0"?"0px":t,Zb="--persona-",gM=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let l=e.slice(1);if(!/^[0-9a-f]+$/.test(l))return;l.length===3||l.length===4?n=[0,1,2].map(c=>parseInt(l[c]+l[c],16)):(l.length===6||l.length===8)&&(n=[0,2,4].map(c=>parseInt(l.slice(c,c+2),16)))}else{let l=e.match(/^rgba?\(([^)]+)\)$/);if(l){let c=l[1].split(/[,/\s]+/).filter(Boolean);c.length>=3&&(n=c.slice(0,3).map(d=>{let u=d.endsWith("%"),g=parseFloat(u?d.slice(0,-1):d);return u?g/100*255:g}))}}if(!n||n.some(l=>!Number.isFinite(l)))return;let[o,s,i]=n.map(l=>{let c=Math.max(0,Math.min(255,l))/255;return c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4)});return .2126*o+.7152*s+.0722*i},fM=.179,Xt=(t,e)=>{for(let[n,...o]of e){let s;for(let i of o)if(s=i.charCodeAt(0)===61?i.slice(1):t[Zb+i],s!==void 0)break;s!==void 0&&(t[Zb+n]=s)}};function nv(t){let e=ev(t),n={};for(let[N,Te]of Object.entries(e)){let Ue=N.replace(/\./g,"-");n[`--persona-${Ue}`]=Te.value}Xt(n,[["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 o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],Xt(n,[["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"]]),Xt(n,[["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"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,Xt(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??zc,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??jc,Xt(n,[["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"]]),Xt(n,[["header-bg","components-header-background","surface"]]);let s=n["--persona-header-bg"],i=n["--persona-components-header-foreground"],l=i?`color-mix(in srgb, ${i} 72%, ${s})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(i?`color-mix(in srgb, ${i} 14%, ${s})`:void 0)??n["--persona-divider"],Xt(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??i??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??l??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??l??n["--persona-muted"],Xt(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let c=t.components?.header;c?.shadow&&(n["--persona-header-shadow"]=c.shadow),c?.borderBottom&&(n["--persona-header-border-bottom"]=c.borderBottom),c?.minHeight&&(n["--persona-header-min-height"]=c.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let u=n["--persona-components-history-railHeader-border"];u&&(n["--persona-history-rail-header-border"]=u);let g=n["--persona-components-history-railHeader-minHeight"];g&&(n["--persona-history-rail-header-min-height"]=g);for(let[N,Te]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ue=n[`--persona-components-history-overlay-${N}`];Ue&&(n[`--persona-history-overlay-${Te}`]=Ue)}for(let[N,Te]of[["background","bg"],["borderRadius","radius"]]){let Ue=n[`--persona-components-history-menu-${N}`];Ue&&(n[`--persona-history-menu-${Te}`]=Ue)}let m=t.components?.history?.motion;if(m){let N=qt=>{if(qt===void 0)return;let Le=String(qt).trim();return/^\d+(\.\d+)?$/.test(Le)?`${Le}ms`:Le},Te=N(m.enterDurationMs);Te!==void 0&&(n["--persona-history-enter-ms"]=Te);let Ue=N(m.exitDurationMs);Ue!==void 0&&(n["--persona-history-exit-ms"]=Ue),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let b=n["--persona-components-history-dangerForeground"];b&&(n["--persona-history-danger-fg"]=b),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let N of["scrim","shadow"]){let Te=n[`--persona-components-history-confirm-${N}`];Te&&(n[`--persona-history-confirm-${N}`]=Te)}for(let[N,Te]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ue=n[`--persona-components-tooltip-${N}`];Ue&&(n[`--persona-tooltip-${Te}`]=Ue)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[N,Te]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ue=n[`--persona-components-messageActions-${N}`];Ue&&(n[`--persona-message-action-${Te}`]=Ue)}Xt(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],x=n["--persona-components-introCard-shadow"],T=(!h||h==="transparent"||h==="none")&&(!x||x==="none"),M=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=T&&M==="1.5rem"?"1.5rem 0":M,Xt(n,[["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"]]),Xt(n,[["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 O=n["--persona-components-markdown-heading-h1-fontSize"];O&&(n["--persona-md-h1-size"]=O);let I=n["--persona-components-markdown-heading-h1-fontWeight"];I&&(n["--persona-md-h1-weight"]=I);let z=n["--persona-components-markdown-heading-h2-fontSize"];z&&(n["--persona-md-h2-size"]=z);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let H=n["--persona-components-markdown-prose-fontFamily"];H&&H!=="inherit"&&(n["--persona-md-prose-font-family"]=H),Xt(n,[["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"]]),Xt(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Xt(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Xt(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Xt(n,[["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"]]),n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],Xt(n,[["message-border","components-message-border","border"]]),Xt(n,[["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 w=t.components,D=w?.iconButton;D&&(D.background&&(n["--persona-icon-btn-bg"]=D.background),D.border&&(n["--persona-icon-btn-border"]=D.border),D.color&&(n["--persona-icon-btn-color"]=D.color),D.padding&&(n["--persona-icon-btn-padding"]=D.padding),D.borderRadius&&(n["--persona-icon-btn-radius"]=D.borderRadius),D.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=D.hoverBackground),D.hoverColor&&(n["--persona-icon-btn-hover-color"]=D.hoverColor),D.activeBackground&&(n["--persona-icon-btn-active-bg"]=D.activeBackground),D.activeBorder&&(n["--persona-icon-btn-active-border"]=D.activeBorder));let K=w?.labelButton;K&&(K.background&&(n["--persona-label-btn-bg"]=K.background),K.border&&(n["--persona-label-btn-border"]=K.border),K.color&&(n["--persona-label-btn-color"]=K.color),K.padding&&(n["--persona-label-btn-padding"]=K.padding),K.borderRadius&&(n["--persona-label-btn-radius"]=K.borderRadius),K.hoverBackground&&(n["--persona-label-btn-hover-bg"]=K.hoverBackground),K.fontSize&&(n["--persona-label-btn-font-size"]=K.fontSize),K.gap&&(n["--persona-label-btn-gap"]=K.gap));let ie=w?.toggleGroup;ie&&(ie.gap&&(n["--persona-toggle-group-gap"]=ie.gap),ie.borderRadius&&(n["--persona-toggle-group-radius"]=ie.borderRadius));let Z=w?.artifact;if(Z?.toolbar){let N=Z.toolbar;N.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=N.iconHoverColor),N.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=N.iconHoverBackground),N.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=N.iconPadding),N.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=N.iconBorderRadius),N.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=N.iconBorder),N.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Uu(N.toggleGroupGap)),N.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=N.toggleBorderRadius),N.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Uu(N.toggleGroupPadding)),N.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=N.toggleGroupBorder),N.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=N.toggleGroupBorderRadius),N.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=un(t,N.toggleGroupBackground)??N.toggleGroupBackground),N.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=N.copyBackground),N.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=N.copyBorder),N.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=N.copyColor),N.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Uu(N.copyBorderRadius)),N.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=N.copyPadding),N.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=N.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??N.copyMenuBackground),N.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=N.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??N.copyMenuBorder),N.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=N.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??N.copyMenuShadow),N.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=N.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??N.copyMenuBorderRadius),N.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=N.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??N.copyMenuItemHoverBackground),N.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=N.iconBackground),N.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=N.toolbarBorder)}if(Z?.tab){let N=Z.tab;N.background&&(n["--persona-artifact-tab-bg"]=N.background),N.activeBackground&&(n["--persona-artifact-tab-active-bg"]=N.activeBackground),N.activeBorder&&(n["--persona-artifact-tab-active-border"]=N.activeBorder),N.borderRadius&&(n["--persona-artifact-tab-radius"]=N.borderRadius),N.textColor&&(n["--persona-artifact-tab-color"]=N.textColor),N.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=N.hoverBackground),N.listBackground&&(n["--persona-artifact-tab-list-bg"]=N.listBackground),N.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=N.listBorderColor),N.listPadding&&(n["--persona-artifact-tab-list-padding"]=N.listPadding)}if(Z?.pane){let N=Z.pane;if(N.toolbarBackground){let Te=un(t,N.toolbarBackground)??N.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Te}}if(Z?.card){let N=Z.card;N.background&&(n["--persona-artifact-card-bg"]=N.background),N.border&&(n["--persona-artifact-card-border"]=N.border),N.borderRadius&&(n["--persona-artifact-card-radius"]=N.borderRadius),N.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=N.hoverBackground),N.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=N.hoverBorderColor)}if(Z?.inline){let N=Z.inline;N.background&&(n["--persona-artifact-inline-bg"]=un(t,N.background)??N.background),N.border&&(n["--persona-artifact-inline-border"]=N.border),N.borderRadius&&(n["--persona-artifact-inline-radius"]=N.borderRadius),N.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=un(t,N.chromeBackground)??N.chromeBackground),N.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=un(t,N.chromeBorder)??N.chromeBorder),N.titleColor&&(n["--persona-artifact-inline-title-color"]=un(t,N.titleColor)??N.titleColor),N.mutedColor&&(n["--persona-artifact-inline-muted-color"]=un(t,N.mutedColor)??N.mutedColor),N.frameHeight&&(n["--persona-artifact-inline-frame-height"]=N.frameHeight)}let S=w?.code;S&&(S.keywordColor&&(n["--persona-code-keyword-color"]=S.keywordColor),S.stringColor&&(n["--persona-code-string-color"]=S.stringColor),S.commentColor&&(n["--persona-code-comment-color"]=S.commentColor),S.numberColor&&(n["--persona-code-number-color"]=S.numberColor),S.tagColor&&(n["--persona-code-tag-color"]=S.tagColor),S.attrColor&&(n["--persona-code-attr-color"]=S.attrColor),S.propertyColor&&(n["--persona-code-property-color"]=S.propertyColor),S.lineNumberColor&&(n["--persona-code-line-number-color"]=S.lineNumberColor),S.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=S.gutterBorderColor),S.background&&(n["--persona-code-bg"]=un(t,S.background)??S.background));let W=n["--persona-surface"],R=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",J=n["--persona-palette-colors-gray-200"]??"#e5e7eb",U=n["--persona-palette-colors-gray-300"]??"#d1d5db",ae=!R||R===W,re=gM(W??n["--persona-background"]),ue=ae&&re!==void 0&&re<fM,Ee=ue?"rgba(255, 255, 255, 0.08)":L,he=ue?"rgba(255, 255, 255, 0.12)":J,ce=ue?"rgba(255, 255, 255, 0.16)":U,at=ae?Ee:R,ye=ae?he:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??at,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ye,ae&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ce),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??at,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??at,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??at,n}var mM={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"}}},hM={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)"}}}},ov=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},$u=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",yM=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":$u()},rv=t=>yM(t),bM=t=>ci(t),vM=t=>{let e=ai(hM,t??{})??{};return ci({...e,palette:{...e.palette,colors:{...mM.colors,...e.palette?.colors}}},{validate:!1})},di=t=>{let e=rv(t),n=ov(t?.theme),o=ov(t?.darkTheme);return e==="dark"?vM(ai(n??{},o??{})):bM(n)},CM=t=>nv(t),Ia=(t,e)=>{let n=di(e),o=CM(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",rv(e))},Vc=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t($u())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t($u());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};import{Activity as MC,Check as EC,Copy as TC}from"lucide";var kr=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Kc="24px",qu=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",La=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},sv=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var iv=null;var zu=()=>{if(iv!==null)return iv;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},wM="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Gc=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},Qc=t=>{let e=t.toLowerCase().split("+").map(s=>s.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let s of e)if(s==="mod"||s==="cmd"||s==="ctrl")o.mod=!0;else if(s==="shift")o.shift=!0;else if(s==="alt"||s==="option")o.alt=!0;else return Gc("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Gc("unsupported",t),null):(n==="space"&&(o.key=" "),o)},SM=t=>wM.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),av=(t,e)=>{let n=Qc(t);if(!n)return"";let o=zu(),s=SM(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${s}`;let i=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&i.push("Alt"),n.shift&&i.push("Shift"),i.push(s),i.join("+")},Xc=t=>av(t,!1),Ha=t=>av(t,!0),xM=(t,e)=>e.key?.toLowerCase()===t.key&&(zu()?e.metaKey:e.ctrlKey)===t.mod&&!(zu()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,AM=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},lv=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(i,l)=>{if((i.scope??"widget")==="page")return!0;if(!t)return!1;let c=l.composedPath?.();return c?.length?c.includes(t):t.contains(l.target)},s=i=>{if(i.isComposing||!e.size)return;let l=i.composedPath?.()[0]??i.target;for(let c of e.values())if(xM(c.parsed,i)&&c.when?.()!==!1&&o(c,i)&&!(!c.allowInInput&&AM(l))){i.preventDefault();try{c.run(i)}catch(d){Gc(`${c.id} threw on`,c.combo),console.warn(d)}return}};return n?.addEventListener("keydown",s),{register(i){let l=Qc(i.combo);if(!l)return()=>{};let c=`${l.mod?"m":""}${l.shift?"s":""}${l.alt?"a":""}${l.key}`,d=e.get(c);return d?(Gc(`${d.id} already owns`,i.combo),()=>{}):(e.set(c,{...i,parsed:l}),i.element?.setAttribute("aria-keyshortcuts",Ha(i.combo)),()=>{e.get(c)?.id===i.id&&e.delete(c),i.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",s)}}};import{Idiomorph as MM}from"idiomorph";var Yc=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;MM.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,i){if(s instanceof HTMLElement&&o){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-tool-elapsed"))return i instanceof HTMLElement&&i.getAttribute("data-tool-elapsed")===s.getAttribute("data-tool-elapsed")?!1:void 0;if(s.hasAttribute("data-preserve-animation")){if(i instanceof HTMLElement&&!i.hasAttribute("data-preserve-animation"))return;if(i instanceof HTMLElement&&i.hasAttribute("data-preserve-animation")){let l=s.textContent??"",c=i.textContent??"";if(l!==c)return}return!1}}}}})};var cv=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var ju={index:-1,draft:""};function dv(t){let{direction:e,history:n,currentValue:o,atStart:s,state:i}=t,l=i.index!==-1;if(n.length===0)return{handled:!1,state:i};if(e==="up"){if(!l&&!s)return{handled:!1,state:i};if(!l){let c=n.length-1;return{handled:!0,value:n[c],state:{index:c,draft:o}}}if(i.index>0){let c=i.index-1;return{handled:!0,value:n[c],state:{index:c,draft:i.draft}}}return{handled:!0,state:i}}if(!l)return{handled:!1,state:i};if(i.index<n.length-1){let c=i.index+1;return{handled:!0,value:n[c],state:{index:c,draft:i.draft}}}return{handled:!0,value:i.draft,state:{index:-1,draft:i.draft}}}function pv(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function uv(){return new Map}function gv(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function fv(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function mv(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:oI,load:EM}=Tt({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var hv=EM;function Vu(t,e=an){let n=t.style.position,o=t.style.zIndex,s=t.style.isolation,i=getComputedStyle(t),l=i.position==="static"||i.position==="";return l&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{l&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=s}}var Ra=0,Pr=null;function Ku(t=document){if(Ra++,Ra===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Pr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,Ra=Math.max(0,Ra-1),Ra===0&&Pr)){let n=t.body,o=t.defaultView??window;n.style.overflow=Pr.originalOverflow,n.style.position=Pr.originalPosition,n.style.top=Pr.originalTop,n.style.width=Pr.originalWidth,o.scrollTo(0,Pr.scrollY),Pr=null}}}var Wa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=t=>(t?.launcher?.mountMode??"floating")==="docked",Ba=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Yn=t=>{let e=t?.launcher?.dock;return{side:e?.side??Wa.side,width:e?.width??Wa.width,animate:e?.animate??Wa.animate,reveal:e?.reveal??Wa.reveal,maxHeight:e?.maxHeight??Wa.maxHeight}};import{ArrowRight as TM}from"lucide";var Gu=t=>t==="followUp"?"follow-up":t,Qu=(t,e=0)=>{if(typeof t=="string"){let s=t.trim();return s?{id:s,label:s,prompt:s,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},kM=t=>{switch(t){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'}},yv=new WeakSet,PM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,IM=t=>{PM()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Xu=t=>{var z,A,H;let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:d,chipsConfig:u,session:g,getTextarea:m,eventTarget:b,submitPrompt:h}=t,x=o==="followUp",T=e.behavior,M=()=>{if(g.isStreaming())return;let w={suggestion:{...e},surface:o,source:s,behavior:T},D=b.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:w,bubbles:!0,composed:!0,cancelable:!0}));if(x&&b.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!D)return;for(let ie of d)if(ie.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let K=m();if(T==="fill"){K.value=e.prompt,K.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),K.focus();return}if(h){h(e.prompt);return}K.value="",g.sendMessage(e.prompt)},O=()=>{let w=k("button",`persona-suggestion persona-suggestion--${i}`);if(w.type="button",w.disabled=l,w.dataset.suggestionId=e.id,w.dataset.emphasis=e.emphasis,w.dataset.behavior=T,i==="chip"&&(u?.fontFamily&&(w.style.fontFamily=kM(u.fontFamily)),u?.fontWeight&&(w.style.fontWeight=u.fontWeight),u?.paddingX&&(w.style.paddingLeft=u.paddingX,w.style.paddingRight=u.paddingX),u?.paddingY&&(w.style.paddingTop=u.paddingY,w.style.paddingBottom=u.paddingY)),e.icon){let K=ge(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);K&&(K.classList.add("persona-suggestion__icon"),e.iconColor&&(K.style.color=e.iconColor),w.appendChild(K))}let D=k("span","persona-suggestion__copy");if(D.appendChild(G("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&D.appendChild(G("span",{className:"persona-suggestion__description",text:e.description})),w.appendChild(D),i!=="chip"){let K=en(TM,16,"currentColor",1.8);K&&(K.classList.add("persona-suggestion__arrow"),w.appendChild(K))}return w.addEventListener("click",M),w},I=null;for(let w of d)if(w.renderSuggestion&&(I=w.renderSuggestion({suggestion:{...e},index:n,surface:o,source:s,variant:i,streaming:l,config:c,defaultRenderer:O,select:M}),I))break;return I??(I=O()),(z=I.dataset).suggestionId||(z.suggestionId=e.id),(A=I.dataset).behavior||(A.behavior=T),(H=I.dataset).emphasis||(H.emphasis=e.emphasis),I instanceof HTMLButtonElement||I.setAttribute("aria-disabled",l?"true":"false"),I},Da=t=>{let e=[],n=[],o=null,s=null,i=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},l=()=>{if(s=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){i();return}let g=Math.max(0,t.scrollWidth-t.clientWidth);if(g<=1){i();return}let m=getComputedStyle(t).direction==="rtl",b=Math.min(g,Math.max(0,Math.abs(t.scrollLeft))),h=4,x=b<=h,T=b>=g-h,M=m?!T:!x,O=m?!x:!T;t.toggleAttribute("data-scroll-left",M),t.toggleAttribute("data-scroll-right",O)},c=()=>{if(s!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&l();return}s=requestAnimationFrame(l)};t.addEventListener("scroll",c,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(c):null;return d?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",c),d?.disconnect(),s!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(s),s=null},render:(g,m,b,h,x,T)=>{t.replaceChildren(),e.length=0,n.length=0;let M=T?.source??"config",O=T?.surface??(M==="config"?"starter":"followUp"),I=O==="followUp",z=T?.variant??"chip",A=T?.behavior??"send",H=T?.overflow??"wrap",w=T?.config??{},D=T?.plugins??[],K=typeof T?.maxItems=="number"?Math.max(0,Math.floor(T.maxItems)):void 0,ie=I?"followUps":"starters";!yv.has(w)&&w.debug===!0&&z!=="chip"&&w.suggestions?.[ie]?.overflow!==void 0&&(yv.add(w),console.info(`[persona] suggestions.${ie}.overflow applies to the "chip" variant only; the "${z}" variant manages its own stacking.`));let Z=U=>U.map(Qu).filter(ae=>ae!==null).map(ae=>({...ae,behavior:ae.behavior??A})),S=Z(g??[]);D.forEach(U=>{U.transformSuggestions&&(S=Z(U.transformSuggestions({suggestions:S.map(ae=>({...ae})),surface:O,source:M,config:w})))});let W=K===void 0?S:S.slice(0,K);if(!W.length){t.hidden=!0,o=null,i();return}if(!I&&(h??m.getMessages()).some(ae=>ae.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=Gu(O),t.dataset.variant=z,t.dataset.overflow=H;let R=document.createDocumentFragment(),L=m.isStreaming();W.forEach((U,ae)=>{let re=Xu({item:U,index:ae,surface:O,source:M,variant:z,streaming:L,config:w,plugins:D,chipsConfig:x,session:m,getTextarea:()=>b,eventTarget:t,submitPrompt:T?.submitPrompt});R.appendChild(re),n.push(re),[...re instanceof HTMLButtonElement?[re]:[],...Array.from(re.querySelectorAll("button"))].forEach(Ee=>{e.includes(Ee)||(Ee.disabled=L,e.push(Ee))})}),t.appendChild(R),l(),c();let J=JSON.stringify({normalized:W,surface:O,variant:z,source:M});J!==o&&(o=J,IM(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:W.map(U=>({...U})),surface:O,source:M,variant:z},bubbles:!0,composed:!0})),I&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:W.map(U=>U.prompt)},bubbles:!0,composed:!0})))}}};var Fn={"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 LM="persona-header-control",HM="persona-header-control--glyph",RM="persona-header-control--sparse",WM=20,BM={x:[1.4,1.05]},bv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",DM="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Jc=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=BM[e]??[1,1.5],c=!o;t.classList.toggle(HM,c),t.classList.toggle(RM,c&&i!==1);let d=parseFloat(o??"")||WM,u=ge(e,`${Math.round(d*i)}px`,"currentColor",l);u?(u.style.display="block",c||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((l/1.5).toFixed(4))})`),t.replaceChildren(u)):s&&(t.textContent=s)},gs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=bv,size:c,iconSize:d,color:u,backgroundColor:g,borderWidth:m,borderColor:b,borderRadius:h,paddingX:x,paddingY:T,hidden:M,extraClassName:O,attrs:I}=t,z=k("div",l),A=!!(m||b),H=G("button",{className:_n(LM,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!h&&"persona-rounded-full",O),attrs:{type:"button","aria-label":e,...I},style:{width:c,height:c,minWidth:c,minHeight:c,display:M?"none":void 0,color:u||gn.actionIconColor,backgroundColor:g,border:A?`${m||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:h,paddingLeft:x,paddingRight:x,paddingTop:T,paddingBottom:T}});return s?Jc(H,s,{iconSize:d,iconText:i}):i&&(H.textContent=i),z.appendChild(H),Qt({anchor:H,trigger:z,text:()=>H.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:H,wrapper:z}},pi=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=bv,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",d=l.closeButtonShowTooltip??!0,{button:u,wrapper:g}=gs({ariaLabel:c,tooltip:d,iconName:l.closeButtonIconName??"x",iconText:l.closeButtonIconText??"\xD7",wrapperClassName:o,size:s??l.closeButtonSize,iconSize:i,color:l.closeButtonColor,backgroundColor:l.closeButtonBackgroundColor,borderWidth:l.closeButtonBorderWidth,borderColor:l.closeButtonBorderColor,borderRadius:l.closeButtonBorderRadius,paddingX:l.closeButtonPaddingX,paddingY:l.closeButtonPaddingY,hidden:!n});return{button:u,wrapper:g}},ui=(t,e={})=>{let{wrapperClassName:n=DM,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",d=l.showTooltip??!0,{button:u,wrapper:g}=gs({ariaLabel:c,tooltip:d,iconName:l.iconName??"refresh-cw",wrapperClassName:n,size:o??l.size,iconSize:s,color:l.iconColor,backgroundColor:l.backgroundColor,borderWidth:l.borderWidth,borderColor:l.borderColor,borderRadius:l.borderRadius,paddingX:l.paddingX,paddingY:l.paddingY});return{button:u,wrapper:g}};var gn={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)"},Yu={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)"},OM={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)"},fs=t=>{let{config:e,showClose:n=!0}=t,o=G("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:gn.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)))"}}),s=e?.launcher??{},i=s.headerIconSize??"48px",l=s.closeButtonPlacement??"inline",c=s.headerIconHidden??!1,d=s.headerIconName,u=G("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:i,width:i,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!c)if(d){let H=parseFloat(i)||24,w=ge(d,H*.6,"currentColor",1);w?u.replaceChildren(w):u.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let H=k("img");H.src=e.launcher.iconUrl,H.alt="",H.className="persona-rounded-xl persona-object-cover",H.style.height=i,H.style.width=i,u.replaceChildren(H)}else u.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let g=k("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=G("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:gn.titleColor,...Yu}}),b=G("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:gn.subtitleColor,...OM}});g.append(m,b),c?o.append(g):o.append(u,g);let h=s.clearChat??{},x=h.enabled??!0,T=h.placement??"inline",M=null,O=null;if(x){let w=ui(e,{wrapperClassName:T==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=w.button,O=w.wrapper,T==="top-right"&&(O.style.right="48px"),T==="inline"&&o.appendChild(O)}let I=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&T==="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:z,wrapper:A}=pi(e,{showClose:n,wrapperClassName:I});return l!=="top-right"&&o.appendChild(A),{header:o,iconHolder:u,headerTitle:m,headerSubtitle:b,closeButton:z,closeButtonWrapper:A,clearChatButton:M,clearChatButtonWrapper:O}},Oa=(t,e,n)=>{let o=n?.launcher??{},s=o.closeButtonPlacement??"inline",i=o.clearChat?.placement??"inline";t.appendChild(e.header),s==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&i==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};var _M=t=>{let e=fs({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return e};function NM(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=gs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Xc(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(s.setAttribute("data-persona-header-action",o.id),o.shortcut){let l=Ha(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=ey({items:o.menuItems,onSelect:c=>n?.(c),anchor:i,position:"bottom-right"});i.appendChild(l.element),s.addEventListener("click",c=>{c.stopPropagation(),l.toggle()})}else s.addEventListener("click",()=>n?.(o.id));t.appendChild(i)}}var FM=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:i}=t,l=e?.launcher??{},c=k("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");c.setAttribute("data-persona-theme-zone","header"),c.style.minHeight=gn.minHeight,c.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",c.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",c.style.boxShadow="var(--persona-header-shadow, none)",c.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s?.titleMenu,u,g;if(d){let A=ny({label:l.title??"Chat Assistant",menuItems:d.menuItems,onSelect:H=>{let w=K=>{K===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:H}}))},D=d.onSelect(H);D instanceof Promise?D.then(w,()=>{}):w(D)},hover:d.hover,className:""});u=A.element,u.style.color=gn.titleColor,g=u.querySelector(".persona-combo-btn-label")??u}else{if(u=k("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=k("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=gn.titleColor,Object.assign(g.style,Yu),g.textContent=l.title??"Chat Assistant",u.appendChild(g),s?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let H=s.onTitleClick;u.addEventListener("click",w=>{w.target.closest("button")||H()}),u.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),H())})}let A=s?.titleRowHover;A&&(u.style.borderRadius=A.borderRadius??"10px",u.style.padding=A.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=A.background??"",u.style.borderColor=A.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}c.appendChild(u);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:b,wrapper:h}=pi(e,{showClose:n,wrapperClassName:m});o&&b.addEventListener("click",o);let x=k("div","persona-flex persona-items-center persona-gap-1");d||NM(x,s?.trailingActions,s?.onAction??i);let T=l.clearChat??{},M=null,O=null;if(T.enabled??!0){let A=T.placement??"inline",H=ui(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});M=H.button,O=H.wrapper,A==="top-right"?O.style.right="48px":x.appendChild(O)}x.appendChild(h),c.appendChild(x);let I=k("div");I.style.display="none";let z=k("span");return z.style.display="none",{header:c,iconHolder:I,headerTitle:g,headerSubtitle:z,closeButton:b,closeButtonWrapper:h,clearChatButton:M,clearChatButtonWrapper:O}},vv={default:_M,minimal:FM},UM=t=>vv[t]??vv.default,Zc=(t,e,n)=>{if(e?.render){let l=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),c=k("div");c.style.display="none";let d=k("span"),u=k("span"),g=k("button");g.style.display="none";let m=k("div");return m.style.display="none",{header:l,iconHolder:c,headerTitle:d,headerSubtitle:u,closeButton:g,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=UM(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(i.iconHolder.style.display="none"),e.showTitle===!1&&(i.headerTitle.style.display="none"),e.showSubtitle===!1&&(i.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(i.closeButton.style.display="none"),e.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display="none")),i};var _a=t=>{let{config:e}=t,n=G("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Uc(),s=G("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:i,attachAutoResize:l}=Oc(e);l();let c=_c(e),d=li(e),u=Nc(e),g=Fc(e),m=G("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(m),u&&(u.previewsContainer.style.gap="8px",m.append(u.previewsContainer),s.append(u.input)),s.append(i);let b=G("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=G("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),x=G("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return u&&h.append(u.wrapper),d&&x.append(d.wrapper),x.append(c.wrapper),b.append(h,x),s.append(b),s.addEventListener("click",T=>{T.target!==c.button&&T.target!==c.wrapper&&T.target!==d?.button&&T.target!==d?.wrapper&&T.target!==u?.button&&T.target!==u?.wrapper&&i.focus()}),n.append(o,s,g),{footer:n,suggestions:o,composerForm:s,header:m,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:g,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:b,leftActions:h,rightActions:x,setSendButtonMode:c.setMode}};import{ChevronUp as $M,MessageSquare as qM}from"lucide";var Cv=()=>{let t=G("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=k("span","persona-pill-peek__icon"),n=en(qM,16,"currentColor",1.5);n&&e.appendChild(n);let o=k("span","persona-pill-peek__text"),s=k("span","persona-pill-peek__caret"),i=en($M,16,"currentColor",1.5);return i&&s.appendChild(i),t.append(e,o,s),{root:t,textNode:o}},ed=t=>{let{config:e}=t,n=G("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Uc(),s=Fc(e);s.style.display="none";let{textarea:i,attachAutoResize:l}=Oc(e,{defaultMaxLines:5});l();let c=_c(e),d=li(e),u=Nc(e);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let g=G("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=G("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&m.append(u.wrapper);let b=G("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&b.append(d.wrapper),b.append(c.wrapper),g.addEventListener("click",T=>{T.target!==c.button&&T.target!==c.wrapper&&T.target!==d?.button&&T.target!==d?.wrapper&&T.target!==u?.button&&T.target!==u?.wrapper&&i.focus()}),u&&g.append(u.input),g.append(m,i,b);let h=G("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),u&&h.append(u.previewsContainer),n.append(o,g,s);let x=g;return{footer:n,suggestions:o,composerForm:g,header:h,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:s,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:x,leftActions:m,rightActions:b,setSendButtonMode:c.setMode}};var zM=t=>{switch(t){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}},jM=(t,e)=>{if(!t)return null;let n=zM(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},VM=(t,e)=>{let n=k("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},KM=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Zu=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},eg=320,Mv=320,GM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),QM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),XM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),YM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),JM=t=>{if(!t||t.length===0)return null;let e=G("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=G("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=k("span","persona-mention-chip-icon"),i=ge(n.iconName??"at-sign",13,"currentColor",2);i&&s.appendChild(i),o.appendChild(s),o.appendChild(G("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},ZM=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Pa(o.ref,{readonly:!0,render:e}))}return n},wv="\uE000",Sv="\uE001",eE=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=b=>`${wv}${s}:${b}${Sv}`,l=e.map((b,h)=>b.kind==="text"?b.text:i(h)).join(""),c=n(l);if(!e.every((b,h)=>b.kind==="text"||c.includes(i(h)))){t.replaceChildren(ZM(e,o));return}t.innerHTML=c;let u=new RegExp(`${wv}${s}:(\\d+)${Sv}`),g=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),m=[];for(let b=g.nextNode();b;b=g.nextNode())m.push(b);for(let b of m){let h=b;for(let x=u.exec(h.data);x;x=u.exec(h.data)){let T=e[Number(x[1])],M=h.splitText(x.index);M.data=M.data.slice(x[0].length),T?.kind==="mention"&&M.parentNode?.insertBefore(Pa(T.ref,{readonly:!0,render:o}),M),h=M}}},tE=(t,e,n)=>{if(t.length===0)return null;try{let o=k("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let s=0,i=!1,l=()=>{i||(i=!0,o.remove(),n?.())};return t.forEach((c,d)=>{let u=k("img");u.alt=c.alt?.trim()||`Attached image ${d+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${eg}px`,u.style.maxHeight=`${Mv}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 g=!1;s+=1,u.addEventListener("error",()=>{g||(g=!0,s=Math.max(0,s-1),u.remove(),s===0&&l())}),u.addEventListener("load",()=>{g=!0}),KM(c.image)?(u.src=c.image,o.appendChild(u)):(g=!0,s=Math.max(0,s-1),u.remove())}),s===0?(l(),null):o}catch{return n?.(),null}},nE=t=>{if(t.length===0)return null;try{let e=k("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!Zu(o.audio))return;let s=k("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${eg}px`,e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},oE=t=>{if(t.length===0)return null;try{let e=k("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!Zu(o.video))return;let s=k("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${eg}px`,s.style.maxHeight=`${Mv}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},rE=t=>{if(t.length===0)return null;try{let e=k("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!Zu(o.data))return;let s=k("a");s.href=o.data,s.download=o.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Na=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";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="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(s),t},sE=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Na};if(e){let s=e(o);if(s!==null)return s}return Na()},iE=(t,e)=>{let n=k("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let s=k("img");s.src=o,s.alt=e==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},xv=(t,e,n="div")=>{let o=k(n,"persona-text-xs persona-text-persona-muted"),s=new Date(t.createdAt);return e.format?o.textContent=e.format(s):o.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Fa=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.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 n},Av={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"}},aE=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=Av[n??"bubble"]??Av.bubble;o.padding&&(t.style.padding=`var(--persona-message-${s}-padding, ${i.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${s}-font-size, ${i.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${s}-line-height, ${i.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${s}-font-family, inherit)`)},td="custom:",lE=t=>`${td}${t}`,Ev=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),cE=(t,e,n,o)=>{let s=e.showCopy??!0,i=e.showUpvote??!0,l=e.showDownvote??!0,c=e.showReadAloud??!1,d=(e.showRegenerate??!1)&&o?.canRegenerate===!0,u=(e.showEdit??!1)&&o?.canEdit===!0,g=(e.showQuote??!1)&&o?.canQuote!==!1,m=Ev(e,t.role);if(!s&&!i&&!l&&!c&&!d&&!u&&!g&&m.length===0){let z=k("div");return z.style.display="none",z.id=`actions-${t.id}`,z.setAttribute("data-actions-for",t.id),z}let b=e.visibility??"hover",h=e.align??"right",x=e.layout??"pill-inside",T={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],M={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[x],O=k("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${T} ${M} ${b==="hover"?"persona-message-actions-hover":""}`);O.id=`actions-${t.id}`,O.setAttribute("data-actions-for",t.id);let I=(z,A,H)=>{let w=ty({icon:z,label:A,size:14,className:"persona-message-action-btn",chromeless:!0});return w.setAttribute("data-action",H),w};s&&O.appendChild(I("copy","Copy message","copy")),c&&O.appendChild(I("volume-2","Read aloud","read-aloud")),i&&O.appendChild(I("thumbs-up","Upvote","upvote")),l&&O.appendChild(I("thumbs-down","Downvote","downvote")),d&&O.appendChild(I("refresh-cw","Regenerate response","regenerate")),u&&O.appendChild(I("pencil","Edit message","edit")),g&&O.appendChild(I("quote","Quote message","quote"));for(let z of m)O.appendChild(I(z.iconName??"ellipsis",z.label,lE(z.id)));return O},tg=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",d=l.avatar,u=l.timestamp,g=d?.show??!1,m=u?.show??!1,b=d?.position??"left",h=u?.position??"below",x=Fa(t.role,c),T=k("div",x.join(" "));T.id=`bubble-${t.id}`,T.setAttribute("data-message-id",t.id),T.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let M=i?.widgetConfig?.theme?.components?.message;aE(T,t.role,c,t.role==="user"?M?.user:M?.assistant),c==="flat"?(T.style.backgroundColor="transparent",T.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(T.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",T.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(T.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",T.style.color="var(--persona-message-assistant-text, var(--persona-text))");let O=GM(t),I=t.content?.trim()??"",A=O.length>0&&I===ii,H=mc(i?.widgetConfig?.features?.streamAnimation),w=i?.widgetConfig?.features?.streamAnimation?.plugins,D=t.role==="assistant"&&H.type!=="none"?ua(H.type,w):null,K=t.role==="assistant"&&D?.isAnimating?.(t)===!0,ie=t.role==="assistant"&&D!==null&&(!!t.streaming||K);ie&&D?.bubbleClass&&T.classList.add(D.bubbleClass);let Z=document.createElement("div");Z.classList.add("persona-message-content"),t.streaming&&Z.classList.add("persona-content-streaming"),ie&&D&&(D.containerClass&&Z.classList.add(D.containerClass),Z.style.setProperty("--persona-stream-step",`${H.speed}ms`),Z.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let S=ie?hc(t.content??"",H.buffer,D,t,!!t.streaming):t.content??"",W=()=>{let ye=e({text:S,message:t,streaming:!!t.streaming,raw:t.rawContent});return ie&&D?.wrap==="char"?ga(ye,"char",t.id,{skipTags:D.skipTags}):ie&&D?.wrap==="word"?ga(ye,"word",t.id,{skipTags:D.skipTags}):ye},R=null;if(A?(R=document.createElement("div"),R.innerHTML=W(),R.style.display="none",Z.appendChild(R)):t.contentSegments?.length?eE(Z,t.contentSegments,ye=>e({text:ye,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):Z.innerHTML=W(),ie&&D?.useCaret&&!A&&I){let ye=yc(),N=Z.querySelectorAll(".persona-stream-char, .persona-stream-word"),Te=N[N.length-1];if(Te?.parentNode)Te.parentNode.insertBefore(ye,Te.nextSibling);else{let Ue=Z.lastElementChild;Ue?Ue.appendChild(ye):Z.appendChild(ye)}}if(m&&h==="inline"&&t.createdAt){let ye=xv(t,u,"span");ye.classList.add("persona-timestamp-inline");let N=Z.lastElementChild;N?N.appendChild(ye):Z.appendChild(ye)}if(O.length>0){let ye=tE(O,!A&&!!I,()=>{A&&R&&(R.style.display="")});ye?T.appendChild(ye):A&&R&&(R.style.display="")}let L=QM(t);if(L.length>0){let ye=nE(L);ye&&T.appendChild(ye)}let J=XM(t);if(J.length>0){let ye=oE(J);ye&&T.appendChild(ye)}let U=YM(t);if(U.length>0){let ye=rE(U);ye&&T.appendChild(ye)}let ae=t.contentSegments?.length?null:JM(t.contextMentions);if(ae&&T.appendChild(ae),T.appendChild(Z),m&&h==="below"&&t.createdAt){let ye=xv(t,u);ye.classList.add("persona-mt-1"),T.appendChild(ye)}let re=t.role==="assistant"?jM(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ye=!!(S&&S.trim()),N=H.placeholder==="skeleton",Te=N&&H.buffer==="line"&&ye;if(ye)Te&&T.appendChild(fa());else if(N)T.appendChild(fa());else{let Ue=sE("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);Ue&&T.appendChild(Ue)}}re&&t.stopReason&&!t.streaming&&(I||(Z.style.display="none"),T.appendChild(VM(t.stopReason,re)));let ue=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,Ee=i?.actionEligibility,he=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ee?.canEdit===!0||o?.showQuote===!0&&Ee?.canQuote===!0||Ev(o,"user").length>0);if((ue||he)&&o){let ye=cE(t,he?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,Ee);T.appendChild(ye)}if(!g||t.role==="system")return T;let ce=k("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),at=iE(d,t.role);return b==="right"||b==="left"&&t.role==="user"?ce.append(T,at):ce.append(at,T),ce};var dE=40,pE=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=ge(e.name,dE);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(G("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(G("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},Tv=(t,e,n={})=>{let o=G("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let s=k("p","persona-welcome-kicker");s.hidden=!0;let i=k("h2","persona-welcome-title"),l=k("p","persona-welcome-subtitle"),c=G("div",{className:"persona-welcome-head-text"},s,i),d=G("div",{className:"persona-welcome-title-row"},o,c);return{host:G("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:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},d,l,e),iconHolder:o,kicker:s,title:i,subtitle:l,starterSuggestions:e}},gi=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},od=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",pE(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},uE="data-persona-welcome-plugin",kv="data-persona-welcome-overlay",nd="persona-welcome-overlay-active",ng=new WeakMap,og=(t,e,n)=>{n.setAttribute(uE,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(kv,""),t.classList.contains(nd)||(ng.set(t,t.scrollTop),t.classList.add(nd),t.scrollTop=0)},rg=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(kv),t.classList.contains(nd)&&(t.classList.remove(nd),t.scrollTop=ng.get(t)??t.scrollTop,ng.delete(t))},Pv=()=>{let t=G("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},rd=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",s=G("div",{className:Fa("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="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))"}});t.appendChild(G("div",{className:"persona-flex"},s)),t.hidden=!1},Iv=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Lv=(t,e)=>{if(Iv()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,s=0,i=0,l=0;if(o){let x=getComputedStyle(o);s=parseFloat(x.rowGap)||0;let T=t.previousElementSibling,M=t.nextElementSibling,I=o.getBoundingClientRect().top+(parseFloat(x.borderTopWidth)||0)+(parseFloat(x.paddingTop)||0)-o.scrollTop;i=Math.max(0,T?n.top-T.getBoundingClientRect().bottom-s:n.top-I),l=Math.max(0,M?M.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let d=getComputedStyle(t),u=parseFloat(d.paddingTop)||0,g=parseFloat(d.paddingBottom)||0,m=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${g}px`,marginTop:`${i}px`,marginBottom:`${l}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-s}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),b=!1,h=()=>{b||(b=!0,t.style.overflow=c,e(m))};return m.finished.then(h).catch(h),m},Hv=(t,e,n)=>{if(e<=1||Iv()||typeof t.animate!="function"||!t.isConnected)return null;let o=n==="drop"?-e:e;return t.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var gE="Hello \u{1F44B}",fE="I can answer questions and help you get things done here.",Rv=new WeakSet,fn=(t,e)=>!!t&&t[e]!==void 0,mE=(t,e)=>{!t||t.debug!==!0||!e.length||Rv.has(t)||(Rv.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Zo=t=>{let e=t?.welcome,n=t?.copy,o=fn(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",s=o==="hero"?"on-first-message":fn(e,"dismiss")?e.dismiss:"never",i=[];fn(e,"title")&&fn(n,"welcomeTitle")&&i.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),fn(e,"subtitle")&&fn(n,"welcomeSubtitle")&&i.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),fn(e,"variant")&&fn(n,"showWelcomeCard")&&i.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&fn(e,"message")&&i.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&fn(e,"dismiss")&&e.dismiss!=="on-first-message"&&i.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let l=e?.anchor==="center"?"center":"bottom",c=La(e?.anchorComposerTop)!==null;return fn(e,"anchorComposerTop")&&!c&&i.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),l!=="center"&&(fn(e,"anchorComposerTop")||fn(e,"composerGap"))&&i.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),mE(t,i),{title:fn(e,"title")?e.title:n?.welcomeTitle??gE,kicker:e?.kicker??"",subtitle:fn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??fE,icon:e?.icon,align:e?.align==="start"||e?.align==="center"?e.align:void 0,iconPlacement:e?.icon&&typeof e.icon!="function"&&e.icon.placement==="inline"?"inline":"above",variant:o,dismiss:s,message:o==="hero"?void 0:e?.message,anchor:l,anchorComposerTop:c?e.anchorComposerTop:"44%",composerGap:e?.composerGap?.trim()||Kc}},Wv=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",fi=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var Bv="16px",ig="10px",ag="14px",Dv=t=>{let e=t?.launcher?.enabled??!0,n=Lt(t);if(Ba(t)){let g=t?.launcher?.composerBar??{},m=k("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=g.expandedSize??"anchored",m.style.zIndex=String(t?.launcher?.zIndex??an);let b=k("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",m.appendChild(b);let h=k("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=g.expandedSize??"anchored",h.style.zIndex=String(t?.launcher?.zIndex??an),{wrapper:m,panel:b,pillRoot:h}}if(n){let g=k("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=k("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return g.appendChild(m),{wrapper:g,panel:m}}if(!e){let g=k("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=k("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=t?.launcher?.width??"100%";return g.style.width=b,m.style.width="100%",g.appendChild(m),{wrapper:g,panel:m}}let s=t?.launcher??{},i=s.position&&Fn[s.position]?Fn[s.position]:Fn["bottom-right"],l=k("div",`persona-widget-wrapper persona-fixed ${i} persona-transition`);l.style.zIndex=String(t?.launcher?.zIndex??an);let c=k("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=t?.launcher?.width??t?.launcherWidth??Jo;return c.style.width=u,c.style.maxWidth=u,l.appendChild(c),{wrapper:l,panel:c}},lg=t=>{let e=G("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Gu(t)}});return e.hidden=!0,e},Ov=(t,e)=>{let n=lg("starter"),o=Tv(t,n,{flatShadow:Lt(t)}),s=Zo(t);od(o,s),gi(e,o.host,fi(s,t?.initialMessages));let i=Pv();return rd(i,s.message,t),{welcome:o,greetingHost:i}},hE=(t,e)=>{let n=k("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:s}=pi(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:Bv,iconSize:ig});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let i=t?.launcher?.clearChat?.enabled??!0,l=null,c=null;if(i){let D=ui(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Bv,iconSize:ag});l=D.button,c=D.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let d=G("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=G("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:g,greetingHost:m}=Ov(t,u),{host:b,title:h,subtitle:x}=g,T=g.starterSuggestions,M=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),O=lg("followUp"),I=kr(t,!0);I&&(M.style.maxWidth=I,M.style.marginLeft="auto",M.style.marginRight="auto",M.style.width="100%"),u.append(b,m,M,O);let z=G("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"}}),A=ed({config:t}),{root:H,textNode:w}=Cv();return n.append(d,s,u,z),c&&n.appendChild(c),{container:n,body:u,messagesWrapper:M,starterSuggestions:T,transcriptSuggestions:O,composerOverlay:z,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:b,welcomeIconHolder:g.iconHolder,greetingHost:m,introKicker:g.kicker,introTitle:h,introSubtitle:x,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:k("span"),headerTitle:k("span"),headerSubtitle:k("span"),header:d,footer:A.footer,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:H,peekTextNode:w}},_v=(t,e=!0)=>{if(Ba(t))return hE(t,e);let n=G("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,s=t?.layout?.showHeader!==!1,i=o?Zc(t,o,{showClose:e}):fs({config:t,showClose:e}),l=G("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"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:d}=Ov(t,l),{host:u,title:g,subtitle:m}=c,b=c.starterSuggestions,h=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),x=lg("followUp"),T=kr(t,!1);T&&(h.style.maxWidth=T,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),l.append(u,d,h,x);let M=_a({config:t}),O=t?.layout?.showFooter!==!1;s?Oa(n,i,t):(i.header.style.display="none",Oa(n,i,t)),n.append(l);let I=G("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 O||(M.footer.style.display="none"),n.append(M.footer),n.append(I),{container:n,body:l,messagesWrapper:h,starterSuggestions:b,transcriptSuggestions:x,composerOverlay:I,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:c.iconHolder,greetingHost:d,introKicker:c.kicker,introTitle:g,introSubtitle:m,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,header:i.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 cg=(t,e)=>{let n=k("button");n.type="button",n.innerHTML=`
|
|
16
|
+
`),c=Array.isArray(e.contentParts)&&e.contentParts.length>0,d=s.contentParts.length>0;if(c){let u=[];i&&u.push(Mo(i)),u.push(...s.contentParts),u.push(...e.contentParts),e.contentParts=u}else if(d){let u=[];l&&u.push(Mo(l)),u.push(...s.contentParts),e.contentParts=u}else i&&(e.llmContent=l);Object.keys(s.context).length>0&&(e.mentionContext=s.context)}async sendMessage(e,n){let o=e.trim(),s=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!s)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let i=bc(),l=ti();this.activeAssistantMessageId=null;let c=n?.contentParts&&xc(n.contentParts)?ii:"",d={id:i,role:"user",content:o||c,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(d),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,n?.mentions){let m=this.messages.find(v=>v.id===i)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(h=>h.id===i)??d,v=Yy({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});v.contentParts&&(m.contentParts=v.contentParts),v.llmContent!==void 0&&(m.llmContent=v.llmContent),(v.contentParts||v.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let g=[...this.messages];try{await this.dispatchWithDeletedRecovery(g,u,l,i,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let v=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!v){let h=Su(m,this.config.errorMessage);if(h){let T={id:l,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(e,n){let o=Jy(this.messages,e);if(!o)return!1;let s=this.messages[o.start],i=n.replacement,l=i?i.text:s.content,c=i?i.contentParts:s.contentParts;if(!(!!l?.trim()||(c?.length??0)>0||!i&&(s.llmContent?.trim()?.length??0)>0))return!1;let u=i?void 0:{...s.llmContent!==void 0&&{llmContent:s.llmContent},...s.rawContent!==void 0&&{rawContent:s.rawContent},...s.mentionContext&&{mentionContext:s.mentionContext},...s.contextMentions&&{contextMentions:s.contextMentions},...s.quote&&{quote:s.quote}},g=i?this.toComposerOptionsPayload(i.options):s.composerOptions,m=i?i.contentSegments:s.contentSegments,v=i?i.options?.quote:void 0,h=i?i.viaVoice:s.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(l??"",{...c?.length?{contentParts:[...c]}:{},...m?.length?{contentSegments:[...m]}:{},...g?{composerOptions:g}:{},...v?{quote:v}:{},...u&&Object.keys(u).length>0?{replayFields:u}:{},viaVoice:h===!0}),!0}toComposerOptionsPayload(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n: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 e=ti();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;let i=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!i){let l=Su(s,this.config.errorMessage);if(l){let c={id:e,role:"assistant",createdAt:new Date().toISOString(),content:l,sequence:this.nextSequence()};this.appendMessage(c)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,i||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(i){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let s=this.messages.find(i=>i.id===e);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let s=`approval-${e.id}`,i={...e,status:n,resolvedAt:Date.now()},l=this.messages.find(g=>g.id===s),c={id:s,role:"assistant",content:"",createdAt:l?.createdAt??new Date().toISOString(),...l?.sequence!==void 0?{sequence:l.sequence}:{},streaming:!1,variant:"approval",approval:i};this.upsertMessage(c),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,u=d&&typeof d=="object"?d.onDecision:void 0;try{let g;if(u?g=await u({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):g=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),g){let m=null;if(g instanceof Response){if(!g.ok){let v=await g.json().catch(()=>null);throw new Error(v?.error??`Approval request failed: ${g.status}`)}m=g.body}else g instanceof ReadableStream&&(m=g);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.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(g){let m=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(g=>g.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let s=e.agentMetadata?.executionId,i=e.toolCall?.name;if(!s||!i){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let l=typeof n=="string"?void 0:n;if(l===void 0&&typeof n=="string"){let g=e.toolCall?.args,m=Array.isArray(g?.questions)?g.questions:[];if(m.length===1){let v=typeof m[0]?.question=="string"?m[0].question:"";v&&(l={[v]:n})}}this.markAskUserQuestionResolved(e,l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=e.toolCall.id,d=e.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===0){let g=typeof n=="string"?n:Object.entries(n).map(([m,v])=>`${m}: ${Array.isArray(v)?v.join(", "):v}`).join(" | ");this.appendMessage({id:`ask-user-answer-${c}`,role:"user",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let g=l??{};u.forEach((m,v)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let T=g[h],M=Array.isArray(T)?T.join(", "):typeof T=="string"?T:"";this.appendMessage({id:`ask-user-q-${c}-${v}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${c}-${v}`,role:"user",content:M||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let g=await this.client.resumeFlow(s,{[i]:n},{after:this.resumable?.executionId===s?this.resumable.lastEventId:void 0});if(!g.ok){let m=await g.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${g.status}`)}g.body?await this.connectStream(g.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(g){let m=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(g instanceof Error?g:new Error(String(g)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(o)&&(s.seen.add(o),s.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(s=>s.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==Mr?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,s=Date.now(),i){this.messages.some(l=>l.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...i},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:s,duration:void 0,durationMs:Math.max(0,s-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let i=async d=>{let u=d.toolCall?.name,g=d.toolCall?.id;if(!u||!g)return null;let m=`${e}:${g}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(m),o.push(m);let v=this.markWebMcpToolRunning(d),h=d.agentMetadata?.webMcpToolCallId??u;if(u===Mr)return{dedupeKey:m,resumeKey:h,output:Iy(),toolMessage:d,startedAt:v,completedAt:Date.now()};let T=this.client.executeWebMcpToolCall(u,d.toolCall?.args,s.signal),M;if(!T)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await T}catch(E){let I=E instanceof Error&&(E.name==="AbortError"||E.message.includes("aborted")||E.message.includes("abort"));return I||this.callbacks.onError?.(E instanceof Error?E:new Error(String(E))),this.markWebMcpToolComplete(d,xu(I?"Aborted by cancel()":mA(E)),v),this.webMcpInflightKeys.delete(m),null}return s.signal.aborted?(this.markWebMcpToolComplete(d,xu("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:M,toolMessage:d,startedAt:v,completedAt:Date.now()}},l;if(this.config.webmcp?.execution==="sequential"){l=[];for(let d of n)l.push(await i(d))}else l=await Promise.all(n.map(i));let c=[];try{if(c=l.filter(g=>g!==null),c.length===0)return;let d={};for(let g of c)d[g.resumeKey]=g.output;let u=await this.client.resumeFlow(e,d,{signal:s.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!u.ok){let g=await u.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${u.status}`)}for(let g of c)this.webMcpResolvedKeys.add(g.dedupeKey),this.markWebMcpToolComplete(g.toolMessage,g.output,g.startedAt,g.completedAt,g.toolMessage.toolCall?.name===Mr?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let g of c)this.markWebMcpToolComplete(g.toolMessage,xu("Aborted by cancel()"),g.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,s=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!s){let l=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(l)||this.webMcpResolvedKeys.has(l))return;this.webMcpInflightKeys.add(l);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(l)}catch(c){this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}finally{this.webMcpInflightKeys.delete(l)}return}let i=`${n}:${s}`;if(!(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i)||this.isSuggestRepliesAlreadyResolved(e)))return this.resolveWebMcpToolCallBatch(n,[e])}async resumeWithToolOutput(e,n,o,s){let i=await this.client.resumeFlow(e,{[n]:o},{signal:s?.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!i.ok){let l=await i.json().catch(()=>null);throw new Error(l?.error??`Resume failed: ${i.status}`)}s?.onHttpOk?.(),i.body?await this.connectStream(i.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=Sr(this.config.features?.artifacts,e),s=ha(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),i=this.messages.find(l=>l.id===n);if(i){i.rawContent=s,i.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:s})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(l=>l.id===`artifact-ref-${n.id}`);if(!o)continue;let s=Sr(this.config.features?.artifacts,n),i=ha(s,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==i&&(o.rawContent=i,o.streaming=n.status==="streaming",e=!0)}e&&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(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}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(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.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(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=nb().then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,s)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>Su(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=ti(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let s=Cu(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return bu(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=Cu(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,i)=>{if(i!==o)return s;let l={...s,...n};if(s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(l.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(l.agentMetadata={...l.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let g=s.approval,m=n.approval;l.approval={...g,...m,executionId:m.executionId||g.executionId,toolName:m.toolName||g.toolName,description:m.description||g.description,toolType:m.toolType??g.toolType,reason:m.reason??g.reason,parameters:m.parameters??g.parameters}}let c=n.toolCall?.name,d=n.agentMetadata?.executionId,u=n.toolCall?.id;if(c&&ob(c)&&d&&u&&n.agentMetadata?.awaitingLocalTool===!0){let g=`${d}:${u}`,m=this.webMcpInflightKeys.has(g),v=this.webMcpResolvedKeys.has(g),h=s.toolCall?.name,T=s.agentMetadata?.executionId===d&&s.toolCall?.id===u&&h!==void 0&&ob(h)&&s.toolCall?.status==="complete";(m||v||T)&&(l.agentMetadata={...l.agentMetadata??{},awaitingLocalTool:!1},l.toolCall=s.toolCall,l.streaming=s.streaming)}return l}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),i=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=n.sequence??0,c=o.sequence??0;return l!==c?l-c:n.id.localeCompare(o.id)})}};import{File as hA,FileCode as yA,FileSpreadsheet as bA,FileText as Au,X as vA}from"lucide";var CA={add:t=>Oy(t)},wA=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Pc={allowedTypes:Yo,maxFileSize:10*1024*1024,maxFiles:4};function SA(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xA(t){return t==="application/pdf"?Au:t.startsWith("text/")?Au:t.includes("word")?Au:t.includes("excel")||t.includes("spreadsheet")?bA:t==="application/json"?yA:hA}var Ma=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Pc.allowedTypes,maxFileSize:e.maxFileSize??Pc.maxFileSize,maxFiles:e.maxFiles??Pc.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:CA}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Pc.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.destroyed)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let s=_y(o,this.config.allowedTypes,this.config.maxFileSize);if(!s.valid){let l=s.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,l);continue}let i={id:SA(),file:o,previewUrl:Ac(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(i),this.renderPreview(i),n.push(i)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(e){let n=new AbortController;this.pendingAdds.set(e.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(e.id)!==n||!this.attachments.includes(e);try{let s=await this.adapter().add(e.file,{signal:n.signal,onProgress:i=>{o()||e.status!=="uploading"||(e.progress=wA(i),this.updatePreview(e),this.notify())}});if(o())return;e.contentPart=s,e.status="ready",e.progress=void 0,e.error=void 0}catch(s){if(o())return;e.status="error",e.progress=void 0,e.error=s instanceof Error?s.message:String(s??"Upload failed")}finally{this.pendingAdds.get(e.id)===n&&this.pendingAdds.delete(e.id)}this.updatePreview(e),this.notify()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(e){let n=this.pendingAdds.get(e);n&&(this.pendingAdds.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(i=>i.id===e);if(n===-1)return;let o=this.attachments[n];this.abortAdd(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);s&&s.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(s=>{console.error("[AttachmentManager] adapter.remove failed:",s)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.abortAdd(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.pendingAdds.values())e.abort();this.pendingAdds.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=Ac(e.file),o=k("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let g=k("img");g.src=e.previewUrl,g.alt=e.file.name,g.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",g.style.width="48px",g.style.height="48px",g.style.objectFit="cover",g.style.borderRadius="8px",o.appendChild(g)}else{let g=k("div");g.style.width="48px",g.style.height="48px",g.style.borderRadius="8px",g.style.backgroundColor="var(--persona-container, #f3f4f6)",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.display="flex",g.style.flexDirection="column",g.style.alignItems="center",g.style.justifyContent="center",g.style.gap="2px",g.style.overflow="hidden";let m=xA(e.file.type),v=en(m,20,"var(--persona-muted, #6b7280)",1.5);v&&g.appendChild(v);let h=k("span");h.textContent=Ny(e.file.type,e.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",g.appendChild(h),o.appendChild(g)}let s=G("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),i=k("div","persona-attachment-progress");i.appendChild(k("div","persona-attachment-progress__bar"));let l=G("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=ge("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);c?l.appendChild(c):l.textContent="\u21BB",l.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.retryAttachment(e.id)}),s.append(i,l),o.appendChild(s);let d=k("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let u=en(vA,10,"var(--persona-text-inverse, #ffffff)",2);u?d.appendChild(u):(d.textContent="\xD7",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(d),this.previewsContainer.appendChild(o),this.applyPreviewState(o,e)}updatePreview(e){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.applyPreviewState(n,e)}applyPreviewState(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let s=e.querySelector(".persona-attachment-progress__bar");if(s){let i=n.progress;s.style.width=typeof i=="number"?`${Math.round(i*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var rb=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),AA=(t,e)=>t.length===e.length&&t.every((n,o)=>{let s=e[o];return n.id===s.id&&n.name===s.name&&n.mimeType===s.mimeType&&n.size===s.size&&n.status===s.status&&n.progress===s.progress&&n.error===s.error});function sb(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,s=!1,i=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",l=()=>{let g=i();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:g,inputDisabled:t.inputDisabled,sendDisabled:g!=="idle"||t.sendDisabled||t.inputDisabled})},c=()=>(n||(n=l()),n),d=()=>{if(o=!1,s||e.size===0)return;let g=c();for(let m of[...e])try{m(g)}catch(v){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",v)}},u=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(d))};return{getState:c,subscribe:g=>(e.add(g),()=>e.delete(g)),setText:g=>{t.text!==g&&(t.text=g,u())},setAttachments:g=>{AA(t.attachments,g)||(t.attachments=[...g],u())},setMentionRefs:g=>{rb(t.mentionRefs,g)||(t.mentionRefs=[...g],u())},setSelectedModelId:g=>{t.selectedModelId!==g&&(t.selectedModelId=g,u())},setActiveModeIds:g=>{rb(t.activeModeIds,g)||(t.activeModeIds=[...g],u())},setQuote:g=>{let m=t.quote;m?.text===g?.text&&m?.messageId===g?.messageId&&m?.sourceLabel===g?.sourceLabel||(t.quote=g?{...g}:void 0,u())},setPendingSubmission:g=>{t.pendingSubmission!==g&&(t.pendingSubmission=g,u())},setPreparing:g=>{t.preparing!==g&&(t.preparing=g,u())},setStreaming:g=>{t.streaming!==g&&(t.streaming=g,u())},setInputDisabled:g=>{t.inputDisabled!==g&&(t.inputDisabled=g,u())},setSendDisabled:g=>{t.sendDisabled!==g&&(t.sendDisabled=g,u())},flush:()=>{o&&d()},destroy:()=>{s=!0,o=!1,e.clear()}}}var kn=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},ib=(t,e)=>{let n=k("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function ab(t,e={}){let n=kn(t,"[data-persona-composer-form]"),o=kn(t,"[data-persona-composer-input]");if(!n||!o){let I=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(I);return typeof console<"u"&&console.warn(I),null}let s={header:kn(t,"[data-persona-composer-header]"),body:kn(t,"[data-persona-composer-body]"),actionsStart:kn(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:kn(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:kn(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:kn(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:kn(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=ib("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(l,n):t.appendChild(l));let c=s.body??o.parentElement??n,d=(E,I,P,N,x)=>{if(I)return I;i.add(E);let R=ib(P,N);return x.appendChild(R),R},u=d("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),g=d("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",s.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),v=d("status",s.status,"persona-widget-composer__status","data-persona-composer-status",t),h=[],T=(E,I)=>E.target===I.target&&E.type===I.type&&E.handler===I.handler,M=kn(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:l,body:c,actionsStart:u,actionsEnd:g,suggestions:m,status:v,attachmentInput:M,attachmentPreviews:kn(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:kn(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:kn(t,"[data-persona-composer-submit]")??void 0,micButton:kn(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(E,I,P,N)=>{E.addEventListener(I,P,N),h.push({target:E,type:I,handler:P,options:N})},removeListener:(E,I,P,N)=>{E.removeEventListener(I,P,N),h=h.filter(x=>!T(x,{target:E,type:I,handler:P}))},destroy:()=>{for(let E of h)E.target.removeEventListener(E.type,E.handler,E.options);h=[]}}}var MA=8,EA=8,Mu=10,lb=200,cb=300,db=0,Lc=t=>Math.max(0,t);function pb(t){t.delayMs!==void 0&&(lb=Lc(t.delayMs)),t.skipDelayMs!==void 0&&(cb=Lc(t.skipDelayMs))}var TA=()=>Date.now()<db,kA=t=>{db=t>0?Date.now()+t:0},Ic=new WeakMap,Tu="data-persona-tooltip-suppressed",PA=t=>typeof t.closest=="function"&&t.closest(`[${Tu}]`)!==null;function ub(t){Ic.get(t)?.hide()}var gb=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,IA=t=>{let e=t.getRootNode?.();return gb(e)?e:t.ownerDocument.body},Eu=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),LA=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(t=>`--persona-tooltip-${t}`),"--persona-font-family","--persona-radius-sm"];function Qt(t){Ic.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:s,enabled:i=!0,gap:l=MA,viewportPadding:c=EA}=t,d=()=>e.ownerDocument,u=()=>d().defaultView??window,g=null,m=null,v=null,h=null,T,M=!1,E=!1,I=!1,P=()=>(typeof o=="function"?o():o).trim(),N=()=>(typeof s=="function"?s():s??"").trim(),x=()=>Lc(t.delayMs??lb),R=()=>Lc(t.skipDelayMs??cb),w=()=>{T!==void 0&&(u().clearTimeout(T),T=void 0)},O=()=>{w();let ue=g!==null;h?.(),h=null,g?.remove(),g=null,m=null,v=null,ue&&kA(R())},K=()=>{if(!g)return;let ue=d(),Ee=u(),he=e.getBoundingClientRect(),ce=g.getBoundingClientRect(),at=ue.documentElement.clientWidth||Ee.innerWidth,ye=ue.documentElement.clientHeight||Ee.innerHeight,F=at-c-ce.width,Te=he.left+he.width/2-ce.width/2,Ue=Eu(Te,c,F),qt=he.top-c,Le=ye-c-he.bottom,Fe=ce.height+l,ve=qt>=Fe||qt>=Le?"top":"bottom",ln=ve==="top"?he.top-l-ce.height:he.bottom+l,Zn=ye-c-ce.height,Po=Eu(ln,c,Zn),vt=he.left+he.width/2,Io=Math.max(Mu,ce.width-Mu),j=Eu(vt-Ue,Mu,Io);g.dataset.placement=ve,g.style.left=`${Ue}px`,g.style.top=`${Po}px`,g.style.setProperty("--persona-tooltip-arrow-x",`${j}px`)},ie=()=>{if(I||!i||g||!e.isConnected||PA(e))return;let ue=P(),Ee=IA(e);if(!ue||!Ee)return;let he=d(),ce=u();g=he.createElement("div"),g.className="persona-control-tooltip",g.setAttribute("role","tooltip"),g.dataset.state="measuring",g.style.zIndex=String(uc);let at=ce.getComputedStyle?.(e);if(at){for(let Fe of LA){let ve=at.getPropertyValue(Fe).trim();ve&&g.style.setProperty(Fe,ve)}at.fontFamily&&(g.style.fontFamily=at.fontFamily)}m=he.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ue,g.appendChild(m);let ye=N();ye&&(v=he.createElement("span"),v.className="persona-control-tooltip__hint",v.textContent=ye,g.appendChild(v));let F=he.createElement("span");F.className="persona-control-tooltip__arrow",g.appendChild(F),Ee.appendChild(g),K(),g.dataset.state="open";let Te=()=>{if(!e.isConnected){O();return}m&&(m.textContent=P()),v&&(v.textContent=N()),K()};ce.addEventListener("scroll",Te,!0),ce.addEventListener("resize",Te);let Ue=e.getRootNode(),qt=gb(Ue)?Ue:he.documentElement,Le=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||O()});Le?.observe(qt,{childList:!0,subtree:!0}),h=()=>{ce.removeEventListener("scroll",Te,!0),ce.removeEventListener("resize",Te),Le?.disconnect()}},Z=ue=>{if(!(I||g)){if(w(),ue||x()<=0||TA()){ie();return}T=u().setTimeout(()=>{T=void 0,ie()},x())}},S=()=>{M||E?Z(E):O()},B=()=>{let ue=u();(!ue.matchMedia||!ue.matchMedia("(hover: none)").matches)&&(M=!0,S())},W=()=>{M=!1,S()},H=()=>{try{E=e.matches(":focus-visible")}catch{E=!0}S()},J=()=>{E=!1,S()},$=()=>{M=!1,E=!1,O()},ae=ue=>{ue.key==="Escape"&&$()};n.addEventListener("mouseenter",B),n.addEventListener("mouseleave",W),e.addEventListener("focus",H),e.addEventListener("blur",J),e.addEventListener("keydown",ae),e.addEventListener("click",$);let re={get isOpen(){return g!==null},show:ie,hide:O,reposition:K,destroy:()=>{I||(I=!0,O(),n.removeEventListener("mouseenter",B),n.removeEventListener("mouseleave",W),e.removeEventListener("focus",H),e.removeEventListener("blur",J),e.removeEventListener("keydown",ae),e.removeEventListener("click",$),Ic.delete(e))}};return Ic.set(e,re),re}var fb=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ai(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];fb(i)&&fb(s)?n[o]=ai(i,s):n[o]=s}return n}var Jo="min(440px, calc(100vw - 24px))",hb="440px",ku="How can I help...",HA={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:Jo,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)"},nt={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:HA,copy:{inputPlaceholder:ku,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 mb(t,e){if(!(!t&&!e))return t?e?ai(t,e):t:e}function Hc(t){return t?{...nt,...t,theme:mb(nt.theme,t.theme),darkTheme:mb(nt.darkTheme,t.darkTheme),launcher:{...nt.launcher,...t.launcher,dock:{...nt.launcher?.dock,...t.launcher?.dock},clearChat:{...nt.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...nt.tooltip,...t.tooltip},copy:{...nt.copy,...t.copy},sendButton:{...nt.sendButton,...t.sendButton},statusIndicator:{...nt.statusIndicator,...t.statusIndicator},voiceRecognition:{...nt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=nt.features?.artifacts,n=t.features?.artifacts,o=nt.features?.scrollToBottom,s=t.features?.scrollToBottom,i=nt.features?.scrollBehavior,l=t.features?.scrollBehavior,c=nt.features?.streamAnimation,d=t.features?.streamAnimation,u=nt.features?.askUserQuestion,g=t.features?.askUserQuestion,m=nt.features?.history,v=t.features?.history,h=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},T=o===void 0&&s===void 0?void 0:{...o,...s},M=i===void 0&&l===void 0?void 0:{...i,...l},E=c===void 0&&d===void 0?void 0:{...c,...d},I=u===void 0&&g===void 0?void 0:{...u,...g,styles:{...u?.styles,...g?.styles}},P=m===void 0&&v===void 0?void 0:{...m,...v,copy:{...m?.copy,...v?.copy}};return{...nt.features,...t.features,...T!==void 0?{scrollToBottom:T}:{},...M!==void 0?{scrollBehavior:M}:{},...h!==void 0?{artifacts:h}:{},...E!==void 0?{streamAnimation:E}:{},...I!==void 0?{askUserQuestion:I}:{},...P!==void 0?{history:P}:{}}})(),suggestionChips:t.suggestionChips??nt.suggestionChips,suggestionChipsConfig:{...nt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...nt.layout,...t.layout,header:{...nt.layout?.header,...t.layout?.header},messages:{...nt.layout?.messages,...t.layout?.messages,avatar:{...nt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...nt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...nt.layout?.slots,...t.layout?.slots}},markdown:{...nt.markdown,...t.markdown,options:{...nt.markdown?.options,...t.markdown?.options}},messageActions:{...nt.messageActions,...t.messageActions}}:nt}function Pu(t){let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return 20;let n=e.getComputedStyle(t).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function Rc(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function yb(t,e){t.style.maxHeight=`${e*Pu(t)}px`,t.style.overflowY="auto"}function ka(t){let e=t?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!e||typeof e.matchMedia!="function")return!1;try{return e.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function bb(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function vb(t,e){if(t.key!=="Enter"||t.shiftKey||t.isComposing)return!1;let n=t.metaKey===!0||t.ctrlKey===!0,o=e.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!bb(e)}function RA(t){return(t.submitKey??"enter")!=="enter"||bb(t)?"enter":"send"}function Wc(t,e){t.setAttribute("enterkeyhint",RA(e))}function Bc(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(s,i)=>{i===void 0?t.removeAttribute(s):t.setAttribute(s,i)};o("autocapitalize",typeof e?.autocapitalize=="string"?e.autocapitalize:void 0),o("spellcheck",typeof e?.spellcheck=="boolean"?String(e.spellcheck):void 0),o("inputmode",typeof e?.inputmode=="string"&&e.inputmode?e.inputmode:void 0),o("aria-label",typeof e?.ariaLabel=="string"&&e.ariaLabel?e.ariaLabel:void 0)}function Iu(t){return t===!0?{disabled:!0}:!t||typeof t!="object"?{disabled:!1}:{disabled:!0,reason:typeof t.reason=="string"&&t.reason?t.reason:void 0}}var Nn="persona-composer-control",po="persona-composer-control--glyph",Hu=40,pn=24,Dc=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let s=o.getComputedStyle(t);for(let i of n){let l=s.getPropertyValue(i).trim();l?e.style.setProperty(i,l):e.style.removeProperty(i)}},Oc=(t,e)=>{let n=k("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??ku,n.dir="auto",Wc(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:ka(n)}),Bc(n,t?.composer?.inputAttributes),n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=Rc(t?.composer?.maxLines,e?.defaultMaxLines??3),s=`${o*20}px`;n.style.maxHeight=s,n.style.overflowY="auto";let i=()=>{let c=n.style.maxHeight;if(c!==s){let u=parseFloat(c);if(Number.isFinite(u)&&u>0)return u}let d=o*Pu(n);return s=`${d}px`,n.style.maxHeight=s,d},l=()=>{n.addEventListener("input",()=>{n.style.height="auto";let c=Math.min(n.scrollHeight,i());n.style.height=`${c}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:l}},BA="[data-persona-glyph-stack]",Ru=(t,e,n="send")=>{let o=G("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return t.setAttribute("data-glyph","send"),e.setAttribute("data-glyph","stop"),o.append(t,e),o},_c=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",s=e.iconName,i=e.stopIconName??"square",l=e.tooltipText??"Send message",c=e.stopTooltipText??"Stop generating",d=t?.copy?.sendButtonLabel??"Send",u=t?.copy?.stopButtonLabel??"Stop",g=e.showTooltip??!1,m=e.size,v=parseFloat(m??"")||Hu,h=e.backgroundColor,T=e.textColor,M=k("div","persona-send-button-wrapper"),E=G("button",{className:_n("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Nn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!T&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?T||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":T||void 0,backgroundColor:n&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),I=null,P=null,N=null;if(n){let w=parseFloat(e.iconSize??"")||Math.round(v*.5),O=e.iconStrokeWidth??2,K=T?.trim()||"currentColor";s&&(I=ge(s,w,K,O)),P=ge(i,w,K,O),I&&P?(N=Ru(I,P),E.appendChild(N)):I?E.appendChild(I):(E.textContent=o,P=null)}else E.textContent=d;E.setAttribute("aria-label",l),M.appendChild(E),Qt({anchor:E,trigger:M,text:()=>E.getAttribute("aria-label")??"",enabled:g});let x="send";return{button:E,wrapper:M,setMode:w=>{if(w===x)return;x=w;let O=w==="stop"?c:l;E.setAttribute("aria-label",O),E.setAttribute("data-persona-send-mode",w),n?(E.querySelector(BA)??N)?.setAttribute("data-mode",w):E.textContent=w==="stop"?u:d},glyphStack:N}},li=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),s=e.provider?.type==="runtype",i=e.provider?.type==="custom";if(!(o||s||i))return null;let c=e.iconName??"mic",d=e.iconSize,u=parseFloat(d??"")||pn,g=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,v=k("div","persona-send-button-wrapper"),h=G("button",{className:_n("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nn,!d&&po),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),M=ge(c,u,m||"currentColor",1.5);M?h.appendChild(M):h.textContent="\u{1F3A4}",v.appendChild(h);let E=e.tooltipText??"Start voice recognition",I=e.showTooltip??!1;return Qt({anchor:h,trigger:v,text:()=>h.getAttribute("aria-label")??E,enabled:I}),{button:h,wrapper:v}},Nc=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=k("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(e.allowedTypes??Yo).join(","),o.multiple=(e.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",i=k("div","persona-send-button-wrapper"),l=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Nn} ${po}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),c=ge(s,pn,"currentColor",1.5);c?l.appendChild(c):l.textContent="\u{1F4CE}",l.addEventListener("click",u=>{u.preventDefault(),o.click()}),i.appendChild(l);let d=e.buttonTooltipText??"Attach file";return Qt({anchor:l,trigger:i,text:()=>l.getAttribute("aria-label")??d}),{button:l,wrapper:i,input:o,previewsContainer:n}},Fc=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=k("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let s=e.visible??!0;o.style.display=s?"":"none";let i=e.idleText??"Online";if(e.idleLink){let l=k("a");l.href=e.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=i,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=i;return o},Uc=()=>G("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var DA='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',OA=["--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"],Wu="data-persona-menu-focus",_A=new Set(["ArrowDown","ArrowUp","Home","End"]);function Cb(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(DA)??t}var NA=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function wb(t){let e=t.label,n=!1,o=k("div","persona-send-button-wrapper"),s=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Nn} ${po}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=G("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),l=()=>{let H=t.getButtonSize?.()??"";s.style.width=H,s.style.height=H,s.style.minWidth=H,s.style.minHeight=H,s.style.lineHeight="1",s.replaceChildren();let J=ge("plus",pn,"currentColor",1.5);J?s.appendChild(J):s.textContent="+"},c=()=>{s.setAttribute("aria-label",e),s.setAttribute("title",e),i.setAttribute("aria-label",e)};c(),l();let d=[],u=-1,g=!1,m=()=>{let J=i.getRootNode().activeElement;return J instanceof HTMLElement?J:null},v=()=>{let H=m();for(let J of d){let $=!!H&&Cb(J)===H;J.toggleAttribute(Wu,$&&g)}},h=()=>d.filter(H=>H.isConnected||i.contains(H)).map(Cb).filter(H=>!NA(H)),T=(H,J)=>{H.forEach(($,ae)=>{$.setAttribute("tabindex",ae===J?"0":"-1")})},M=H=>{let J=h();if(J.length===0)return;let $=(H%J.length+J.length)%J.length;u=$,T(J,$),J[$].focus(),v()},E=()=>o.ownerDocument??document,I=null,P=null,N=null,x=()=>{I&&(E().removeEventListener("focusin",I,!0),I=null)},R=()=>{P&&(i.removeEventListener("focusin",P),P=null),N&&(i.removeEventListener("pointerdown",N,!0),N=null)},w=null,O=()=>(w||(w=gc({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),x()}})),w),K=()=>w?.isOpen===!0,ie=(H=!1)=>{if(K()){w?.close(),s.setAttribute("aria-expanded","false"),x(),R(),u=-1,g=!1;for(let J of d)J.removeAttribute(Wu);H&&s.focus()}},Z=(H=0,J=!1)=>{if(n||K())return;g=J,Dc(s,i,OA),O().open(),s.setAttribute("aria-expanded","true");let $=h();T($,-1),M(H<0?$.length-1:H),I=ae=>{let re=typeof ae.composedPath=="function"?ae.composedPath():[];re.includes(i)||re.includes(o)||ie()},E().addEventListener("focusin",I,!0),P=()=>v(),i.addEventListener("focusin",P),N=()=>{g=!1},i.addEventListener("pointerdown",N,!0)},S=H=>{H.preventDefault(),H.stopPropagation(),K()?ie(!0):Z(0)},B=H=>{if(H.key==="ArrowDown"||H.key==="Enter"||H.key===" "){H.preventDefault(),g=!0,K()?M(0):Z(0,!0);return}H.key==="ArrowUp"&&(H.preventDefault(),g=!0,K()?M(-1):Z(-1,!0))},W=H=>{switch(_A.has(H.key)&&(g=!0),H.key){case"ArrowDown":H.preventDefault(),M(u+1);return;case"ArrowUp":H.preventDefault(),M(u-1);return;case"Home":H.preventDefault(),M(0);return;case"End":H.preventDefault(),M(h().length-1);return;case"Escape":H.preventDefault(),H.stopPropagation(),ie(!0);return;case"Tab":ie(!0);return;default:}};return s.addEventListener("click",S),s.addEventListener("keydown",B),i.addEventListener("keydown",W),{trigger:o,triggerButton:s,panel:i,setItems:H=>{for(let $ of d)H.includes($)||$.removeAttribute(Wu);if(d=[...H],!K())return;let J=h();T(J,Math.min(u,J.length-1)),v()},isOpen:K,open:()=>Z(0),close:ie,setLabel:H=>{H!==e&&(e=H,c())},applyButtonSize:l,destroy:()=>{n=!0,x(),R(),s.removeEventListener("click",S),s.removeEventListener("keydown",B),i.removeEventListener("keydown",W),w?.destroy(),w=null,o.remove(),i.remove(),d=[]}}}var To={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Sb="data-persona-composer-action",Bu="data-persona-composer-disable-when-streaming",FA="core:overflow",UA=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function $A(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=k("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let s=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(s)&&s>0?s:Number.isFinite(n)?n:null}function Du(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),s=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-s)}var xb=(t,e)=>{!t||typeof console>"u"||console.warn(e)},qA=(t,e)=>e.includes(":")?e:`${t}:${e}`;function zA(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let d=o.get(c.id);if(d){xb(e,`[Persona] composer action "${c.id}" is already contributed by ${Ab(d)}; the ${Ab(c)} copy is ignored.`);return}o.set(c.id,c),n.push(c)};for(let c of t.builtIns)i({id:c.id,placement:c.placement,presentation:"bar",order:c.order,sequence:s++,source:"core",builtIn:c});let l=(c,d,u)=>{let g=u?qA(u,c.id):c.id,m=c.order??To.custom;c.placement==="end"&&m>=To.send&&(xb(e,`[Persona] composer action "${g}" ordered at ${m} would render after send; clamped to ${To.send-1}.`),m=To.send-1),i({id:g,placement:c.placement,presentation:c.presentation??"bar",order:m,sequence:s++,source:d,pluginId:u,action:c})};for(let c of t.configActions??[])l(c,"config");for(let c of t.plugins){if(!c.contributeComposerActions)continue;let d;try{d=c.contributeComposerActions(t.contributionContext)}catch(u){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,u);continue}for(let u of d??[])l(u,"plugin",c.id)}return n.sort((c,d)=>c.order===d.order?c.sequence-d.sequence:c.order-d.order)}var Ab=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",Mb=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,jA=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function VA(t,e){if(!t||t==="always")return!0;let n=jA(e);return t==="when-text"?n:!n}var Tr=t=>t.kind==="custom",Ou=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,KA=t=>{let e=Ou(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},GA='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function QA(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let s=o;typeof s.matches=="function"&&s.matches(GA)||o.childNodes.forEach(n)};return n(t),e.trim()}var XA=t=>QA(t).length===0;function Eb(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(S,B)=>{let W=S.button;if(!W)return;W.setAttribute("role","menuitem"),W.setAttribute("tabindex","-1"),W.className="persona-composer-overflow-menu__item";for(let $ of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])W.style[$]="";W.style.lineHeight="1",B.tooltipText?W.setAttribute("title",B.tooltipText):W.removeAttribute("title"),W.replaceChildren();let H=k("span","persona-composer-overflow-menu__icon");if(B.iconName){let $=ge(B.iconName,16,"currentColor",1.5);$&&H.appendChild($)}let J=k("span","persona-composer-overflow-menu__label");J.textContent=B.shortLabel??B.label,W.append(H,J)},l=(S,B)=>{let W=S.button;if(!W)return;if(W.setAttribute("aria-label",B.label),B.pressed===void 0?W.removeAttribute("aria-pressed"):W.setAttribute("aria-pressed",B.pressed?"true":"false"),W.toggleAttribute(Bu,B.disableWhenStreaming===!0),S.mode==="menu"){S.tooltip?.destroy(),S.tooltip=void 0,i(S,B);return}W.removeAttribute("role"),W.removeAttribute("tabindex"),W.removeAttribute("title");let H=s(),J=!!B.shortLabel;if(W.className=_n("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Nn,po,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),W.style.width=H&&!J?H:"",W.style.height=H??"",W.style.minWidth=H&&!J?H:"",W.style.minHeight=H??"",W.style.fontSize=J?"":"18px",W.style.lineHeight="1",W.style.color=B.iconColor??"",W.style.backgroundColor=B.backgroundColor??"",W.replaceChildren(),B.iconName){let $=ge(B.iconName,pn,"currentColor",1.5);$&&W.appendChild($)}if(J){let $=k("span","persona-composer-action-button__label");$.textContent=B.shortLabel,W.appendChild($)}else W.firstChild||(W.textContent=B.label);S.tooltip?.destroy(),S.tooltip=Qt({anchor:W,trigger:S.element,text:()=>B.tooltipText??B.label,enabled:!!B.tooltipText})},c=(S,B)=>{let W=S.action,H=G("button",{attrs:{type:"button"}}),J=H;if(B==="bar"){let re=k("div","persona-send-button-wrapper");re.appendChild(H),J=re}J.setAttribute(Sb,S.id);let $={resolved:S,element:J,button:H,owned:!0,managed:!0,busy:!1,visible:!0,mode:B},ae=re=>{if(re.preventDefault(),re.stopPropagation(),$.busy||H.disabled)return;let ue=$.resolved.action;$.mode==="menu"&&h?.close(!0);let Ee;try{Ee=ue.onSelect(t.actionContext,re)}catch(he){t.reportError(he,{actionId:$.resolved.id});return}!Ee||typeof Ee.then!="function"||($.busy=!0,H.setAttribute("aria-busy","true"),Ee.catch(he=>{t.reportError(he,{actionId:$.resolved.id})}).finally(()=>{$.busy=!1,H.removeAttribute("aria-busy")}))};return H.addEventListener("click",ae),$.detach=()=>H.removeEventListener("click",ae),l($,W),$},d=S=>{let B=S.action,W;try{W=B.render({...t.actionContext,id:S.id,action:B})}catch(H){return t.reportError(H,{actionId:S.id}),null}return W?.element?(W.element.setAttribute(Sb,S.id),W.element.toggleAttribute(Bu,B.disableWhenStreaming===!0),{resolved:S,element:W.element,owned:!0,managed:!0,destroy:W.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(S,B)=>{if(S.builtIn){let H=S.builtIn.element;return H?{resolved:S,element:H,owned:!1,managed:S.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let W=S.action;return W?Tr(W)?d(S):c(S,B):null},g=S=>{if(S.detach?.(),S.tooltip?.destroy(),S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0,S.owned){try{S.destroy?.()}catch(B){t.reportError(B,{actionId:S.resolved.id})}S.element.remove()}},m=(S,B)=>{for(let W=0;W<B.length;W++){let H=B[W];if(!H.managed)continue;let J=null;for(let $=W+1;$<B.length;$++){let ae=B[$];if(!ae.managed&&ae.element.parentElement===S){J=ae.element;break}}J?(H.element.parentElement!==S||H.element.nextSibling!==J)&&S.insertBefore(H.element,J):S.lastChild!==H.element&&S.appendChild(H.element)}},v=(S,B)=>{if(S.button){S.button.disabled=B;return}if(!S.owned)return;let W=S.element;W.toggleAttribute("data-disabled",B),W.setAttribute("aria-disabled",B?"true":"false");let H=W instanceof HTMLButtonElement||W instanceof HTMLSelectElement||W instanceof HTMLInputElement||W instanceof HTMLTextAreaElement?W:W.querySelector("button, select, input, textarea");H&&(H.disabled=B)},h=null,T=null,M=null,E=0,I=()=>{let S=t.getOverflow?.();return S?.enabled===!0?S:void 0},P=()=>(h?h.setLabel(t.getOverflowLabel?.()??"More actions"):h=wb({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),h),N=S=>{T!==S&&(M?.disconnect(),T=S,E=Du(S),!(typeof ResizeObserver>"u")&&(M=new ResizeObserver(B=>{let H=B[B.length-1]?.contentRect?.width??Du(S);H!==E&&(E=H,ie())}),M.observe(S)))},x=(S,B)=>{let W=$A(S.collapseAutoActionsBelow,B);if(W===null)return!1;let H=E||Du(B);return H>0&&H<W},R=(S,B,W)=>{if(!B)return"bar";if(S.resolved.builtIn){let J=UA(S.resolved.id);return J&&B.includeBuiltIns?.includes(J)?"menu":"bar"}let H=S.resolved.presentation;return H==="overflow"||H==="auto"&&W?"menu":"bar"},w=S=>{let B=S.menuSlot;if(!B)return;if(!XA(S.element)){S.menuLabel?.remove(),S.menuLabel=void 0;return}let W=KA(S.element);if(!W){S.menuLabel?.remove(),S.menuLabel=void 0;return}S.menuLabel||(S.menuLabel=k("span","persona-composer-overflow-menu__label")),S.menuLabel.textContent!==W&&(S.menuLabel.textContent=W),S.menuLabel.parentElement!==B&&B.appendChild(S.menuLabel)},O=(S,B)=>{if(S.mode===B)return S;let W=S.resolved.action;if(W&&!Tr(W)){g(S),e.delete(S.resolved.id);let H=c(S.resolved,B);return e.set(S.resolved.id,H),H}if(B==="menu"){let H=G("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Tu]:""}});H.appendChild(S.element),ub(Ou(S.element)),S.menuSlot=H;let J=$=>{let ae=Ou(S.element);if(ae.disabled)return;let re=$.target===ae||ae.contains($.target);h?.close(!0),re||ae.click()};H.addEventListener("click",J,!0),S.detachMenuSlot=()=>H.removeEventListener("click",J,!0),S.managed=!0,w(S)}else S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0;return S.mode=B,S},K=(S,B)=>{let W=B.map(H=>H.menuSlot??H.element);for(W.forEach((H,J)=>{let $=S.children[J];$!==H&&($?S.insertBefore(H,$):S.appendChild(H))});S.children.length>W.length;)S.lastElementChild?.remove()},ie=()=>{if(o)return;let S=t.getBindings();if(!S)return;let B=t.getState(),W=B.phase==="streaming",H=I();H&&N(S.footer);let J=H?x(H,S.footer):!1,$={start:[],end:[]},ae=[];for(let re of n){let ue=e.get(re.id);if(!ue)continue;let Ee=re.action,he=Ee?Mb(Ee.visible,B,!0)&&VA(Ee.visibility,B):!0;if(ue.visible!==he&&(ue.visible=he,!he&&ue.managed&&(ue.menuSlot??ue.element).remove()),!!he){if(ue=O(ue,R(ue,H,J)),Ee){let ce=Mb(Ee.disabled,B,!1)||Ee.disableWhenStreaming===!0&&W;v(ue,ce),!Tr(Ee)&&Ee.pressed!==void 0&&ue.button?.setAttribute("aria-pressed",Ee.pressed?"true":"false")}ue.mode==="menu"?(w(ue),ae.push(ue)):$[re.placement].push(ue)}}if(ae.length>0){let re=P();K(re.panel,ae),re.setItems(ae.map(ce=>ce.menuSlot??ce.element)),re.applyButtonSize();let ue=Number.isFinite(H?.order)?H?.order:To.overflow,Ee=$.start.findIndex(ce=>ce.resolved.order>ue),he={resolved:{id:FA,placement:"start",presentation:"bar",order:ue,sequence:-1,source:"core"},element:re.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};$.start.splice(Ee<0?$.start.length:Ee,0,he)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(S.actionsStart,$.start),m(S.actionsEnd,$.end)};return{resolve:()=>{if(o)return;let S=zA(t.collect()),B=new Set(S.map(W=>W.id));for(let[W,H]of e)B.has(W)||(g(H),e.delete(W));for(let W of S){let H=e.get(W.id);if(!H){let re=u(W,"bar");re&&e.set(W.id,re);continue}let J=H.resolved.action,$=W.action;if(!!J!=!!$||J&&$&&Tr(J)!==Tr($)||J&&$&&Tr(J)&&Tr($)&&J.render!==$.render){g(H),e.delete(W.id);let re=u(W,H.mode);re&&e.set(W.id,re);continue}H.resolved=W,W.builtIn?(H.managed=W.builtIn.managed===!0||H.mode==="menu",W.builtIn.element&&H.mode==="bar"&&(H.element=W.builtIn.element)):$&&!Tr($)?l(H,$):$&&H.element.toggleAttribute(Bu,$.disableWhenStreaming===!0)}n=S,ie()},sync:ie,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,M?.disconnect(),M=null,T=null;for(let S of e.values())g(S);e.clear(),h?.destroy(),h=null,n=[]}}}}var YA="core:model",JA=700,Tb=16,ZA=["--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"],kb=()=>{let t=G("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=G("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Pb(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=d=>{let u=t.getSelectedModelId();return d.find(g=>g.id===u)??d[0]},i=()=>{let d=G("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),u="",g=()=>{let M=t.getModels(),E=M.map(I=>`${I.id}:${I.label}`).join("|");E!==u&&(u=E,d.replaceChildren(...M.map(I=>{let P=G("option",{attrs:{value:I.id}});return P.textContent=I.label,P}))),d.value=s(M)?.id??""};g(),o=g;let m=()=>{d.value&&t.onSelect(d.value)};d.addEventListener("change",m);let v=M=>M.stopPropagation();d.addEventListener("click",v);let{wrapper:h,chevron:T}=kb();return h.append(d,T),{element:h,destroy:()=>{o===g&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",v)}}},l=()=>{let d=G("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=k("span","persona-composer-model-picker-label"),g=k("span","persona-composer-model-picker-suffix");d.append(u,g);let m=G("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),v=new Map,h="",T=null,M=()=>T?.isOpen===!0,E=(B=!1)=>{M()&&(T?.close(),d.setAttribute("aria-expanded","false"),B&&d.focus())},I=B=>{let W=[...v.values()];if(W.length===0)return;let H=(B%W.length+W.length)%W.length;W[H].focus()},P=B=>{if(M())return;T||(T=gc({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),Dc(d,m,ZA),T.open(),d.setAttribute("aria-expanded","true");let H=[...v.keys()].indexOf(s(t.getModels())?.id??"");I(B??(H>=0?H:0))},N=B=>{E(!0),t.onSelect(B)},x=B=>{B.preventDefault(),B.stopPropagation();let W=B.currentTarget.getAttribute("data-persona-model-option");W&&N(W)},R=B=>{let W=G("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":B.id}});if(B.icon){let re=ge(B.icon,Tb,"currentColor",1.5);if(re){let ue=k("span","persona-composer-model-option-icon");ue.appendChild(re),W.appendChild(ue)}}let H=k("span","persona-composer-model-option-body"),J=k("span","persona-composer-model-option-label");if(J.textContent=B.label,H.appendChild(J),B.description){let re=k("span","persona-composer-model-option-description");re.textContent=B.description,H.appendChild(re)}W.appendChild(H);let $=k("span","persona-composer-model-option-check");$.setAttribute("aria-hidden","true");let ae=ge("check",Tb,"currentColor",2);return ae&&$.appendChild(ae),W.appendChild($),W.addEventListener("click",x),W},w=()=>{let B=t.getModels(),W=B.map($=>`${$.id}:${$.label}:${$.icon??""}:${$.description??""}`).join("|");if(W!==h){h=W;for(let $ of v.values())$.removeEventListener("click",x);v.clear(),m.replaceChildren(...B.map($=>{let ae=R($);return v.set($.id,ae),ae}))}let H=s(B);for(let[$,ae]of v)ae.setAttribute("aria-selected",String($===H?.id));u.textContent=H?.label??"";let J=t.getSuffix?.()??"";g.textContent=J,d.setAttribute("aria-label",[e,[H?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};w(),o=w;let O=B=>{B.preventDefault(),B.stopPropagation(),M()?E(!0):P()},K=B=>{if(B.key==="ArrowDown"){B.preventDefault(),M()?I(0):P(0);return}B.key==="ArrowUp"&&(B.preventDefault(),M()?I(-1):P(-1))},ie=B=>{let W=[...v.values()],H=W.indexOf(B.target?.closest?.(".persona-composer-model-option"));switch(B.key){case"ArrowDown":B.preventDefault(),I(H+1);return;case"ArrowUp":B.preventDefault(),I(H-1);return;case"Home":B.preventDefault(),I(0);return;case"End":B.preventDefault(),I(W.length-1);return;case"Escape":B.preventDefault(),B.stopPropagation(),E(!0);return;case"Tab":E(!0);return;default:}};d.addEventListener("click",O),d.addEventListener("keydown",K),m.addEventListener("keydown",ie);let{wrapper:Z,chevron:S}=kb();return Z.append(d,S),{element:Z,destroy:()=>{o===w&&(o=null),d.removeEventListener("click",O),d.removeEventListener("keydown",K),m.removeEventListener("keydown",ie);for(let B of v.values())B.removeEventListener("click",x);v.clear(),T?.destroy(),T=null,m.remove()}}};return{action:{id:YA,kind:"custom",placement:"end",order:JA,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var eM=":scope > [data-persona-composer-mode]";function Ib(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=u=>{let g=G("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let T=k("span","persona-mention-chip-icon"),M=ge(u.iconName,12,"currentColor",1.5);M&&T.appendChild(M),g.appendChild(T)}let m=k("span","persona-mention-chip-label");m.textContent=u.shortLabel??u.label,g.appendChild(m);let v=G("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),h=ge("x",12,"currentColor",2);return h?v.appendChild(h):v.textContent="\xD7",v.addEventListener("click",T=>{T.preventDefault(),T.stopPropagation(),t.onRemove(u.id)}),g.appendChild(v),g},l=()=>Array.from(e.querySelectorAll(eM)),c=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let g=()=>{u.remove(),fc(e)},m=e.ownerDocument.defaultView,v=typeof m?.getComputedStyle=="function"?m.getComputedStyle(u).animationName:"";if(!v||v==="none"){g();return}u.addEventListener("animationend",g,{once:!0}),u.addEventListener("animationcancel",g,{once:!0})},d=()=>{for(let u of l())u.remove()};return{element:e,render:(u,g)=>{if(o)return;let m=g.filter(M=>u.includes(M.id)),v=m.map(M=>`${M.id}:${M.shortLabel??M.label}`).join("|");if(v===n)return;n=v;let h=new Map;for(let M of l()){let E=M.getAttribute("data-persona-composer-mode");E&&m.some(P=>P.id===E)&&!M.hasAttribute("data-persona-chip-exit")?h.set(E,M):M.hasAttribute("data-persona-chip-exit")||c(M)}let T=e.firstChild;for(let M of m){let E=h.get(M.id);E||(E=i(M),s.has(M.id)||(E.setAttribute("data-persona-chip-enter",""),E.addEventListener("animationend",()=>E?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(M.id),E!==T&&e.insertBefore(E,T),T=E.nextSibling}fc(e)},destroy:()=>{o=!0,d(),fc(e)}}}var Lb=t=>`core:mode:${t}`;var _u=t=>Math.min(300+t,499),Hb=t=>`core:mode-group:${t}`;function $c(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function tM(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Rb(t,e){return t?.length?t.filter(n=>!$c(n.groupId,e)&&!tM(n.groupId,e)):[]}var nM=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Wb(t,e,n,o){let s=n.find(c=>c.id===e);if(!s)return[...t];let i=t.includes(e),l=new Set(t);if(i)l.delete(e);else{if(nM(s,o)==="single"){let c=n.filter(d=>d.groupId===s.groupId).map(d=>d.id);l=new Set([...l].filter(d=>!c.includes(d)))}l.add(e)}return n.filter(c=>l.has(c.id)).map(c=>c.id)}function qc(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Bb(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Db(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var oM=16;function Ob(t){let e=null;return{action:{id:Hb(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=G("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=u=>{u.preventDefault(),u.stopPropagation();let m=u.currentTarget.getAttribute("data-persona-composer-mode");!m||t.getActiveIds().includes(m)&&t.getGroup()?.selection==="single"||t.onSelect(m)},c=u=>{let g=G("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let v=ge(u.iconName,oM,"currentColor",1.5);v&&g.appendChild(v)}let m=k("span","persona-composer-segmented-label");return m.textContent=u.shortLabel??u.label,g.appendChild(m),g.addEventListener("click",l),g},d=()=>{let u=t.getGroup();u?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",u.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let g=t.getModes(),m=g.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==i){i=m;for(let T of s.values())T.removeEventListener("click",l);s.clear();let h=g.map(T=>{let M=c(T);return s.set(T.id,M),M});o.replaceChildren(...h)}let v=t.getActiveIds();for(let[h,T]of s)T.setAttribute("aria-pressed",String(v.includes(h)))};return d(),e=d,{element:o,destroy:()=>{e===d&&(e=null);for(let u of s.values())u.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function _b(t){let e=G("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,s=i=>{let l=k("span","persona-composer-quote-bar"),c=k("div","persona-composer-quote-content");if(i.sourceLabel){let m=k("div","persona-composer-quote-source");m.textContent=i.sourceLabel,c.appendChild(m)}let d=G("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=Ec(i.text),c.appendChild(d);let u=G("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),g=ge("x",12,"currentColor",2);g?u.appendChild(g):u.textContent="\xD7",u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),t.onDismiss()}),e.replaceChildren(l,c,u)};return{element:e,render:i=>{if(o)return;let l=i?`${i.sourceLabel??""}\0${i.text}`:"";if(l!==n){if(n=l,!i){e.replaceChildren(),e.style.display="none";return}s(i),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function Nb(t){let e=G("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,d,u)=>{let g=G("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[d]:""}}),m=ge(l,12,"currentColor",2);return m?g.appendChild(m):g.textContent=c,g.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),u()}),g},i=l=>{let c=Ec(l.text??"",90);if(c)return c;let d=l.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(l.mentionRefs?.length??0)>0?l.mentionRefs.map(g=>g.label).join(", "):"Queued message"};return{element:e,render:l=>{if(o||l===n)return;if(n=l,!l){e.replaceChildren(),e.style.display="none";return}let c=k("span","persona-composer-pending-badge");c.textContent=t.label??"Sends next";let d=G("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});d.textContent=i(l),e.replaceChildren(c,d,s("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),s("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function Fb(t){let e=G("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=G("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let s=k("div","persona-message-edit-actions"),i=(c,d,u,g)=>{let m=G("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[u]:""},text:c});return m.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),g()}),m},l=()=>{let c=n.value.trim();c&&t.onSave(c)};return s.append(i(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),i(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",l)),n.addEventListener("keydown",c=>{if(c.key==="Escape"){c.preventDefault(),c.stopPropagation(),t.onCancel();return}c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),l())}),e.append(n,s),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let c=n.value.length;n.setSelectionRange(c,c),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function Ub(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function $b(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(d=>n.has(d.sourceId)),s=o.length===(t.mentionRefs?.length??0)&&o.length>0,i=new Set(e.modes.map(d=>d.id)),l=(t.activeModeIds??[]).filter(d=>i.has(d)),c=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...s?{mentionRefs:o}:{},...s&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...c?{selectedModelId:c}:{},...l.length?{activeModeIds:l}:{},...t.quote?.text?{quote:t.quote}:{}}}function qb(t){let e=t.delay??500,n=null,o=!1,s=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(s(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(s(),t.write())},cancel:s,destroy:()=>{o=!0,s()}}}function zb(t){return t.wrapped||t.text.includes(`
|
|
17
|
+
`)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function jb(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function Vb(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),s=Number.parseFloat(n.fontSize),i=Number.isFinite(o)&&o>0?o:Number.isFinite(s)&&s>0?s*1.4:0;if(!i)return!1;let l=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-l>i*1.5}function Nu(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function Gb(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var rM=t=>typeof t?.then=="function";function Kb(t,e){return e===!1?{status:"canceled"}:!e||typeof e!="object"?{status:"proceed"}:(typeof e.text=="string"&&(t.text=e.text),e.options&&(t.options={...t.options,...e.options}),{status:"proceed"})}function Qb(t,e,n){let o;try{o=t(Nu(e),{signal:n})}catch(s){return{status:"error",error:s}}return rM(o)?Promise.resolve(o).then(s=>n.aborted?{status:"aborted"}:Kb(e,s),s=>n.aborted?{status:"aborted"}:{status:"error",error:s}):Kb(e,o)}function Xb(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",s=e.buttonTooltipText??"Add context",i=k("div","persona-send-button-wrapper"),l=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Nn} ${po}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":s,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),c=ge(o,pn,"currentColor",1.5);return c?l.appendChild(c):l.textContent="+",l.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),i.appendChild(l),Qt({anchor:l,trigger:i,text:()=>l.getAttribute("aria-label")??s}),{button:l,wrapper:i}}var{setLoader:EP,load:sM}=Tt({fallbackImport:()=>import("./context-mentions-45MODWOY.js")});var Fu=sM;var{setLoader:PP,load:iM}=Tt({fallbackImport:()=>import("./context-mentions-inline-I2RDEBAK.js"),resetOnSetLoader:!0});var Yb=iM;function Pa(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=G("span",{className:_n("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=ge(t.iconName??"at-sign",13,"currentColor",2);if(o){let s=k("span","persona-mention-token-icon");s.appendChild(o),n.appendChild(s)}return n.appendChild(G("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function Jb(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=jh(e).filter(x=>x.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(x=>x.sources.some(R=>typeof R.matchCommand=="function")),s=x=>o.some(R=>R.trigger?R.position==="line-start"?x.split(`
|
|
18
|
+
`).some(O=>O.startsWith(R.trigger)):(R.position==="anywhere"?x:x.split(`
|
|
19
|
+
`)[0]).startsWith(R.trigger):!1),i=(x,R)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${x}`,{detail:R}))}catch{}},l=!t.chipRow,c=t.chipRow??G("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,u=null,g=t.textarea,m=null,v=null,h=null,T=null,M=()=>{if(d)return Promise.resolve(d);if(u)return u;let x=Fu().then(R=>(R.setMentionIconRenderer(ge),d=R.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:m??void 0,anchor:t.anchor,contextRow:c,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:N,emit:i}),d)).catch(R=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",R),u===x&&(u=null),null));return u=x,x},E=()=>{Yb().then(x=>{let R=x.mountInlineComposer({textarea:t.textarea,renderToken:O=>Pa(O,{render:e.renderMentionToken}),onMentionRemoved:O=>d?.untrackMention(O)});m=R.input,v=R.destroy;let w=g;w.replaceWith(R.element),g=R.element,T={next:R.element,prev:w},h?.(R.element,w),d?d.rebindComposer(R.input):u&&u.then(O=>O?.rebindComposer(R.input))}).catch(x=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",x)})};e.display==="inline"&&E();let I=[],P=new Map;for(let x of n){if(!x.showButton)continue;let R=Xb({config:{...e,buttonIconName:x.buttonIconName,buttonTooltipText:x.buttonTooltipText},onOpen:()=>{M().then(w=>w?.openMenu(x.trigger))}});I.push(R),P.set(x.trigger,R.button)}let N=(x,R,w)=>{let O=P.get(R);O&&(O.setAttribute("aria-expanded",x?"true":"false"),x?O.setAttribute("aria-controls",w):O.removeAttribute("aria-controls"))};return{affordanceButtons:I.map(x=>x.wrapper),contextRow:c,handleInput:x=>{if(d){d.handleInput();return}if(!zh(x))return;let R=g,w=R.selectionStart??0;qh(R.value,w,n)&&M().then(O=>O?.handleInput())},handleKeydown:x=>{if(d?.isMenuOpen())return d.handleKeydown(x);if(x.key==="Backspace"&&d?.hasMentions()&&!T){let R=g,w=R.selectionStart===0&&R.selectionEnd===0;if((R.value.length===0||w)&&d.removeLastChip())return x.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async x=>s(x)?(d??await M())?.dispatchInlineCommand(x)??null:null,clear:()=>d?.clear(),prefetch:()=>{Fu().catch(()=>{})},onComposerSwap:x=>{h=x,T&&x(T.next,T.prev)},destroy:()=>{d?.destroy(),v?.();for(let x of I)x.wrapper.remove();l&&c.remove()}}}var zc="16px",jc="transparent",aM=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),lM={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:aM,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"}},cM={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"}},dM={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:Jo,maxWidth:hb,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:zc,canvasBackground:jc},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 un(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let s of n){if(o==null)return;o=o[s]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?un(t,o):o}function ev(t){let e={};function n(o,s){for(let[i,l]of Object.entries(o)){let c=`${s}.${i}`;if(typeof l=="string"){let d=un(t,l);d!==void 0&&(e[c]={path:c,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof l=="object"&&l!==null&&n(l,c)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function pM(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function tv(t,e){let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];i&&typeof i=="object"&&!Array.isArray(i)&&s&&typeof s=="object"&&!Array.isArray(s)?n[o]=tv(i,s):n[o]=s}return n}function uM(t,e){return e?tv(t,e):t}function ci(t,e={}){let n={palette:lM,semantic:cM,components:dM},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:uM(n.components,t?.components)};if(e.validate!==!1){let s=pM(o);if(!s.valid)throw new Error(`Theme validation failed: ${s.errors.map(i=>i.message).join(", ")}`)}if(e.plugins)for(let s of e.plugins)o=s.transform(o);return o}var Uu=t=>t.trim()==="0"?"0px":t,Zb="--persona-",gM=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let l=e.slice(1);if(!/^[0-9a-f]+$/.test(l))return;l.length===3||l.length===4?n=[0,1,2].map(c=>parseInt(l[c]+l[c],16)):(l.length===6||l.length===8)&&(n=[0,2,4].map(c=>parseInt(l.slice(c,c+2),16)))}else{let l=e.match(/^rgba?\(([^)]+)\)$/);if(l){let c=l[1].split(/[,/\s]+/).filter(Boolean);c.length>=3&&(n=c.slice(0,3).map(d=>{let u=d.endsWith("%"),g=parseFloat(u?d.slice(0,-1):d);return u?g/100*255:g}))}}if(!n||n.some(l=>!Number.isFinite(l)))return;let[o,s,i]=n.map(l=>{let c=Math.max(0,Math.min(255,l))/255;return c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4)});return .2126*o+.7152*s+.0722*i},fM=.179,Xt=(t,e)=>{for(let[n,...o]of e){let s;for(let i of o)if(s=i.charCodeAt(0)===61?i.slice(1):t[Zb+i],s!==void 0)break;s!==void 0&&(t[Zb+n]=s)}};function nv(t){let e=ev(t),n={};for(let[F,Te]of Object.entries(e)){let Ue=F.replace(/\./g,"-");n[`--persona-${Ue}`]=Te.value}Xt(n,[["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 o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],Xt(n,[["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"]]),Xt(n,[["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"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,Xt(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??zc,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??jc,Xt(n,[["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"]]),Xt(n,[["header-bg","components-header-background","surface"]]);let s=n["--persona-header-bg"],i=n["--persona-components-header-foreground"],l=i?`color-mix(in srgb, ${i} 72%, ${s})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(i?`color-mix(in srgb, ${i} 14%, ${s})`:void 0)??n["--persona-divider"],Xt(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??i??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??l??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??l??n["--persona-muted"],Xt(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let c=t.components?.header;c?.shadow&&(n["--persona-header-shadow"]=c.shadow),c?.borderBottom&&(n["--persona-header-border-bottom"]=c.borderBottom),c?.minHeight&&(n["--persona-header-min-height"]=c.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let u=n["--persona-components-history-railHeader-border"];u&&(n["--persona-history-rail-header-border"]=u);let g=n["--persona-components-history-railHeader-minHeight"];g&&(n["--persona-history-rail-header-min-height"]=g);for(let[F,Te]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ue=n[`--persona-components-history-overlay-${F}`];Ue&&(n[`--persona-history-overlay-${Te}`]=Ue)}for(let[F,Te]of[["background","bg"],["borderRadius","radius"]]){let Ue=n[`--persona-components-history-menu-${F}`];Ue&&(n[`--persona-history-menu-${Te}`]=Ue)}let m=t.components?.history?.motion;if(m){let F=qt=>{if(qt===void 0)return;let Le=String(qt).trim();return/^\d+(\.\d+)?$/.test(Le)?`${Le}ms`:Le},Te=F(m.enterDurationMs);Te!==void 0&&(n["--persona-history-enter-ms"]=Te);let Ue=F(m.exitDurationMs);Ue!==void 0&&(n["--persona-history-exit-ms"]=Ue),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let v=n["--persona-components-history-dangerForeground"];v&&(n["--persona-history-danger-fg"]=v),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let F of["scrim","shadow"]){let Te=n[`--persona-components-history-confirm-${F}`];Te&&(n[`--persona-history-confirm-${F}`]=Te)}for(let[F,Te]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ue=n[`--persona-components-tooltip-${F}`];Ue&&(n[`--persona-tooltip-${Te}`]=Ue)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[F,Te]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ue=n[`--persona-components-messageActions-${F}`];Ue&&(n[`--persona-message-action-${Te}`]=Ue)}Xt(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],T=n["--persona-components-introCard-shadow"],M=(!h||h==="transparent"||h==="none")&&(!T||T==="none"),E=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=M&&E==="1.5rem"?"1.5rem 0":E,Xt(n,[["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"]]),Xt(n,[["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 I=n["--persona-components-markdown-heading-h1-fontSize"];I&&(n["--persona-md-h1-size"]=I);let P=n["--persona-components-markdown-heading-h1-fontWeight"];P&&(n["--persona-md-h1-weight"]=P);let N=n["--persona-components-markdown-heading-h2-fontSize"];N&&(n["--persona-md-h2-size"]=N);let x=n["--persona-components-markdown-heading-h2-fontWeight"];x&&(n["--persona-md-h2-weight"]=x);let R=n["--persona-components-markdown-prose-fontFamily"];R&&R!=="inherit"&&(n["--persona-md-prose-font-family"]=R),Xt(n,[["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"]]),Xt(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Xt(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Xt(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Xt(n,[["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"]]),n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],Xt(n,[["message-border","components-message-border","border"]]),Xt(n,[["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 w=t.components,O=w?.iconButton;O&&(O.background&&(n["--persona-icon-btn-bg"]=O.background),O.border&&(n["--persona-icon-btn-border"]=O.border),O.color&&(n["--persona-icon-btn-color"]=O.color),O.padding&&(n["--persona-icon-btn-padding"]=O.padding),O.borderRadius&&(n["--persona-icon-btn-radius"]=O.borderRadius),O.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=O.hoverBackground),O.hoverColor&&(n["--persona-icon-btn-hover-color"]=O.hoverColor),O.activeBackground&&(n["--persona-icon-btn-active-bg"]=O.activeBackground),O.activeBorder&&(n["--persona-icon-btn-active-border"]=O.activeBorder));let K=w?.labelButton;K&&(K.background&&(n["--persona-label-btn-bg"]=K.background),K.border&&(n["--persona-label-btn-border"]=K.border),K.color&&(n["--persona-label-btn-color"]=K.color),K.padding&&(n["--persona-label-btn-padding"]=K.padding),K.borderRadius&&(n["--persona-label-btn-radius"]=K.borderRadius),K.hoverBackground&&(n["--persona-label-btn-hover-bg"]=K.hoverBackground),K.fontSize&&(n["--persona-label-btn-font-size"]=K.fontSize),K.gap&&(n["--persona-label-btn-gap"]=K.gap));let ie=w?.toggleGroup;ie&&(ie.gap&&(n["--persona-toggle-group-gap"]=ie.gap),ie.borderRadius&&(n["--persona-toggle-group-radius"]=ie.borderRadius));let Z=w?.artifact;if(Z?.toolbar){let F=Z.toolbar;F.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=F.iconHoverColor),F.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=F.iconHoverBackground),F.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=F.iconPadding),F.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=F.iconBorderRadius),F.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=F.iconBorder),F.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Uu(F.toggleGroupGap)),F.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=F.toggleBorderRadius),F.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Uu(F.toggleGroupPadding)),F.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=F.toggleGroupBorder),F.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=F.toggleGroupBorderRadius),F.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=un(t,F.toggleGroupBackground)??F.toggleGroupBackground),F.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=F.copyBackground),F.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=F.copyBorder),F.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=F.copyColor),F.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Uu(F.copyBorderRadius)),F.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=F.copyPadding),F.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=F.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??F.copyMenuBackground),F.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=F.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??F.copyMenuBorder),F.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=F.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??F.copyMenuShadow),F.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=F.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??F.copyMenuBorderRadius),F.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=F.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??F.copyMenuItemHoverBackground),F.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=F.iconBackground),F.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=F.toolbarBorder)}if(Z?.tab){let F=Z.tab;F.background&&(n["--persona-artifact-tab-bg"]=F.background),F.activeBackground&&(n["--persona-artifact-tab-active-bg"]=F.activeBackground),F.activeBorder&&(n["--persona-artifact-tab-active-border"]=F.activeBorder),F.borderRadius&&(n["--persona-artifact-tab-radius"]=F.borderRadius),F.textColor&&(n["--persona-artifact-tab-color"]=F.textColor),F.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=F.hoverBackground),F.listBackground&&(n["--persona-artifact-tab-list-bg"]=F.listBackground),F.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=F.listBorderColor),F.listPadding&&(n["--persona-artifact-tab-list-padding"]=F.listPadding)}if(Z?.pane){let F=Z.pane;if(F.toolbarBackground){let Te=un(t,F.toolbarBackground)??F.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Te}}if(Z?.card){let F=Z.card;F.background&&(n["--persona-artifact-card-bg"]=F.background),F.border&&(n["--persona-artifact-card-border"]=F.border),F.borderRadius&&(n["--persona-artifact-card-radius"]=F.borderRadius),F.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=F.hoverBackground),F.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=F.hoverBorderColor)}if(Z?.inline){let F=Z.inline;F.background&&(n["--persona-artifact-inline-bg"]=un(t,F.background)??F.background),F.border&&(n["--persona-artifact-inline-border"]=F.border),F.borderRadius&&(n["--persona-artifact-inline-radius"]=F.borderRadius),F.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=un(t,F.chromeBackground)??F.chromeBackground),F.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=un(t,F.chromeBorder)??F.chromeBorder),F.titleColor&&(n["--persona-artifact-inline-title-color"]=un(t,F.titleColor)??F.titleColor),F.mutedColor&&(n["--persona-artifact-inline-muted-color"]=un(t,F.mutedColor)??F.mutedColor),F.frameHeight&&(n["--persona-artifact-inline-frame-height"]=F.frameHeight)}let S=w?.code;S&&(S.keywordColor&&(n["--persona-code-keyword-color"]=S.keywordColor),S.stringColor&&(n["--persona-code-string-color"]=S.stringColor),S.commentColor&&(n["--persona-code-comment-color"]=S.commentColor),S.numberColor&&(n["--persona-code-number-color"]=S.numberColor),S.tagColor&&(n["--persona-code-tag-color"]=S.tagColor),S.attrColor&&(n["--persona-code-attr-color"]=S.attrColor),S.propertyColor&&(n["--persona-code-property-color"]=S.propertyColor),S.lineNumberColor&&(n["--persona-code-line-number-color"]=S.lineNumberColor),S.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=S.gutterBorderColor),S.background&&(n["--persona-code-bg"]=un(t,S.background)??S.background));let B=n["--persona-surface"],W=n["--persona-container"],H=n["--persona-palette-colors-gray-100"]??"#f3f4f6",J=n["--persona-palette-colors-gray-200"]??"#e5e7eb",$=n["--persona-palette-colors-gray-300"]??"#d1d5db",ae=!W||W===B,re=gM(B??n["--persona-background"]),ue=ae&&re!==void 0&&re<fM,Ee=ue?"rgba(255, 255, 255, 0.08)":H,he=ue?"rgba(255, 255, 255, 0.12)":J,ce=ue?"rgba(255, 255, 255, 0.16)":$,at=ae?Ee:W,ye=ae?he:W;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??at,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ye,ae&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ce),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??at,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??at,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??at,n}var mM={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"}}},hM={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)"}}}},ov=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},$u=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",yM=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":$u()},rv=t=>yM(t),bM=t=>ci(t),vM=t=>{let e=ai(hM,t??{})??{};return ci({...e,palette:{...e.palette,colors:{...mM.colors,...e.palette?.colors}}},{validate:!1})},di=t=>{let e=rv(t),n=ov(t?.theme),o=ov(t?.darkTheme);return e==="dark"?vM(ai(n??{},o??{})):bM(n)},CM=t=>nv(t),Ia=(t,e)=>{let n=di(e),o=CM(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",rv(e))},Vc=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t($u())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t($u());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};import{Activity as MC,Check as EC,Copy as TC}from"lucide";var kr=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Kc="24px",qu=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",La=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},sv=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var iv=null;var zu=()=>{if(iv!==null)return iv;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},wM="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Gc=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},Qc=t=>{let e=t.toLowerCase().split("+").map(s=>s.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let s of e)if(s==="mod"||s==="cmd"||s==="ctrl")o.mod=!0;else if(s==="shift")o.shift=!0;else if(s==="alt"||s==="option")o.alt=!0;else return Gc("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Gc("unsupported",t),null):(n==="space"&&(o.key=" "),o)},SM=t=>wM.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),av=(t,e)=>{let n=Qc(t);if(!n)return"";let o=zu(),s=SM(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${s}`;let i=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&i.push("Alt"),n.shift&&i.push("Shift"),i.push(s),i.join("+")},Xc=t=>av(t,!1),Ha=t=>av(t,!0),xM=(t,e)=>e.key?.toLowerCase()===t.key&&(zu()?e.metaKey:e.ctrlKey)===t.mod&&!(zu()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,AM=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},lv=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(i,l)=>{if((i.scope??"widget")==="page")return!0;if(!t)return!1;let c=l.composedPath?.();return c?.length?c.includes(t):t.contains(l.target)},s=i=>{if(i.isComposing||!e.size)return;let l=i.composedPath?.()[0]??i.target;for(let c of e.values())if(xM(c.parsed,i)&&c.when?.()!==!1&&o(c,i)&&!(!c.allowInInput&&AM(l))){i.preventDefault();try{c.run(i)}catch(d){Gc(`${c.id} threw on`,c.combo),console.warn(d)}return}};return n?.addEventListener("keydown",s),{register(i){let l=Qc(i.combo);if(!l)return()=>{};let c=`${l.mod?"m":""}${l.shift?"s":""}${l.alt?"a":""}${l.key}`,d=e.get(c);return d?(Gc(`${d.id} already owns`,i.combo),()=>{}):(e.set(c,{...i,parsed:l}),i.element?.setAttribute("aria-keyshortcuts",Ha(i.combo)),()=>{e.get(c)?.id===i.id&&e.delete(c),i.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",s)}}};import{Idiomorph as MM}from"idiomorph";var Yc=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;MM.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,i){if(s instanceof HTMLElement&&o){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-tool-elapsed"))return i instanceof HTMLElement&&i.getAttribute("data-tool-elapsed")===s.getAttribute("data-tool-elapsed")?!1:void 0;if(s.hasAttribute("data-preserve-animation")){if(i instanceof HTMLElement&&!i.hasAttribute("data-preserve-animation"))return;if(i instanceof HTMLElement&&i.hasAttribute("data-preserve-animation")){let l=s.textContent??"",c=i.textContent??"";if(l!==c)return}return!1}}}}})};var cv=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var ju={index:-1,draft:""};function dv(t){let{direction:e,history:n,currentValue:o,atStart:s,state:i}=t,l=i.index!==-1;if(n.length===0)return{handled:!1,state:i};if(e==="up"){if(!l&&!s)return{handled:!1,state:i};if(!l){let c=n.length-1;return{handled:!0,value:n[c],state:{index:c,draft:o}}}if(i.index>0){let c=i.index-1;return{handled:!0,value:n[c],state:{index:c,draft:i.draft}}}return{handled:!0,state:i}}if(!l)return{handled:!1,state:i};if(i.index<n.length-1){let c=i.index+1;return{handled:!0,value:n[c],state:{index:c,draft:i.draft}}}return{handled:!0,value:i.draft,state:{index:-1,draft:i.draft}}}function pv(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function uv(){return new Map}function gv(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function fv(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function mv(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:oI,load:EM}=Tt({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var hv=EM;function Vu(t,e=an){let n=t.style.position,o=t.style.zIndex,s=t.style.isolation,i=getComputedStyle(t),l=i.position==="static"||i.position==="";return l&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{l&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=s}}var Ra=0,Pr=null;function Ku(t=document){if(Ra++,Ra===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Pr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,Ra=Math.max(0,Ra-1),Ra===0&&Pr)){let n=t.body,o=t.defaultView??window;n.style.overflow=Pr.originalOverflow,n.style.position=Pr.originalPosition,n.style.top=Pr.originalTop,n.style.width=Pr.originalWidth,o.scrollTo(0,Pr.scrollY),Pr=null}}}var Wa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=t=>(t?.launcher?.mountMode??"floating")==="docked",Ba=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Jn=t=>{let e=t?.launcher?.dock;return{side:e?.side??Wa.side,width:e?.width??Wa.width,animate:e?.animate??Wa.animate,reveal:e?.reveal??Wa.reveal,maxHeight:e?.maxHeight??Wa.maxHeight}};import{ArrowRight as TM}from"lucide";var Gu=t=>t==="followUp"?"follow-up":t,Qu=(t,e=0)=>{if(typeof t=="string"){let s=t.trim();return s?{id:s,label:s,prompt:s,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},kM=t=>{switch(t){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'}},yv=new WeakSet,PM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,IM=t=>{PM()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Xu=t=>{var N,x,R;let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:d,chipsConfig:u,session:g,getTextarea:m,eventTarget:v,submitPrompt:h}=t,T=o==="followUp",M=e.behavior,E=()=>{if(g.isStreaming())return;let w={suggestion:{...e},surface:o,source:s,behavior:M},O=v.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:w,bubbles:!0,composed:!0,cancelable:!0}));if(T&&v.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!O)return;for(let ie of d)if(ie.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let K=m();if(M==="fill"){K.value=e.prompt,K.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),K.focus();return}if(h){h(e.prompt);return}K.value="",g.sendMessage(e.prompt)},I=()=>{let w=k("button",`persona-suggestion persona-suggestion--${i}`);if(w.type="button",w.disabled=l,w.dataset.suggestionId=e.id,w.dataset.emphasis=e.emphasis,w.dataset.behavior=M,i==="chip"&&(u?.fontFamily&&(w.style.fontFamily=kM(u.fontFamily)),u?.fontWeight&&(w.style.fontWeight=u.fontWeight),u?.paddingX&&(w.style.paddingLeft=u.paddingX,w.style.paddingRight=u.paddingX),u?.paddingY&&(w.style.paddingTop=u.paddingY,w.style.paddingBottom=u.paddingY)),e.icon){let K=ge(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);K&&(K.classList.add("persona-suggestion__icon"),e.iconColor&&(K.style.color=e.iconColor),w.appendChild(K))}let O=k("span","persona-suggestion__copy");if(O.appendChild(G("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&O.appendChild(G("span",{className:"persona-suggestion__description",text:e.description})),w.appendChild(O),i!=="chip"){let K=en(TM,16,"currentColor",1.8);K&&(K.classList.add("persona-suggestion__arrow"),w.appendChild(K))}return w.addEventListener("click",E),w},P=null;for(let w of d)if(w.renderSuggestion&&(P=w.renderSuggestion({suggestion:{...e},index:n,surface:o,source:s,variant:i,streaming:l,config:c,defaultRenderer:I,select:E}),P))break;return P??(P=I()),(N=P.dataset).suggestionId||(N.suggestionId=e.id),(x=P.dataset).behavior||(x.behavior=M),(R=P.dataset).emphasis||(R.emphasis=e.emphasis),P instanceof HTMLButtonElement||P.setAttribute("aria-disabled",l?"true":"false"),P},Da=t=>{let e=[],n=[],o=null,s=null,i=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},l=()=>{if(s=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){i();return}let g=Math.max(0,t.scrollWidth-t.clientWidth);if(g<=1){i();return}let m=getComputedStyle(t).direction==="rtl",v=Math.min(g,Math.max(0,Math.abs(t.scrollLeft))),h=4,T=v<=h,M=v>=g-h,E=m?!M:!T,I=m?!T:!M;t.toggleAttribute("data-scroll-left",E),t.toggleAttribute("data-scroll-right",I)},c=()=>{if(s!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&l();return}s=requestAnimationFrame(l)};t.addEventListener("scroll",c,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(c):null;return d?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",c),d?.disconnect(),s!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(s),s=null},render:(g,m,v,h,T,M)=>{t.replaceChildren(),e.length=0,n.length=0;let E=M?.source??"config",I=M?.surface??(E==="config"?"starter":"followUp"),P=I==="followUp",N=M?.variant??"chip",x=M?.behavior??"send",R=M?.overflow??"wrap",w=M?.config??{},O=M?.plugins??[],K=typeof M?.maxItems=="number"?Math.max(0,Math.floor(M.maxItems)):void 0,ie=P?"followUps":"starters";!yv.has(w)&&w.debug===!0&&N!=="chip"&&w.suggestions?.[ie]?.overflow!==void 0&&(yv.add(w),console.info(`[persona] suggestions.${ie}.overflow applies to the "chip" variant only; the "${N}" variant manages its own stacking.`));let Z=$=>$.map(Qu).filter(ae=>ae!==null).map(ae=>({...ae,behavior:ae.behavior??x})),S=Z(g??[]);O.forEach($=>{$.transformSuggestions&&(S=Z($.transformSuggestions({suggestions:S.map(ae=>({...ae})),surface:I,source:E,config:w})))});let B=K===void 0?S:S.slice(0,K);if(!B.length){t.hidden=!0,o=null,i();return}if(!P&&(h??m.getMessages()).some(ae=>ae.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=Gu(I),t.dataset.variant=N,t.dataset.overflow=R;let W=document.createDocumentFragment(),H=m.isStreaming();B.forEach(($,ae)=>{let re=Xu({item:$,index:ae,surface:I,source:E,variant:N,streaming:H,config:w,plugins:O,chipsConfig:T,session:m,getTextarea:()=>v,eventTarget:t,submitPrompt:M?.submitPrompt});W.appendChild(re),n.push(re),[...re instanceof HTMLButtonElement?[re]:[],...Array.from(re.querySelectorAll("button"))].forEach(Ee=>{e.includes(Ee)||(Ee.disabled=H,e.push(Ee))})}),t.appendChild(W),l(),c();let J=JSON.stringify({normalized:B,surface:I,variant:N,source:E});J!==o&&(o=J,IM(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:B.map($=>({...$})),surface:I,source:E,variant:N},bubbles:!0,composed:!0})),P&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:B.map($=>$.prompt)},bubbles:!0,composed:!0})))}}};var Fn={"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 LM="persona-header-control",HM="persona-header-control--glyph",RM="persona-header-control--sparse",WM=20,BM={x:[1.4,1.05]},bv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",DM="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Jc=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=BM[e]??[1,1.5],c=!o;t.classList.toggle(HM,c),t.classList.toggle(RM,c&&i!==1);let d=parseFloat(o??"")||WM,u=ge(e,`${Math.round(d*i)}px`,"currentColor",l);u?(u.style.display="block",c||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((l/1.5).toFixed(4))})`),t.replaceChildren(u)):s&&(t.textContent=s)},gs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=bv,size:c,iconSize:d,color:u,backgroundColor:g,borderWidth:m,borderColor:v,borderRadius:h,paddingX:T,paddingY:M,hidden:E,extraClassName:I,attrs:P}=t,N=k("div",l),x=!!(m||v),R=G("button",{className:_n(LM,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"persona-bg-transparent hover:persona-bg-gray-100",!x&&"persona-border-none",!h&&"persona-rounded-full",I),attrs:{type:"button","aria-label":e,...P},style:{width:c,height:c,minWidth:c,minHeight:c,display:E?"none":void 0,color:u||gn.actionIconColor,backgroundColor:g,border:x?`${m||"0px"} solid ${v||"transparent"}`:void 0,borderRadius:h,paddingLeft:T,paddingRight:T,paddingTop:M,paddingBottom:M}});return s?Jc(R,s,{iconSize:d,iconText:i}):i&&(R.textContent=i),N.appendChild(R),Qt({anchor:R,trigger:N,text:()=>R.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:R,wrapper:N}},pi=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=bv,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",d=l.closeButtonShowTooltip??!0,{button:u,wrapper:g}=gs({ariaLabel:c,tooltip:d,iconName:l.closeButtonIconName??"x",iconText:l.closeButtonIconText??"\xD7",wrapperClassName:o,size:s??l.closeButtonSize,iconSize:i,color:l.closeButtonColor,backgroundColor:l.closeButtonBackgroundColor,borderWidth:l.closeButtonBorderWidth,borderColor:l.closeButtonBorderColor,borderRadius:l.closeButtonBorderRadius,paddingX:l.closeButtonPaddingX,paddingY:l.closeButtonPaddingY,hidden:!n});return{button:u,wrapper:g}},ui=(t,e={})=>{let{wrapperClassName:n=DM,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",d=l.showTooltip??!0,{button:u,wrapper:g}=gs({ariaLabel:c,tooltip:d,iconName:l.iconName??"refresh-cw",wrapperClassName:n,size:o??l.size,iconSize:s,color:l.iconColor,backgroundColor:l.backgroundColor,borderWidth:l.borderWidth,borderColor:l.borderColor,borderRadius:l.borderRadius,paddingX:l.paddingX,paddingY:l.paddingY});return{button:u,wrapper:g}};var gn={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)"},Yu={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)"},OM={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)"},fs=t=>{let{config:e,showClose:n=!0}=t,o=G("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:gn.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)))"}}),s=e?.launcher??{},i=s.headerIconSize??"48px",l=s.closeButtonPlacement??"inline",c=s.headerIconHidden??!1,d=s.headerIconName,u=G("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:i,width:i,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!c)if(d){let R=parseFloat(i)||24,w=ge(d,R*.6,"currentColor",1);w?u.replaceChildren(w):u.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let R=k("img");R.src=e.launcher.iconUrl,R.alt="",R.className="persona-rounded-xl persona-object-cover",R.style.height=i,R.style.width=i,u.replaceChildren(R)}else u.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let g=k("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=G("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:gn.titleColor,...Yu}}),v=G("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:gn.subtitleColor,...OM}});g.append(m,v),c?o.append(g):o.append(u,g);let h=s.clearChat??{},T=h.enabled??!0,M=h.placement??"inline",E=null,I=null;if(T){let w=ui(e,{wrapperClassName:M==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=w.button,I=w.wrapper,M==="top-right"&&(I.style.right="48px"),M==="inline"&&o.appendChild(I)}let P=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":T&&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:N,wrapper:x}=pi(e,{showClose:n,wrapperClassName:P});return l!=="top-right"&&o.appendChild(x),{header:o,iconHolder:u,headerTitle:m,headerSubtitle:v,closeButton:N,closeButtonWrapper:x,clearChatButton:E,clearChatButtonWrapper:I}},Oa=(t,e,n)=>{let o=n?.launcher??{},s=o.closeButtonPlacement??"inline",i=o.clearChat?.placement??"inline";t.appendChild(e.header),s==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&i==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};var _M=t=>{let e=fs({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return e};function NM(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=gs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Xc(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(s.setAttribute("data-persona-header-action",o.id),o.shortcut){let l=Ha(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=ey({items:o.menuItems,onSelect:c=>n?.(c),anchor:i,position:"bottom-right"});i.appendChild(l.element),s.addEventListener("click",c=>{c.stopPropagation(),l.toggle()})}else s.addEventListener("click",()=>n?.(o.id));t.appendChild(i)}}var FM=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:i}=t,l=e?.launcher??{},c=k("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");c.setAttribute("data-persona-theme-zone","header"),c.style.minHeight=gn.minHeight,c.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",c.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",c.style.boxShadow="var(--persona-header-shadow, none)",c.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s?.titleMenu,u,g;if(d){let x=ny({label:l.title??"Chat Assistant",menuItems:d.menuItems,onSelect:R=>{let w=K=>{K===!1&&x.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:R}}))},O=d.onSelect(R);O instanceof Promise?O.then(w,()=>{}):w(O)},hover:d.hover,className:""});u=x.element,u.style.color=gn.titleColor,g=u.querySelector(".persona-combo-btn-label")??u}else{if(u=k("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=k("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=gn.titleColor,Object.assign(g.style,Yu),g.textContent=l.title??"Chat Assistant",u.appendChild(g),s?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let R=s.onTitleClick;u.addEventListener("click",w=>{w.target.closest("button")||R()}),u.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),R())})}let x=s?.titleRowHover;x&&(u.style.borderRadius=x.borderRadius??"10px",u.style.padding=x.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=x.background??"",u.style.borderColor=x.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}c.appendChild(u);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:v,wrapper:h}=pi(e,{showClose:n,wrapperClassName:m});o&&v.addEventListener("click",o);let T=k("div","persona-flex persona-items-center persona-gap-1");d||NM(T,s?.trailingActions,s?.onAction??i);let M=l.clearChat??{},E=null,I=null;if(M.enabled??!0){let x=M.placement??"inline",R=ui(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});E=R.button,I=R.wrapper,x==="top-right"?I.style.right="48px":T.appendChild(I)}T.appendChild(h),c.appendChild(T);let P=k("div");P.style.display="none";let N=k("span");return N.style.display="none",{header:c,iconHolder:P,headerTitle:g,headerSubtitle:N,closeButton:v,closeButtonWrapper:h,clearChatButton:E,clearChatButtonWrapper:I}},vv={default:_M,minimal:FM},UM=t=>vv[t]??vv.default,Zc=(t,e,n)=>{if(e?.render){let l=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),c=k("div");c.style.display="none";let d=k("span"),u=k("span"),g=k("button");g.style.display="none";let m=k("div");return m.style.display="none",{header:l,iconHolder:c,headerTitle:d,headerSubtitle:u,closeButton:g,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=UM(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(i.iconHolder.style.display="none"),e.showTitle===!1&&(i.headerTitle.style.display="none"),e.showSubtitle===!1&&(i.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(i.closeButton.style.display="none"),e.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display="none")),i};var _a=t=>{let{config:e}=t,n=G("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Uc(),s=G("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:i,attachAutoResize:l}=Oc(e);l();let c=_c(e),d=li(e),u=Nc(e),g=Fc(e),m=G("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(m),u&&(u.previewsContainer.style.gap="8px",m.append(u.previewsContainer),s.append(u.input)),s.append(i);let v=G("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=G("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),T=G("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return u&&h.append(u.wrapper),d&&T.append(d.wrapper),T.append(c.wrapper),v.append(h,T),s.append(v),s.addEventListener("click",M=>{M.target!==c.button&&M.target!==c.wrapper&&M.target!==d?.button&&M.target!==d?.wrapper&&M.target!==u?.button&&M.target!==u?.wrapper&&i.focus()}),n.append(o,s,g),{footer:n,suggestions:o,composerForm:s,header:m,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:g,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:v,leftActions:h,rightActions:T,setSendButtonMode:c.setMode}};import{ChevronUp as $M,MessageSquare as qM}from"lucide";var Cv=()=>{let t=G("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=k("span","persona-pill-peek__icon"),n=en(qM,16,"currentColor",1.5);n&&e.appendChild(n);let o=k("span","persona-pill-peek__text"),s=k("span","persona-pill-peek__caret"),i=en($M,16,"currentColor",1.5);return i&&s.appendChild(i),t.append(e,o,s),{root:t,textNode:o}},ed=t=>{let{config:e}=t,n=G("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Uc(),s=Fc(e);s.style.display="none";let{textarea:i,attachAutoResize:l}=Oc(e,{defaultMaxLines:5});l();let c=_c(e),d=li(e),u=Nc(e);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let g=G("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=G("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&m.append(u.wrapper);let v=G("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&v.append(d.wrapper),v.append(c.wrapper),g.addEventListener("click",M=>{M.target!==c.button&&M.target!==c.wrapper&&M.target!==d?.button&&M.target!==d?.wrapper&&M.target!==u?.button&&M.target!==u?.wrapper&&i.focus()}),u&&g.append(u.input),g.append(m,i,v);let h=G("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),u&&h.append(u.previewsContainer),n.append(o,g,s);let T=g;return{footer:n,suggestions:o,composerForm:g,header:h,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:s,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:T,leftActions:m,rightActions:v,setSendButtonMode:c.setMode}};var zM=t=>{switch(t){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}},jM=(t,e)=>{if(!t)return null;let n=zM(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},VM=(t,e)=>{let n=k("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},KM=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Zu=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},eg=320,Mv=320,GM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),QM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),XM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),YM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),JM=t=>{if(!t||t.length===0)return null;let e=G("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=G("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=k("span","persona-mention-chip-icon"),i=ge(n.iconName??"at-sign",13,"currentColor",2);i&&s.appendChild(i),o.appendChild(s),o.appendChild(G("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},ZM=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Pa(o.ref,{readonly:!0,render:e}))}return n},wv="\uE000",Sv="\uE001",eE=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=v=>`${wv}${s}:${v}${Sv}`,l=e.map((v,h)=>v.kind==="text"?v.text:i(h)).join(""),c=n(l);if(!e.every((v,h)=>v.kind==="text"||c.includes(i(h)))){t.replaceChildren(ZM(e,o));return}t.innerHTML=c;let u=new RegExp(`${wv}${s}:(\\d+)${Sv}`),g=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),m=[];for(let v=g.nextNode();v;v=g.nextNode())m.push(v);for(let v of m){let h=v;for(let T=u.exec(h.data);T;T=u.exec(h.data)){let M=e[Number(T[1])],E=h.splitText(T.index);E.data=E.data.slice(T[0].length),M?.kind==="mention"&&E.parentNode?.insertBefore(Pa(M.ref,{readonly:!0,render:o}),E),h=E}}},tE=(t,e,n)=>{if(t.length===0)return null;try{let o=k("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let s=0,i=!1,l=()=>{i||(i=!0,o.remove(),n?.())};return t.forEach((c,d)=>{let u=k("img");u.alt=c.alt?.trim()||`Attached image ${d+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${eg}px`,u.style.maxHeight=`${Mv}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 g=!1;s+=1,u.addEventListener("error",()=>{g||(g=!0,s=Math.max(0,s-1),u.remove(),s===0&&l())}),u.addEventListener("load",()=>{g=!0}),KM(c.image)?(u.src=c.image,o.appendChild(u)):(g=!0,s=Math.max(0,s-1),u.remove())}),s===0?(l(),null):o}catch{return n?.(),null}},nE=t=>{if(t.length===0)return null;try{let e=k("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!Zu(o.audio))return;let s=k("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${eg}px`,e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},oE=t=>{if(t.length===0)return null;try{let e=k("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!Zu(o.video))return;let s=k("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${eg}px`,s.style.maxHeight=`${Mv}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},rE=t=>{if(t.length===0)return null;try{let e=k("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!Zu(o.data))return;let s=k("a");s.href=o.data,s.download=o.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Na=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";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="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(s),t},sE=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Na};if(e){let s=e(o);if(s!==null)return s}return Na()},iE=(t,e)=>{let n=k("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let s=k("img");s.src=o,s.alt=e==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},xv=(t,e,n="div")=>{let o=k(n,"persona-text-xs persona-text-persona-muted"),s=new Date(t.createdAt);return e.format?o.textContent=e.format(s):o.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Fa=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.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 n},Av={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"}},aE=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=Av[n??"bubble"]??Av.bubble;o.padding&&(t.style.padding=`var(--persona-message-${s}-padding, ${i.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${s}-font-size, ${i.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${s}-line-height, ${i.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${s}-font-family, inherit)`)},td="custom:",lE=t=>`${td}${t}`,Ev=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),cE=(t,e,n,o)=>{let s=e.showCopy??!0,i=e.showUpvote??!0,l=e.showDownvote??!0,c=e.showReadAloud??!1,d=(e.showRegenerate??!1)&&o?.canRegenerate===!0,u=(e.showEdit??!1)&&o?.canEdit===!0,g=(e.showQuote??!1)&&o?.canQuote!==!1,m=Ev(e,t.role);if(!s&&!i&&!l&&!c&&!d&&!u&&!g&&m.length===0){let N=k("div");return N.style.display="none",N.id=`actions-${t.id}`,N.setAttribute("data-actions-for",t.id),N}let v=e.visibility??"hover",h=e.align??"right",T=e.layout??"pill-inside",M={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],E={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[T],I=k("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${M} ${E} ${v==="hover"?"persona-message-actions-hover":""}`);I.id=`actions-${t.id}`,I.setAttribute("data-actions-for",t.id);let P=(N,x,R)=>{let w=ty({icon:N,label:x,size:14,className:"persona-message-action-btn",chromeless:!0});return w.setAttribute("data-action",R),w};s&&I.appendChild(P("copy","Copy message","copy")),c&&I.appendChild(P("volume-2","Read aloud","read-aloud")),i&&I.appendChild(P("thumbs-up","Upvote","upvote")),l&&I.appendChild(P("thumbs-down","Downvote","downvote")),d&&I.appendChild(P("refresh-cw","Regenerate response","regenerate")),u&&I.appendChild(P("pencil","Edit message","edit")),g&&I.appendChild(P("quote","Quote message","quote"));for(let N of m)I.appendChild(P(N.iconName??"ellipsis",N.label,lE(N.id)));return I},tg=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",d=l.avatar,u=l.timestamp,g=d?.show??!1,m=u?.show??!1,v=d?.position??"left",h=u?.position??"below",T=Fa(t.role,c),M=k("div",T.join(" "));M.id=`bubble-${t.id}`,M.setAttribute("data-message-id",t.id),M.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let E=i?.widgetConfig?.theme?.components?.message;aE(M,t.role,c,t.role==="user"?E?.user:E?.assistant),c==="flat"?(M.style.backgroundColor="transparent",M.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(M.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",M.style.color="var(--persona-message-user-text, white)"):t.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 I=GM(t),P=t.content?.trim()??"",x=I.length>0&&P===ii,R=mc(i?.widgetConfig?.features?.streamAnimation),w=i?.widgetConfig?.features?.streamAnimation?.plugins,O=t.role==="assistant"&&R.type!=="none"?ua(R.type,w):null,K=t.role==="assistant"&&O?.isAnimating?.(t)===!0,ie=t.role==="assistant"&&O!==null&&(!!t.streaming||K);ie&&O?.bubbleClass&&M.classList.add(O.bubbleClass);let Z=document.createElement("div");Z.classList.add("persona-message-content"),t.streaming&&Z.classList.add("persona-content-streaming"),ie&&O&&(O.containerClass&&Z.classList.add(O.containerClass),Z.style.setProperty("--persona-stream-step",`${R.speed}ms`),Z.style.setProperty("--persona-stream-duration",`${R.duration}ms`));let S=ie?hc(t.content??"",R.buffer,O,t,!!t.streaming):t.content??"",B=()=>{let ye=e({text:S,message:t,streaming:!!t.streaming,raw:t.rawContent});return ie&&O?.wrap==="char"?ga(ye,"char",t.id,{skipTags:O.skipTags}):ie&&O?.wrap==="word"?ga(ye,"word",t.id,{skipTags:O.skipTags}):ye},W=null;if(x?(W=document.createElement("div"),W.innerHTML=B(),W.style.display="none",Z.appendChild(W)):t.contentSegments?.length?eE(Z,t.contentSegments,ye=>e({text:ye,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):Z.innerHTML=B(),ie&&O?.useCaret&&!x&&P){let ye=yc(),F=Z.querySelectorAll(".persona-stream-char, .persona-stream-word"),Te=F[F.length-1];if(Te?.parentNode)Te.parentNode.insertBefore(ye,Te.nextSibling);else{let Ue=Z.lastElementChild;Ue?Ue.appendChild(ye):Z.appendChild(ye)}}if(m&&h==="inline"&&t.createdAt){let ye=xv(t,u,"span");ye.classList.add("persona-timestamp-inline");let F=Z.lastElementChild;F?F.appendChild(ye):Z.appendChild(ye)}if(I.length>0){let ye=tE(I,!x&&!!P,()=>{x&&W&&(W.style.display="")});ye?M.appendChild(ye):x&&W&&(W.style.display="")}let H=QM(t);if(H.length>0){let ye=nE(H);ye&&M.appendChild(ye)}let J=XM(t);if(J.length>0){let ye=oE(J);ye&&M.appendChild(ye)}let $=YM(t);if($.length>0){let ye=rE($);ye&&M.appendChild(ye)}let ae=t.contentSegments?.length?null:JM(t.contextMentions);if(ae&&M.appendChild(ae),M.appendChild(Z),m&&h==="below"&&t.createdAt){let ye=xv(t,u);ye.classList.add("persona-mt-1"),M.appendChild(ye)}let re=t.role==="assistant"?jM(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ye=!!(S&&S.trim()),F=R.placeholder==="skeleton",Te=F&&R.buffer==="line"&&ye;if(ye)Te&&M.appendChild(fa());else if(F)M.appendChild(fa());else{let Ue=sE("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);Ue&&M.appendChild(Ue)}}re&&t.stopReason&&!t.streaming&&(P||(Z.style.display="none"),M.appendChild(VM(t.stopReason,re)));let ue=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,Ee=i?.actionEligibility,he=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ee?.canEdit===!0||o?.showQuote===!0&&Ee?.canQuote===!0||Ev(o,"user").length>0);if((ue||he)&&o){let ye=cE(t,he?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,Ee);M.appendChild(ye)}if(!g||t.role==="system")return M;let ce=k("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),at=iE(d,t.role);return v==="right"||v==="left"&&t.role==="user"?ce.append(M,at):ce.append(at,M),ce};var dE=40,pE=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=ge(e.name,dE);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(G("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(G("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},Tv=(t,e,n={})=>{let o=G("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let s=k("p","persona-welcome-kicker");s.hidden=!0;let i=k("h2","persona-welcome-title"),l=k("p","persona-welcome-subtitle"),c=G("div",{className:"persona-welcome-head-text"},s,i),d=G("div",{className:"persona-welcome-title-row"},o,c);return{host:G("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:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},d,l,e),iconHolder:o,kicker:s,title:i,subtitle:l,starterSuggestions:e}},gi=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},od=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",pE(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},uE="data-persona-welcome-plugin",kv="data-persona-welcome-overlay",nd="persona-welcome-overlay-active",ng=new WeakMap,og=(t,e,n)=>{n.setAttribute(uE,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(kv,""),t.classList.contains(nd)||(ng.set(t,t.scrollTop),t.classList.add(nd),t.scrollTop=0)},rg=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(kv),t.classList.contains(nd)&&(t.classList.remove(nd),t.scrollTop=ng.get(t)??t.scrollTop,ng.delete(t))},Pv=()=>{let t=G("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},rd=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",s=G("div",{className:Fa("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="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))"}});t.appendChild(G("div",{className:"persona-flex"},s)),t.hidden=!1},Iv=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Lv=(t,e)=>{if(Iv()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,s=0,i=0,l=0;if(o){let T=getComputedStyle(o);s=parseFloat(T.rowGap)||0;let M=t.previousElementSibling,E=t.nextElementSibling,P=o.getBoundingClientRect().top+(parseFloat(T.borderTopWidth)||0)+(parseFloat(T.paddingTop)||0)-o.scrollTop;i=Math.max(0,M?n.top-M.getBoundingClientRect().bottom-s:n.top-P),l=Math.max(0,E?E.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let d=getComputedStyle(t),u=parseFloat(d.paddingTop)||0,g=parseFloat(d.paddingBottom)||0,m=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${g}px`,marginTop:`${i}px`,marginBottom:`${l}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-s}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),v=!1,h=()=>{v||(v=!0,t.style.overflow=c,e(m))};return m.finished.then(h).catch(h),m},Hv=(t,e,n)=>{if(e<=1||Iv()||typeof t.animate!="function"||!t.isConnected)return null;let o=n==="drop"?-e:e;return t.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var gE="Hello \u{1F44B}",fE="I can answer questions and help you get things done here.",Rv=new WeakSet,fn=(t,e)=>!!t&&t[e]!==void 0,mE=(t,e)=>{!t||t.debug!==!0||!e.length||Rv.has(t)||(Rv.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Zo=t=>{let e=t?.welcome,n=t?.copy,o=fn(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",s=o==="hero"?"on-first-message":fn(e,"dismiss")?e.dismiss:"never",i=[];fn(e,"title")&&fn(n,"welcomeTitle")&&i.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),fn(e,"subtitle")&&fn(n,"welcomeSubtitle")&&i.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),fn(e,"variant")&&fn(n,"showWelcomeCard")&&i.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&fn(e,"message")&&i.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&fn(e,"dismiss")&&e.dismiss!=="on-first-message"&&i.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let l=e?.anchor==="center"?"center":"bottom",c=La(e?.anchorComposerTop)!==null;return fn(e,"anchorComposerTop")&&!c&&i.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),l!=="center"&&(fn(e,"anchorComposerTop")||fn(e,"composerGap"))&&i.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),mE(t,i),{title:fn(e,"title")?e.title:n?.welcomeTitle??gE,kicker:e?.kicker??"",subtitle:fn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??fE,icon:e?.icon,align:e?.align==="start"||e?.align==="center"?e.align:void 0,iconPlacement:e?.icon&&typeof e.icon!="function"&&e.icon.placement==="inline"?"inline":"above",variant:o,dismiss:s,message:o==="hero"?void 0:e?.message,anchor:l,anchorComposerTop:c?e.anchorComposerTop:"44%",composerGap:e?.composerGap?.trim()||Kc}},Wv=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",fi=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var Bv="16px",ig="10px",ag="14px",Dv=t=>{let e=t?.launcher?.enabled??!0,n=Lt(t);if(Ba(t)){let g=t?.launcher?.composerBar??{},m=k("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=g.expandedSize??"anchored",m.style.zIndex=String(t?.launcher?.zIndex??an);let v=k("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");v.style.width="100%",m.appendChild(v);let h=k("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=g.expandedSize??"anchored",h.style.zIndex=String(t?.launcher?.zIndex??an),{wrapper:m,panel:v,pillRoot:h}}if(n){let g=k("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=k("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return g.appendChild(m),{wrapper:g,panel:m}}if(!e){let g=k("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=k("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),v=t?.launcher?.width??"100%";return g.style.width=v,m.style.width="100%",g.appendChild(m),{wrapper:g,panel:m}}let s=t?.launcher??{},i=s.position&&Fn[s.position]?Fn[s.position]:Fn["bottom-right"],l=k("div",`persona-widget-wrapper persona-fixed ${i} persona-transition`);l.style.zIndex=String(t?.launcher?.zIndex??an);let c=k("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=t?.launcher?.width??t?.launcherWidth??Jo;return c.style.width=u,c.style.maxWidth=u,l.appendChild(c),{wrapper:l,panel:c}},lg=t=>{let e=G("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Gu(t)}});return e.hidden=!0,e},Ov=(t,e)=>{let n=lg("starter"),o=Tv(t,n,{flatShadow:Lt(t)}),s=Zo(t);od(o,s),gi(e,o.host,fi(s,t?.initialMessages));let i=Pv();return rd(i,s.message,t),{welcome:o,greetingHost:i}},hE=(t,e)=>{let n=k("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:s}=pi(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:Bv,iconSize:ig});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let i=t?.launcher?.clearChat?.enabled??!0,l=null,c=null;if(i){let O=ui(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Bv,iconSize:ag});l=O.button,c=O.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let d=G("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=G("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:g,greetingHost:m}=Ov(t,u),{host:v,title:h,subtitle:T}=g,M=g.starterSuggestions,E=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),I=lg("followUp"),P=kr(t,!0);P&&(E.style.maxWidth=P,E.style.marginLeft="auto",E.style.marginRight="auto",E.style.width="100%"),u.append(v,m,E,I);let N=G("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"}}),x=ed({config:t}),{root:R,textNode:w}=Cv();return n.append(d,s,u,N),c&&n.appendChild(c),{container:n,body:u,messagesWrapper:E,starterSuggestions:M,transcriptSuggestions:I,composerOverlay:N,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,welcomeHost:v,welcomeIconHolder:g.iconHolder,greetingHost:m,introKicker:g.kicker,introTitle:h,introSubtitle:T,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:k("span"),headerTitle:k("span"),headerSubtitle:k("span"),header:d,footer:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions,setSendButtonMode:x.setSendButtonMode,peekBanner:R,peekTextNode:w}},_v=(t,e=!0)=>{if(Ba(t))return hE(t,e);let n=G("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,s=t?.layout?.showHeader!==!1,i=o?Zc(t,o,{showClose:e}):fs({config:t,showClose:e}),l=G("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"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:d}=Ov(t,l),{host:u,title:g,subtitle:m}=c,v=c.starterSuggestions,h=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),T=lg("followUp"),M=kr(t,!1);M&&(h.style.maxWidth=M,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),l.append(u,d,h,T);let E=_a({config:t}),I=t?.layout?.showFooter!==!1;s?Oa(n,i,t):(i.header.style.display="none",Oa(n,i,t)),n.append(l);let P=G("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 I||(E.footer.style.display="none"),n.append(E.footer),n.append(P),{container:n,body:l,messagesWrapper:h,starterSuggestions:v,transcriptSuggestions:T,composerOverlay:P,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,welcomeHost:u,welcomeIconHolder:c.iconHolder,greetingHost:d,introKicker:c.kicker,introTitle:g,introSubtitle:m,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,header:i.header,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode}};var cg=(t,e)=>{let n=k("button");n.type="button",n.innerHTML=`
|
|
20
20
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
21
21
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
22
22
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -24,14 +24,14 @@ _Details: ${n.message}_`:o}var xu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
24
24
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
25
25
|
</span>
|
|
26
26
|
<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>
|
|
27
|
-
`,n.addEventListener("click",e);let o=i=>{let l=i.launcher??{},c=Lt(i),d=n.querySelector("[data-role='launcher-title']");if(d){let z=l.title??"Chat Assistant";d.textContent=z,d.setAttribute("title",z)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let z=l.subtitle??"Here to help you get answers fast";u.textContent=z,u.setAttribute("title",z)}let g=n.querySelector(".persona-flex-col");g&&(l.textHidden||c?g.style.display="none":g.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(l.agentIconHidden)m.style.display="none";else{let z=l.agentIconSize??"40px";if(m.style.height=z,m.style.width=z,l.agentIconBackgroundColor?(m.style.backgroundColor=l.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",l.agentIconName){let A=parseFloat(z)||24,H=ge(l.agentIconName,A*.6,"var(--persona-text-inverse, #ffffff)",1.5);H?(m.appendChild(H),m.style.display=""):(m.textContent=l.agentIconText??"\u{1F4AC}",m.style.display="")}else l.iconUrl?m.style.display="none":(m.textContent=l.agentIconText??"\u{1F4AC}",m.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let z=l.agentIconSize??"40px";b.style.height=z,b.style.width=z,l.iconUrl&&!l.agentIconName&&!l.agentIconHidden?(b.src=l.iconUrl,b.style.display="block"):b.style.display="none"}let h=n.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let z=l.callToActionIconSize??"32px";h.style.height=z,h.style.width=z,l.callToActionIconBackgroundColor?(h.style.backgroundColor=l.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),l.callToActionIconColor?(h.style.color=l.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let A=0;if(l.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=l.callToActionIconPadding,A=(parseFloat(l.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),l.callToActionIconHidden)h.style.display="none";else if(h.style.display=c?"none":"",h.innerHTML="",l.callToActionIconName){let H=parseFloat(z)||24,w=Math.max(H-A,8),D=ge(l.callToActionIconName,w,"currentColor",1.5);D?h.appendChild(D):h.textContent=l.callToActionIconText??"\u2197"}else h.textContent=l.callToActionIconText??"\u2197"}let x=l.position&&Fn[l.position]?Fn[l.position]:Fn["bottom-right"],T="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";n.className=c?M:`${T} ${x}`,c||(n.style.zIndex=String(l.zIndex??an));let O="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=l.border??O,n.style.boxShadow=l.shadow!==void 0?l.shadow.trim()===""?"none":l.shadow:I,c?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=l.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:s}},yE="teaser-dismissed",Fv=new Set,Nv=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${yE}`},bE=(t,e)=>{if(Fv.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},vE=(t,e)=>{if(Fv.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},CE=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,wE=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||Lt(t??{})?null:e},Uv=(t,e)=>{let n=k("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},s=null,i=null,l=null,c=null,d=null,u=!1,g=!1,m=!1,b=!1,h=()=>(s?.frequency??"once")==="once"&&o.persistState!==!1,x=()=>{d!==null&&(clearTimeout(d),d=null)},T=()=>{!i||!u||(u=!1,i.hidden=!0)},M=J=>{x(),m=!0,T(),vE(Nv(o),J&&h())},O=J=>{!s||m||M(J==="user"&&u)},I=()=>{d=null,!(!i||m||b)&&(g=!0,u=!0,i.hidden=!1,!(CE()||typeof i.animate!="function")&&i.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},z=()=>{!s||!i||m||g||b||bE(Nv(o),h())||(x(),d=setTimeout(I,Math.max(0,s.delayMs??0)))},A=()=>{M(h()),e()},H=J=>{J.stopPropagation(),M(h())},D=cg(t,()=>{O("user"),e()}),K=()=>{x(),c?.removeEventListener("click",A),l?.removeEventListener("click",H),i?.remove(),i=null,c=null,l=null,u=!1},ie=()=>{c=G("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),c.addEventListener("click",A),l=G("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),l.addEventListener("click",H),i=G("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},c,l),n.insertBefore(i,D.element)},Z=()=>{let J=o.launcher?.position??"bottom-right",U=Fn[J]??Fn["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",D.element.style.position="";return}n.className=_n("persona-launcher-surface",U),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??an),D.element.style.position="static"},S=J=>{let U=wE(J);if(s=U,!U){K();return}i||ie(),c.textContent=U.text,l.hidden=U.dismissible===!1,l.setAttribute("aria-label",U.dismissLabel??"Dismiss message"),z()},W=J=>{o=J,D.update(J),S(J),Z()},R=(J,U="user")=>{b=J,J&&O(U)},L=()=>{K(),D.destroy(),n.remove()};return n.appendChild(D.element),t&&(S(t),Z()),{element:n,launcher:D,get teaser(){return i?{element:i,show:I,dismiss:M}:null},setPanelOpen:R,update:W,destroy:L}};var $v=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:s}=Dv(t),i=_v(t,e),l={wrapper:n,panel:o,pillRoot:s},c={container:i.container,body:i.body,messagesWrapper:i.messagesWrapper,starterSuggestions:i.starterSuggestions,transcriptSuggestions:i.transcriptSuggestions,composerOverlay:i.composerOverlay,welcomeHost:i.welcomeHost,welcomeIconHolder:i.welcomeIconHolder,greetingHost:i.greetingHost,introTitle:i.introTitle,introSubtitle:i.introSubtitle},d={element:i.header,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper},u={footer:i.footer,form:i.composerForm,textarea:i.textarea,sendButton:i.sendButton,sendButtonWrapper:i.sendButtonWrapper,micButton:i.micButton,micButtonWrapper:i.micButtonWrapper,statusText:i.statusText,suggestions:i.suggestions,attachmentButton:i.attachmentButton,attachmentButtonWrapper:i.attachmentButtonWrapper,attachmentInput:i.attachmentInput,attachmentPreviewsContainer:i.attachmentPreviewsContainer,actionsRow:i.actionsRow,leftActions:i.leftActions,rightActions:i.rightActions,setSendButtonMode:i.setSendButtonMode,peekBanner:i.peekBanner,peekTextNode:i.peekTextNode};return{shell:l,panelElements:i,transcript:c,header:d,composer:u,replaceHeader:b=>(d.element.replaceWith(b.header),d.element=b.header,d.iconHolder=b.iconHolder,d.headerTitle=b.headerTitle,d.headerSubtitle=b.headerSubtitle,d.closeButton=b.closeButton,d.closeButtonWrapper=b.closeButtonWrapper,d.clearChatButton=b.clearChatButton,d.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{u.footer.replaceWith(b),u.footer=b}}},dg=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>cg(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let s=Uv(t,n);return{instance:s,element:s.element}};var SE=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},xE=(t,e,n)=>`${SE(t)}plugin:${e}:${n}`,qv=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return s=>{let i=l=>xE(t(),s,l);return{get:l=>{let c=i(l),d=o();if(d)try{return d.getItem(c)}catch{n=!0}return e.get(c)??null},set:(l,c)=>{let d=i(l),u=o();if(u)try{u.setItem(d,c);return}catch{n=!0}e.set(d,c)},remove:l=>{let c=i(l);e.delete(c);let d=o();if(d)try{d.removeItem(c)}catch{n=!0}}}}};import{ChevronDown as AE,ChevronUp as ME}from"lucide";var EE=["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"],TE="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",kE="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",PE=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),sd=(t,e)=>{let n=k("div",["persona-message-bubble",t,...EE].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},id=t=>{let e=k("button",t.expandable?TE:kE);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},pg=(t,e,n)=>{t.innerHTML="";let o=en(e?ME:AE,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},ad=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=k("div","persona-flex persona-items-center");pg(o,n.expanded,n.iconColor);let s=k("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return s.append(o),t.append(e,s),o},ld=t=>{let e=k("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();PE(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},cd=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&pg(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},dd=(t,e,n)=>{let o=n.stateSet.has(t),s=e.querySelector('button[data-expand-header="true"]'),i=e.querySelector(".persona-border-t"),l=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");d&&pg(d,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};var mi=new Set,IE=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
|
|
28
|
-
`):""},zv=(t,e)=>{dd(t,e,{stateSet:mi,previewKind:"reasoning",iconColor:"currentColor"})},ug=(t,e)=>{let n=t.reasoning,o=sd("persona-reasoning-bubble",t.id);if(!n)return o;let s=e?.features?.reasoningDisplay??{},i=s.expandable!==!1,l=i&&mi.has(t.id),c=n.status!=="complete",d=IE(t,s.previewMaxLines??3),u=id({expandable:i,expanded:l,bubbleType:"reasoning"}),g=k("div","persona-flex persona-flex-col persona-text-left"),m=k("span","persona-text-xs persona-text-persona-primary"),
|
|
27
|
+
`,n.addEventListener("click",e);let o=i=>{let l=i.launcher??{},c=Lt(i),d=n.querySelector("[data-role='launcher-title']");if(d){let N=l.title??"Chat Assistant";d.textContent=N,d.setAttribute("title",N)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let N=l.subtitle??"Here to help you get answers fast";u.textContent=N,u.setAttribute("title",N)}let g=n.querySelector(".persona-flex-col");g&&(l.textHidden||c?g.style.display="none":g.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(l.agentIconHidden)m.style.display="none";else{let N=l.agentIconSize??"40px";if(m.style.height=N,m.style.width=N,l.agentIconBackgroundColor?(m.style.backgroundColor=l.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",l.agentIconName){let x=parseFloat(N)||24,R=ge(l.agentIconName,x*.6,"var(--persona-text-inverse, #ffffff)",1.5);R?(m.appendChild(R),m.style.display=""):(m.textContent=l.agentIconText??"\u{1F4AC}",m.style.display="")}else l.iconUrl?m.style.display="none":(m.textContent=l.agentIconText??"\u{1F4AC}",m.style.display="")}let v=n.querySelector("[data-role='launcher-image']");if(v){let N=l.agentIconSize??"40px";v.style.height=N,v.style.width=N,l.iconUrl&&!l.agentIconName&&!l.agentIconHidden?(v.src=l.iconUrl,v.style.display="block"):v.style.display="none"}let h=n.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let N=l.callToActionIconSize??"32px";h.style.height=N,h.style.width=N,l.callToActionIconBackgroundColor?(h.style.backgroundColor=l.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),l.callToActionIconColor?(h.style.color=l.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let x=0;if(l.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=l.callToActionIconPadding,x=(parseFloat(l.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),l.callToActionIconHidden)h.style.display="none";else if(h.style.display=c?"none":"",h.innerHTML="",l.callToActionIconName){let R=parseFloat(N)||24,w=Math.max(R-x,8),O=ge(l.callToActionIconName,w,"currentColor",1.5);O?h.appendChild(O):h.textContent=l.callToActionIconText??"\u2197"}else h.textContent=l.callToActionIconText??"\u2197"}let T=l.position&&Fn[l.position]?Fn[l.position]:Fn["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",E="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";n.className=c?E:`${M} ${T}`,c||(n.style.zIndex=String(l.zIndex??an));let I="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))";n.style.border=l.border??I,n.style.boxShadow=l.shadow!==void 0?l.shadow.trim()===""?"none":l.shadow:P,c?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=l.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:s}},yE="teaser-dismissed",Fv=new Set,Nv=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${yE}`},bE=(t,e)=>{if(Fv.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},vE=(t,e)=>{if(Fv.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},CE=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,wE=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||Lt(t??{})?null:e},Uv=(t,e)=>{let n=k("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},s=null,i=null,l=null,c=null,d=null,u=!1,g=!1,m=!1,v=!1,h=()=>(s?.frequency??"once")==="once"&&o.persistState!==!1,T=()=>{d!==null&&(clearTimeout(d),d=null)},M=()=>{!i||!u||(u=!1,i.hidden=!0)},E=J=>{T(),m=!0,M(),vE(Nv(o),J&&h())},I=J=>{!s||m||E(J==="user"&&u)},P=()=>{d=null,!(!i||m||v)&&(g=!0,u=!0,i.hidden=!1,!(CE()||typeof i.animate!="function")&&i.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},N=()=>{!s||!i||m||g||v||bE(Nv(o),h())||(T(),d=setTimeout(P,Math.max(0,s.delayMs??0)))},x=()=>{E(h()),e()},R=J=>{J.stopPropagation(),E(h())},O=cg(t,()=>{I("user"),e()}),K=()=>{T(),c?.removeEventListener("click",x),l?.removeEventListener("click",R),i?.remove(),i=null,c=null,l=null,u=!1},ie=()=>{c=G("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),c.addEventListener("click",x),l=G("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),l.addEventListener("click",R),i=G("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},c,l),n.insertBefore(i,O.element)},Z=()=>{let J=o.launcher?.position??"bottom-right",$=Fn[J]??Fn["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",O.element.style.position="";return}n.className=_n("persona-launcher-surface",$),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??an),O.element.style.position="static"},S=J=>{let $=wE(J);if(s=$,!$){K();return}i||ie(),c.textContent=$.text,l.hidden=$.dismissible===!1,l.setAttribute("aria-label",$.dismissLabel??"Dismiss message"),N()},B=J=>{o=J,O.update(J),S(J),Z()},W=(J,$="user")=>{v=J,J&&I($)},H=()=>{K(),O.destroy(),n.remove()};return n.appendChild(O.element),t&&(S(t),Z()),{element:n,launcher:O,get teaser(){return i?{element:i,show:P,dismiss:E}:null},setPanelOpen:W,update:B,destroy:H}};var $v=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:s}=Dv(t),i=_v(t,e),l={wrapper:n,panel:o,pillRoot:s},c={container:i.container,body:i.body,messagesWrapper:i.messagesWrapper,starterSuggestions:i.starterSuggestions,transcriptSuggestions:i.transcriptSuggestions,composerOverlay:i.composerOverlay,welcomeHost:i.welcomeHost,welcomeIconHolder:i.welcomeIconHolder,greetingHost:i.greetingHost,introTitle:i.introTitle,introSubtitle:i.introSubtitle},d={element:i.header,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper},u={footer:i.footer,form:i.composerForm,textarea:i.textarea,sendButton:i.sendButton,sendButtonWrapper:i.sendButtonWrapper,micButton:i.micButton,micButtonWrapper:i.micButtonWrapper,statusText:i.statusText,suggestions:i.suggestions,attachmentButton:i.attachmentButton,attachmentButtonWrapper:i.attachmentButtonWrapper,attachmentInput:i.attachmentInput,attachmentPreviewsContainer:i.attachmentPreviewsContainer,actionsRow:i.actionsRow,leftActions:i.leftActions,rightActions:i.rightActions,setSendButtonMode:i.setSendButtonMode,peekBanner:i.peekBanner,peekTextNode:i.peekTextNode};return{shell:l,panelElements:i,transcript:c,header:d,composer:u,replaceHeader:v=>(d.element.replaceWith(v.header),d.element=v.header,d.iconHolder=v.iconHolder,d.headerTitle=v.headerTitle,d.headerSubtitle=v.headerSubtitle,d.closeButton=v.closeButton,d.closeButtonWrapper=v.closeButtonWrapper,d.clearChatButton=v.clearChatButton,d.clearChatButtonWrapper=v.clearChatButtonWrapper,v),replaceComposer:v=>{u.footer.replaceWith(v),u.footer=v}}},dg=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>cg(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let s=Uv(t,n);return{instance:s,element:s.element}};var SE=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},xE=(t,e,n)=>`${SE(t)}plugin:${e}:${n}`,qv=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return s=>{let i=l=>xE(t(),s,l);return{get:l=>{let c=i(l),d=o();if(d)try{return d.getItem(c)}catch{n=!0}return e.get(c)??null},set:(l,c)=>{let d=i(l),u=o();if(u)try{u.setItem(d,c);return}catch{n=!0}e.set(d,c)},remove:l=>{let c=i(l);e.delete(c);let d=o();if(d)try{d.removeItem(c)}catch{n=!0}}}}};import{ChevronDown as AE,ChevronUp as ME}from"lucide";var EE=["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"],TE="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",kE="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",PE=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),sd=(t,e)=>{let n=k("div",["persona-message-bubble",t,...EE].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},id=t=>{let e=k("button",t.expandable?TE:kE);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},pg=(t,e,n)=>{t.innerHTML="";let o=en(e?ME:AE,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},ad=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=k("div","persona-flex persona-items-center");pg(o,n.expanded,n.iconColor);let s=k("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return s.append(o),t.append(e,s),o},ld=t=>{let e=k("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();PE(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},cd=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&pg(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},dd=(t,e,n)=>{let o=n.stateSet.has(t),s=e.querySelector('button[data-expand-header="true"]'),i=e.querySelector(".persona-border-t"),l=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");d&&pg(d,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};var mi=new Set,IE=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
|
|
28
|
+
`):""},zv=(t,e)=>{dd(t,e,{stateSet:mi,previewKind:"reasoning",iconColor:"currentColor"})},ug=(t,e)=>{let n=t.reasoning,o=sd("persona-reasoning-bubble",t.id);if(!n)return o;let s=e?.features?.reasoningDisplay??{},i=s.expandable!==!1,l=i&&mi.has(t.id),c=n.status!=="complete",d=IE(t,s.previewMaxLines??3),u=id({expandable:i,expanded:l,bubbleType:"reasoning"}),g=k("div","persona-flex persona-flex-col persona-text-left"),m=k("span","persona-text-xs persona-text-persona-primary"),v="Thinking...",h=e?.reasoning??{},T=String(n.startedAt??Date.now()),M=()=>{let H=k("span","");return H.setAttribute("data-tool-elapsed",T),H.textContent=dc(n),H},E=h.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:v,previewText:d,isActive:c,config:e??{},elapsed:dc(n),createElapsedElement:M});typeof E=="string"&&E.trim()?(m.textContent=E,g.appendChild(m)):E instanceof HTMLElement?g.appendChild(E):(m.textContent=v,g.appendChild(m));let I=k("span","persona-text-xs persona-text-persona-primary");I.textContent=Ih(n),g.appendChild(I);let P=s.loadingAnimation??"none",N=h.activeTextTemplate,x=h.completeTextTemplate,R=c?N:x,w=E instanceof HTMLElement,O=(H,J)=>{m.textContent="";let $=pc(H,""),ae=0;for(let re of $){let ue=re.styles.length>0?(()=>{let Ee=k("span",re.styles.map(he=>`persona-tool-text-${he}`).join(" "));return m.appendChild(Ee),Ee})():m;if(re.isDuration&&c)ue.appendChild(M());else{let Ee=re.isDuration?dc(n):re.text;J?ae=Zs(ue,Ee,ae):ue.appendChild(document.createTextNode(Ee))}}};if(!w&&R)if(I.style.display="none",m.style.display="",c&&P!=="none"){let H=h.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),P==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${H}ms`),O(R,!1)):(m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${H}ms`),P==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor)),O(R,!0))}else O(R,!1);else if(!w&&c&&P!=="none"){m.style.display="";let H=h.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),P==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${H}ms`);else{m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${H}ms`),P==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor));let J=m.textContent||v;m.textContent="",Zs(m,J,0)}n.status==="complete"&&(m.style.display="none")}else w||(n.status==="complete"?m.style.display="none":m.style.display="");if(s.iconName&&!w){let H=k("span","persona-reasoning-header-icon"),J=ge(s.iconName,16,"currentColor",2);J&&(H.appendChild(J),u.appendChild(H))}let K="currentColor",ie=ad(u,g,{expandable:i,expanded:l,iconColor:K,metaGap:!1}),Z=ld({bubble:o,previewKind:"reasoning",expanded:l,isActive:c,previewText:d,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:d,isActive:c,config:e??{}})});if(!i)return o.append(u,Z),o;let S=k("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");S.style.display=l?"":"none";let B=n.chunks.join(""),W=k("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return W.textContent=B||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),S.appendChild(W),cd({expanded:l,header:u,toggleIcon:ie,content:S,collapsedPreview:Z,iconColor:K}),o.append(u,Z,S),o};var hi=new Set,jv=t=>t.toggleTextColor||t.headerTextColor||"var(--persona-primary, #171717)",LE=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).slice(-e).join(`
|
|
29
29
|
`);let s=lc(n.args).trim();return s?s.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,e).join(`
|
|
30
|
-
`):""},gg=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},HE=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??"tool-call",i=n?.success===!1?n.error||"Tool failed":LE(t,o?.previewMaxLines??3),l=n?Hh(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",d=e?.toolCall??{},u=l;return s==="tool-name"?u=n.name?.trim()||l:s==="tool-preview"&&i&&(u=i),c&&d.activeTextTemplate?u=eu(n,d.activeTextTemplate,u):!c&&d.completeTextTemplate&&(u=eu(n,d.completeTextTemplate,u)),n.success===!1&&(u+=" \xB7 Failed"),{summary:u,previewText:i,isActive:c}},Vv=(t,e,n)=>{dd(t,e,{stateSet:hi,previewKind:"tool",iconColor:jv(n?.toolCall??{})})},fg=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},s=sd("persona-tool-bubble",t.id);if(o.backgroundColor&&(s.style.backgroundColor=o.backgroundColor),o.borderColor&&(s.style.borderColor=o.borderColor),o.borderWidth&&(s.style.borderWidth=o.borderWidth),o.borderRadius&&(s.style.borderRadius=o.borderRadius),s.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let i=e?.features?.toolCallDisplay??{},l=i.expandable!==!1,c=l&&hi.has(t.id),{summary:d,previewText:u,isActive:g}=HE(t,e),m=id({expandable:l,expanded:c,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let b=k("div","persona-flex persona-flex-col persona-text-left"),h=k("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(h.style.color=o.headerTextColor);let x=String(n.startedAt??Date.now()),T=()=>{let S=k("span","");return S.setAttribute("data-tool-elapsed",x),S.textContent=cc(n),S},M=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:d,previewText:u,collapsedMode:i.collapsedMode??"tool-call",isActive:g,config:e??{},elapsed:cc(n),createElapsedElement:T});typeof M=="string"&&M.trim()?(h.textContent=M,b.appendChild(h)):M instanceof HTMLElement?b.appendChild(M):(h.textContent=d,b.appendChild(h));let O=i.loadingAnimation??"none",I=o.activeTextTemplate,z=o.completeTextTemplate,A=g?I:z,H=M instanceof HTMLElement,w=(S,W)=>{h.textContent="";let R=n.name?.trim()||"tool",L=pc(S,R),J=0;for(let U of L){let ae=U.styles.length>0?(()=>{let re=k("span",U.styles.map(ue=>`persona-tool-text-${ue}`).join(" "));return h.appendChild(re),re})():h;if(U.isDuration&&g)ae.appendChild(T());else{let re=U.isDuration?cc(n):U.text;W?J=Zs(ae,re,J):ae.appendChild(document.createTextNode(re))}}};if(!H)if(g&&O!=="none"){let S=o.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),O==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${S}ms`),A&&w(A,!1);else if(h.classList.add(`persona-tool-loading-${O}`),h.style.setProperty("--persona-tool-anim-duration",`${S}ms`),O==="shimmer-color"&&(o.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),A)w(A,!0);else{let W=h.textContent||d;h.textContent="",Zs(h,W,0)}}else A&&w(A,!1);let D=jv(o),K=ad(m,b,{expandable:l,expanded:c,iconColor:D,metaGap:!0}),ie=ld({bubble:s,previewKind:"tool",expanded:c,isActive:g,previewText:u,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:u,isActive:g,config:e??{}})});if(!l)return s.append(m,ie),s;let Z=k("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(Z.style.display=c?"":"none",o.contentBackgroundColor&&(Z.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(Z.style.color=o.contentTextColor),o.contentPaddingX&&(Z.style.paddingLeft=o.contentPaddingX,Z.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(Z.style.paddingTop=o.contentPaddingY,Z.style.paddingBottom=o.contentPaddingY),n.name){let S=k("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?S.style.color=o.contentTextColor:o.headerTextColor&&(S.style.color=o.headerTextColor),S.textContent=n.name,Z.appendChild(S)}if(n.args!==void 0){let S=k("div","persona-space-y-1"),W=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(W.style.color=o.labelTextColor),W.textContent="Arguments";let R=k("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");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",gg(R,o),R.textContent=lc(n.args),S.append(W,R),Z.appendChild(S)}if(n.chunks&&n.chunks.length){let S=k("div","persona-space-y-1"),W=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(W.style.color=o.labelTextColor),W.textContent="Activity";let R=k("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");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",gg(R,o),R.textContent=n.chunks.join(""),S.append(W,R),Z.appendChild(S)}if(n.success===!1&&Z.appendChild(G("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),n.status==="complete"&&n.result!==void 0){let S=k("div","persona-space-y-1"),W=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(W.style.color=o.labelTextColor),W.textContent="Result";let R=k("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");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",gg(R,o),R.textContent=lc(n.result),S.append(W,R),Z.appendChild(S)}if(n.status==="complete"&&typeof n.duration=="number"){let S=k("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(S.style.color=o.contentTextColor),S.textContent=`Duration: ${n.duration}ms`,Z.appendChild(S)}return cd({expanded:c,header:m,toggleIcon:K,content:Z,collapsedPreview:ie,iconColor:D}),s.append(m,ie,Z),s};var{setLoader:KL,load:RE,provide:GL,getSync:WE}=Tt({fallbackImport:()=>import("./approval-ui-K7R5Q5OC.js")});var Kv=RE;var Gv=WE;var{setLoader:YL,load:BE}=Tt({fallbackImport:()=>import("./event-stream-view-GL3ADRY2.js")});var mg=BE;var hg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:oH,load:DE,provide:rH,getSync:OE}=Tt({fallbackImport:()=>import("./artifacts-ui-F4N6VMKF.js")}),yi=null,pd=new Set,Qv=t=>{if(yi)return yi;yi=t,t.initArtifactsUi({componentRegistry:Xo});for(let o of hg)Xo.has(o)||Xo.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Ys();e?t.__provideMarkdownParsers(e):sc(()=>{let o=Ys();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Nh());let n=[...pd];pd.clear();for(let o of n)try{o()}catch{}return t};var ud=()=>DE().then(Qv);var er=()=>{if(yi)return yi;let t=OE();return t?Qv(t):null},yg=t=>yi?()=>{}:(pd.add(t),()=>{pd.delete(t)});function mn(t){return t?.features?.artifacts?.enabled===!0}function Xv(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!mn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),s=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):s&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",s))}function _E(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Yv=["panel","seamless","detached"];function bg(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Yv.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function vg(t){return!t||!mn(t)?!1:bg(t)==="detached"}function Ua(t,e){if(!mn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),_E(t),Xv(t,e);return}let n=e.features?.artifacts?.layout,o=bg(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let s=n?.paneBackground?.trim();s?t.style.setProperty("--persona-artifact-pane-bg",s):t.style.removeProperty("--persona-artifact-pane-bg");let i=n?.panePadding?.trim();i?t.style.setProperty("--persona-artifact-pane-padding",i):t.style.removeProperty("--persona-artifact-pane-padding");let l=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[c,d]of l){let u=c?.trim();u?t.style.setProperty(d,u):t.style.removeProperty(d)}Xv(t,e)}function $a(t,e){for(let c of Yv)t.classList.remove(`persona-artifact-appearance-${c}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!mn(e))return;let n=e.features?.artifacts?.layout,o=bg(e);t.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let i=n?.paneShadow?.trim();i&&t.style.setProperty("--persona-artifact-pane-shadow",i);let l=n?.chatShadow?.trim();l&&t.style.setProperty("--persona-artifact-chat-shadow",l)}function Jv(t,e){return!e||!mn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var NE=new Set(["__proto__","prototype","constructor"]),FE=new Set(["collapsed","card","panel","inline"]),Zv=new Set(["markdown","component"]),UE=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ms=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),fd=t=>!NE.has(t),Cg=t=>typeof t=="string"&&FE.has(t),hs=t=>Object.keys(t).length>0;function To(t,e,n,o){t.push({path:e,code:n,message:o})}var $E="Ignored because this key is not part of the persisted preference schema.",gd="Ignored an unsupported value.",qE="Expected collapsed, panel, or inline.",zE='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',eC={kind:"mode",message:gd},bi={kind:"string",message:"Expected a CSS length string."},tr={kind:"boolean"},jE={paneWidth:bi,paneMaxWidth:bi,paneMinWidth:bi,expandedPanelWidth:bi,resizableMinWidth:bi,resizableMaxWidth:bi,expandLauncherPanelWhenOpen:tr,resizable:tr},VE={kind:"object",message:"Expected a preference object.",children:{showToolCalls:tr,showReasoning:tr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:gd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:gd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:gd},expandable:tr,grouped:tr}},reasoningDisplay:{kind:"object",children:{expandable:tr,activePreview:tr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:eC,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:eC,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Zv,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Zv}}},filePreview:{kind:"object",children:{enabled:tr}},layout:{kind:"object",children:jE}}}}};function tC(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:To(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:To(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:To(o,n,"invalid_value",e.message);case"mode":return Cg(t)?Qn(t):To(o,n,"invalid_value",e.message);case"modeMap":{if(!ms(t))return To(o,n,"invalid_type","Expected an object.");let s=e.keys==="mediaType"?void 0:e.keys,i={};for(let[l,c]of Object.entries(t)){let d=s?l:ei(l);fd(l)&&(s?s.has(l):UE.test(d))?Cg(c)?i[d]=Qn(c):To(o,`${n}.${l}`,"invalid_value",qE):To(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":zE)}return hs(i)?i:void 0}case"object":{if(e.bareMode&&Cg(t))return Qn(t);if(!ms(t))return To(o,n,"invalid_type",e.message??"Expected an object.");let s=Object.keys(e.children),i=c=>n?`${n}.${c}`:c;for(let c of Object.keys(t))(!fd(c)||!s.includes(c))&&To(o,i(c),"unknown_key",$E);let l={};for(let c of s){let d=e.children[c],u=tC(t[c],d,i(c),o);if(d.deprecated&&t[c]!==void 0&&To(o,i(c),"deprecated_key",d.deprecated),u===void 0)continue;let g=d.alias??c,m=l[g];l[g]=ms(m)&&ms(u)?{...m,...u}:u}return hs(l)?l:void 0}}}function KE(t){let e=[];return{preferences:(t===null?void 0:tC(t,VE,"",e))??{},issues:e}}function vi(t){if(Array.isArray(t))return t.map(vi);if(!ms(t))return t;let e={};for(let[n,o]of Object.entries(t))fd(n)&&o!==void 0&&(e[n]=vi(o));return e}function nC(t,e){let n=vi(t);for(let[o,s]of Object.entries(e)){if(!fd(o)||s===void 0)continue;let i=n[o];n[o]=ms(i)&&ms(s)?nC(i,s):vi(s)}return n}function GE(t){let e={},n;for(let s of t){let i=KE(s).preferences;n=oC(n,i.artifacts?.display),e=nC(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function QE(t,e){if(e===void 0)return t===void 0?void 0:vi(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byMediaType,...e.byMediaType},i={...o?{default:o}:{},...hs(s)?{byMediaType:s}:{}};return hs(i)?i:void 0}function oC(t,e){if(e===void 0)return t===void 0?void 0:vi(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byType,...n.byKind,...e.byType,...e.byKind},i=QE(n.files,e.files),l={...o?{default:o}:{},...hs(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return hs(l)?l:void 0}function XE(t={},e){let n=GE(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let s=t.artifacts??{},i={...s};if(n.artifacts.display!==void 0){let l=oC(s.display,n.artifacts.display);l!==void 0&&(i.display=l)}n.artifacts.filePreview&&(i.filePreview={...s.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...s.layout,...n.artifacts.layout}),o.artifacts=i}return o}function wg(t){let e=t.preferences;return!e||!hs(e)?t:{...t,features:XE(t.features??{},[e])}}function YE(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function JE(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function ZE(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function eT(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function Sg(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let i=/^([\d.]+)/.exec(o);return i?Number(i[1]):8}function rC(t,e,n,o,s,i,l=200){let c=YE(s,200),d=eT(e,n,o,l);d=Math.max(c,d);let u=JE(i);return u!==null&&(d=Math.min(d,u)),ZE(t,c,d)}var{setLoader:pH,load:tT,provide:uH,getSync:nT}=Tt({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var sC=tT;var iC=nT;var xg=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(i=>i.id));return[...n.filter(i=>!o.has(i.id)),...e].sort((i,l)=>(l.priority??0)-(i.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Ag=new xg;var aC=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),oT=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),lC=(t,e,n)=>{if(!aC(t)||!aC(e)||oT.has(n))return e;let o={...t};for(let s of Object.keys(e)){if(e[s]===void 0){delete o[s];continue}let i=n?`${n}.${s}`:s;o[s]=lC(t[s],e[s],i)}return o};function cC(t,e){let n=lC(t,e,"");return Hc(n)}var dC=()=>{let t=new Map,e=(s,i)=>(t.has(s)||t.set(s,new Set),t.get(s).add(i),()=>n(s,i)),n=(s,i)=>{t.get(s)?.delete(i)};return{on:e,off:n,emit:(s,i)=>{t.get(s)?.forEach(l=>{try{l(i)}catch(c){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var rT=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},sT=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let s=n;s<e.length;s+=1){let i=e[s];if(i==="{"&&(o+=1),i==="}"&&(o-=1,o===0))return e.slice(n,s+1)}return null},Eg=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=rT(t),n=sT(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...i}=o;return{type:String(s),payload:i,raw:o}}catch{return null}},Mg=t=>typeof t=="string"?t:t==null?"":String(t),qa={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Mg(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Mg(n.element);if(o&&e.document?.querySelector){let s=e.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Mg(n.text)}}},pC=t=>Array.isArray(t)?t.map(e=>String(e)):[],Tg=t=>{let e=new Set(pC(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(pC(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let i=Array.from(e);t.updateSessionMetadata(l=>({...l,processedActionMessageIds:i}))};return{process:i=>{if(i.streaming||i.message.role!=="assistant"||!i.text||e.has(i.message.id))return null;let l=typeof i.raw=="string"&&i.raw||typeof i.message.rawContent=="string"&&i.message.rawContent||typeof i.text=="string"&&i.text||null;!l&&typeof i.text=="string"&&i.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 c=l?t.parsers.reduce((u,g)=>u||g?.({text:l,message:i.message})||null,null):null;if(!c)return null;e.add(i.message.id),o();let d={action:c,message:i.message};t.emit("action:detected",d);for(let u of t.handlers)if(u)try{let g=()=>{t.emit("action:resubmit",d)},m=u(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:g});if(!m)continue;if(m.handled){let b=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:b,resubmit:m.resubmit}}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:n}};var iT=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},aT=t=>t.map(e=>({...e,streaming:!1})),lT=t=>t.map(e=>({...e,status:"complete"})),uC=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?iT(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?aT(n.messages):void 0,artifacts:n.artifacts?lT(n.artifacts):void 0};o.setItem(t,JSON.stringify(s))}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var cT=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},gC=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return cT(t)},dT=async(t,e)=>{let n=await gC(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await gC(`${t}\0${e}`)}`}};var fC=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,d=0,u=null,g=null,m=new Set,b=()=>{if(n||l)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return l=!0,null}},h=()=>{let w=b();if(!w)return u;try{return w.getItem(o)}catch{return l=!0,u}},x=(w,D)=>{if(c||w===u)return;let K=u;u=w,d+=1;let ie={previousToken:K,token:w,source:D,revision:d};for(let Z of m)Z(ie)},T=w=>{c||w.key!==null&&w.key!==o||x(w.key===null?null:w.newValue??null,"external")},M=(async()=>{let w=await dT(t,e);o=w.storageKey,s=w.leaseKey,i=w.lockName,u=h(),!n&&typeof window<"u"&&window.addEventListener("storage",T)})(),O=w=>new Promise(D=>setTimeout(D,w)),I=()=>{let w=b();if(!w)return null;try{let D=w.getItem(s);if(!D)return null;let K=JSON.parse(D);return typeof K?.expiresAt=="number"&&typeof K?.ownerNonce=="string"?K:null}catch{return null}},z=w=>{let D=b();if(D)try{I()?.ownerNonce===w&&D.removeItem(s)}catch{}},A=w=>new Promise(D=>{let K=setTimeout(ie,w);function ie(){clearTimeout(K),window.removeEventListener("storage",Z),D()}function Z(S){(S.key===null||S.key===s)&&ie()}window.addEventListener("storage",Z)}),H=async w=>{let D=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,K=Date.now()+15e3;for(;Date.now()<K;){let ie=b();if(!ie)break;let Z=Date.now(),S=I();if(S&&S.expiresAt>Z&&S.ownerNonce!==D){await A(Math.min(S.expiresAt-Z,500));continue}try{ie.setItem(s,JSON.stringify({ownerNonce:D,expiresAt:Z+1e4}))}catch{l=!0;break}if(await O(20+Math.random()*40),I()?.ownerNonce!==D){await A(500);continue}g=D;try{return await w()}finally{g=null,z(D)}}return w()};return{ready:M,async get(){return await M,x(h(),"external"),u},async set(w){await M;let D=b();if(D)try{D.setItem(o,w)}catch{l=!0}x(w,"local")},async clear(){await M;let w=b();if(w)try{w.removeItem(o)}catch{l=!0}x(null,"local")},revision(){return d},subscribe(w){return m.add(w),()=>{m.delete(w)}},async withFirstInitLock(w){await M;let D=globalThis.navigator?.locks;return D?.request?D.request(i,()=>w()):b()?H(w):w()},matches(w,D,K){return w===t&&D===e&&K===n},destroy(){c=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",T),g&&z(g)}}};var{setLoader:SH,load:pT}=Tt({fallbackImport:()=>import("./history-view-BD6OXLNA.js")});var kg=pT;var Pg=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},nr=t=>Object.freeze({...t}),mC=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),hC=t=>t?nr(t):null;function yC(t){let{plugins:e,config:n}=t,o=!1,s=!1,i=!1,l=!1,c=null,d=[],u=()=>{for(let A of d.splice(0))try{A()}catch(H){Pg("renderHistoryView cleanup",H)}},g=(A,H)=>{for(let w of e){let D=w[A];if(D)try{let K=D(H);if(K)return K}catch(K){Pg(A,K)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),b={header:A=>l?g("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:nr(A.identityStatus),pendingAction:hC(A.pendingAction),copy:nr(A.copy),actions:Object.freeze({close:T.close,startNewConversation:T.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>l?g("renderHistoryConversation",Object.freeze({...m(),conversation:mC(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>l?g("renderHistoryState",Object.freeze({...m(),state:nr(A.state),identityStatus:nr(A.identityStatus),copy:nr(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},h=e.flatMap(A=>(A.railSections??[]).map(H=>({...H,placement:H.placement??"above-conversations",items:[],render:w=>H.render(Object.freeze({collapsed:w,presentation:t.getPresentation(),actions:T}))}))),x=t.createView({slots:b,renderDom:!1,onModelChange:()=>z(),railSections:h}),T=Object.freeze({...x.operations,close:t.close}),M=()=>(l=!0,x.setDomRenderEnabled(!0),x.element),O=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(mC)),activeConversationId:A.activeConversationId,state:nr(A.state),pendingAction:hC(A.pendingAction),identityStatus:nr(A.identityStatus),nextCursor:A.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:nr(x.copy),actions:T,defaultRenderer:M,requestRender:()=>z(),onCleanup:H=>{d.push(H)}}),I=()=>{l=!1;let A=null;for(let w of e)if(w.renderHistoryView){try{A=w.renderHistoryView(O(x.getModel()))}catch(D){Pg("renderHistoryView",D),A=null}if(A)break}let H=!A||A.contains(x.element);return l=H,x.setDomRenderEnabled(H),A??x.element};function z(){if(!(!i||o||s)){s=!0;try{u();let A=I();if(A===c)return;let H=c;c=A,t.onElementChanged(A,H)}finally{s=!1}}}return i=!0,z(),{view:x,get element(){return c??x.element},requestRender:z,dispose:()=>{o=!0,u()}}}var uT=null;function bC(){return uT}var gT=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"]]),fT=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."]]),Ig=t=>fT.get(t)??"Conversation history is unavailable right now.";function mT(t){if(t instanceof ls)return t;if(t instanceof Oe){let e=gT.get(t.code)??"unavailable";return new ls(e,Ig(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new ls("unavailable",Ig("unavailable"))}function vC(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},s=c=>{if(!n.includes(c))throw new ls("unsupported_scope",Ig("unsupported_scope"))},i=async(c,d)=>{s(c);try{return await d()}catch(u){throw mT(u)}},l=c=>{let d=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){d||(d=!0,c.commit(),await t.onActivationCommitted(c.session))},discard(){d||(d=!0,c.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(c){return e().subscribeHistoryIdentityStatus(c)},subscribeAvailability(c){return e().subscribeHistoryAvailability(c)},async list(c){return i(c.context.scope,async()=>{let d=await e().listConversations({...c.cursor?{cursor:c.cursor}:{},...c.limit!==void 0?{limit:c.limit}:{},...c.targetId?{targetId:c.targetId}:{},scope:c.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(c,d){return i(d.context.scope,async()=>{let u=await e().getConversation(c,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),g=Uy(u.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:u.summary,messages:wa([],g),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(c,d){return i(d.context.scope,async()=>l(await e().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await e().prepareNewConversationSession()))},async delete(c,d){await i(d.context.scope,()=>e().deleteConversation(c,{scope:d.context.scope}))},async deleteAll(c){return i(c.context.scope,()=>e().deleteAllConversations({...c.targetId!==void 0?{targetId:c.targetId}:{},scope:c.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var hT="button:not([disabled])";function md(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,s=`persona-history-confirm-desc-${n}`,i=G("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),l=G("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),c=G("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":s},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"}},G("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),G("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:s},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),G("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},i,l));for(let u of[i,l])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";i.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",i.style.background="transparent",i.style.color="inherit",l.style.border="none",l.style.background="var(--persona-danger, #b42318)",l.style.color="var(--persona-danger-fg, #ffffff)";let d=G("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))"}},c);return new Promise(u=>{let g=!1,m=h=>{g||(g=!0,d.removeEventListener("keydown",b,!0),d.remove(),e?.focus(),u(h))};function b(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let x=Array.from(c.querySelectorAll(hT));if(x.length===0)return;let T=x[0],M=x[x.length-1],O=document.activeElement;h.shiftKey&&(O===T||!c.contains(O))?(h.preventDefault(),M.focus()):!h.shiftKey&&O===M&&(h.preventDefault(),T.focus())}d.addEventListener("keydown",b,!0),d.addEventListener("pointerdown",h=>{h.target===d&&m(!1)}),i.addEventListener("click",()=>m(!1)),l.addEventListener("click",()=>m(!0)),t.host.appendChild(d),i.focus()})}import{parse as RH,STR as WH,OBJ as BH}from"partial-json";function CC(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=Xo.get(t.component);if(!i){if(hg.includes(t.component)){ud().catch(()=>{});let c=k("div","persona-w-full");return c.setAttribute("data-persona-artifact-pending","true"),c}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let l={message:o,config:n,updateProps:c=>{s&&s(c)}};try{return i(t.props,l)}catch(c){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,c),null}}function wC(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Lg(t){let e=wC(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function SC(t){let e=wC(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var yT=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function xC(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:i="Share your thoughts (optional)...",submitText:l="Submit",skipText:c="Skip",showComment:d=!0,ratingLabels:u=yT}=t,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let m=null,b=document.createElement("div");b.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,h.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,h.appendChild(T),b.appendChild(h);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 O=[];for(let w=1;w<=5;w++){let D=document.createElement("button");D.type="button",D.className="persona-feedback-rating-btn persona-feedback-star-btn",D.setAttribute("role","radio"),D.setAttribute("aria-checked","false"),D.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${u[w-1]}`),D.title=u[w-1],D.dataset.rating=String(w),D.innerHTML=`
|
|
30
|
+
`):""},gg=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},HE=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??"tool-call",i=n?.success===!1?n.error||"Tool failed":LE(t,o?.previewMaxLines??3),l=n?Hh(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",d=e?.toolCall??{},u=l;return s==="tool-name"?u=n.name?.trim()||l:s==="tool-preview"&&i&&(u=i),c&&d.activeTextTemplate?u=eu(n,d.activeTextTemplate,u):!c&&d.completeTextTemplate&&(u=eu(n,d.completeTextTemplate,u)),n.success===!1&&(u+=" \xB7 Failed"),{summary:u,previewText:i,isActive:c}},Vv=(t,e,n)=>{dd(t,e,{stateSet:hi,previewKind:"tool",iconColor:jv(n?.toolCall??{})})},fg=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},s=sd("persona-tool-bubble",t.id);if(o.backgroundColor&&(s.style.backgroundColor=o.backgroundColor),o.borderColor&&(s.style.borderColor=o.borderColor),o.borderWidth&&(s.style.borderWidth=o.borderWidth),o.borderRadius&&(s.style.borderRadius=o.borderRadius),s.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let i=e?.features?.toolCallDisplay??{},l=i.expandable!==!1,c=l&&hi.has(t.id),{summary:d,previewText:u,isActive:g}=HE(t,e),m=id({expandable:l,expanded:c,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let v=k("div","persona-flex persona-flex-col persona-text-left"),h=k("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(h.style.color=o.headerTextColor);let T=String(n.startedAt??Date.now()),M=()=>{let S=k("span","");return S.setAttribute("data-tool-elapsed",T),S.textContent=cc(n),S},E=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:d,previewText:u,collapsedMode:i.collapsedMode??"tool-call",isActive:g,config:e??{},elapsed:cc(n),createElapsedElement:M});typeof E=="string"&&E.trim()?(h.textContent=E,v.appendChild(h)):E instanceof HTMLElement?v.appendChild(E):(h.textContent=d,v.appendChild(h));let I=i.loadingAnimation??"none",P=o.activeTextTemplate,N=o.completeTextTemplate,x=g?P:N,R=E instanceof HTMLElement,w=(S,B)=>{h.textContent="";let W=n.name?.trim()||"tool",H=pc(S,W),J=0;for(let $ of H){let ae=$.styles.length>0?(()=>{let re=k("span",$.styles.map(ue=>`persona-tool-text-${ue}`).join(" "));return h.appendChild(re),re})():h;if($.isDuration&&g)ae.appendChild(M());else{let re=$.isDuration?cc(n):$.text;B?J=Zs(ae,re,J):ae.appendChild(document.createTextNode(re))}}};if(!R)if(g&&I!=="none"){let S=o.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),I==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${S}ms`),x&&w(x,!1);else if(h.classList.add(`persona-tool-loading-${I}`),h.style.setProperty("--persona-tool-anim-duration",`${S}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),x)w(x,!0);else{let B=h.textContent||d;h.textContent="",Zs(h,B,0)}}else x&&w(x,!1);let O=jv(o),K=ad(m,v,{expandable:l,expanded:c,iconColor:O,metaGap:!0}),ie=ld({bubble:s,previewKind:"tool",expanded:c,isActive:g,previewText:u,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:u,isActive:g,config:e??{}})});if(!l)return s.append(m,ie),s;let Z=k("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(Z.style.display=c?"":"none",o.contentBackgroundColor&&(Z.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(Z.style.color=o.contentTextColor),o.contentPaddingX&&(Z.style.paddingLeft=o.contentPaddingX,Z.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(Z.style.paddingTop=o.contentPaddingY,Z.style.paddingBottom=o.contentPaddingY),n.name){let S=k("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?S.style.color=o.contentTextColor:o.headerTextColor&&(S.style.color=o.headerTextColor),S.textContent=n.name,Z.appendChild(S)}if(n.args!==void 0){let S=k("div","persona-space-y-1"),B=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Arguments";let W=k("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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",gg(W,o),W.textContent=lc(n.args),S.append(B,W),Z.appendChild(S)}if(n.chunks&&n.chunks.length){let S=k("div","persona-space-y-1"),B=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Activity";let W=k("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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",gg(W,o),W.textContent=n.chunks.join(""),S.append(B,W),Z.appendChild(S)}if(n.success===!1&&Z.appendChild(G("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),n.status==="complete"&&n.result!==void 0){let S=k("div","persona-space-y-1"),B=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Result";let W=k("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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",gg(W,o),W.textContent=lc(n.result),S.append(B,W),Z.appendChild(S)}if(n.status==="complete"&&typeof n.duration=="number"){let S=k("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(S.style.color=o.contentTextColor),S.textContent=`Duration: ${n.duration}ms`,Z.appendChild(S)}return cd({expanded:c,header:m,toggleIcon:K,content:Z,collapsedPreview:ie,iconColor:O}),s.append(m,ie,Z),s};var{setLoader:KL,load:RE,provide:GL,getSync:WE}=Tt({fallbackImport:()=>import("./approval-ui-K7R5Q5OC.js")});var Kv=RE;var Gv=WE;var{setLoader:YL,load:BE}=Tt({fallbackImport:()=>import("./event-stream-view-GL3ADRY2.js")});var mg=BE;var hg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:oH,load:DE,provide:rH,getSync:OE}=Tt({fallbackImport:()=>import("./artifacts-ui-F4N6VMKF.js")}),yi=null,pd=new Set,Qv=t=>{if(yi)return yi;yi=t,t.initArtifactsUi({componentRegistry:Xo});for(let o of hg)Xo.has(o)||Xo.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Ys();e?t.__provideMarkdownParsers(e):sc(()=>{let o=Ys();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Nh());let n=[...pd];pd.clear();for(let o of n)try{o()}catch{}return t};var ud=()=>DE().then(Qv);var er=()=>{if(yi)return yi;let t=OE();return t?Qv(t):null},yg=t=>yi?()=>{}:(pd.add(t),()=>{pd.delete(t)});function mn(t){return t?.features?.artifacts?.enabled===!0}function Xv(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!mn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),s=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):s&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",s))}function _E(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Yv=["panel","seamless","detached"];function bg(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Yv.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function vg(t){return!t||!mn(t)?!1:bg(t)==="detached"}function Ua(t,e){if(!mn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),_E(t),Xv(t,e);return}let n=e.features?.artifacts?.layout,o=bg(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let s=n?.paneBackground?.trim();s?t.style.setProperty("--persona-artifact-pane-bg",s):t.style.removeProperty("--persona-artifact-pane-bg");let i=n?.panePadding?.trim();i?t.style.setProperty("--persona-artifact-pane-padding",i):t.style.removeProperty("--persona-artifact-pane-padding");let l=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[c,d]of l){let u=c?.trim();u?t.style.setProperty(d,u):t.style.removeProperty(d)}Xv(t,e)}function $a(t,e){for(let c of Yv)t.classList.remove(`persona-artifact-appearance-${c}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!mn(e))return;let n=e.features?.artifacts?.layout,o=bg(e);t.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let i=n?.paneShadow?.trim();i&&t.style.setProperty("--persona-artifact-pane-shadow",i);let l=n?.chatShadow?.trim();l&&t.style.setProperty("--persona-artifact-chat-shadow",l)}function Jv(t,e){return!e||!mn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var NE=new Set(["__proto__","prototype","constructor"]),FE=new Set(["collapsed","card","panel","inline"]),Zv=new Set(["markdown","component"]),UE=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ms=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),fd=t=>!NE.has(t),Cg=t=>typeof t=="string"&&FE.has(t),hs=t=>Object.keys(t).length>0;function ko(t,e,n,o){t.push({path:e,code:n,message:o})}var $E="Ignored because this key is not part of the persisted preference schema.",gd="Ignored an unsupported value.",qE="Expected collapsed, panel, or inline.",zE='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',eC={kind:"mode",message:gd},bi={kind:"string",message:"Expected a CSS length string."},tr={kind:"boolean"},jE={paneWidth:bi,paneMaxWidth:bi,paneMinWidth:bi,expandedPanelWidth:bi,resizableMinWidth:bi,resizableMaxWidth:bi,expandLauncherPanelWhenOpen:tr,resizable:tr},VE={kind:"object",message:"Expected a preference object.",children:{showToolCalls:tr,showReasoning:tr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:gd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:gd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:gd},expandable:tr,grouped:tr}},reasoningDisplay:{kind:"object",children:{expandable:tr,activePreview:tr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:eC,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:eC,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Zv,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Zv}}},filePreview:{kind:"object",children:{enabled:tr}},layout:{kind:"object",children:jE}}}}};function tC(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:ko(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:ko(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:ko(o,n,"invalid_value",e.message);case"mode":return Cg(t)?Xn(t):ko(o,n,"invalid_value",e.message);case"modeMap":{if(!ms(t))return ko(o,n,"invalid_type","Expected an object.");let s=e.keys==="mediaType"?void 0:e.keys,i={};for(let[l,c]of Object.entries(t)){let d=s?l:ei(l);fd(l)&&(s?s.has(l):UE.test(d))?Cg(c)?i[d]=Xn(c):ko(o,`${n}.${l}`,"invalid_value",qE):ko(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":zE)}return hs(i)?i:void 0}case"object":{if(e.bareMode&&Cg(t))return Xn(t);if(!ms(t))return ko(o,n,"invalid_type",e.message??"Expected an object.");let s=Object.keys(e.children),i=c=>n?`${n}.${c}`:c;for(let c of Object.keys(t))(!fd(c)||!s.includes(c))&&ko(o,i(c),"unknown_key",$E);let l={};for(let c of s){let d=e.children[c],u=tC(t[c],d,i(c),o);if(d.deprecated&&t[c]!==void 0&&ko(o,i(c),"deprecated_key",d.deprecated),u===void 0)continue;let g=d.alias??c,m=l[g];l[g]=ms(m)&&ms(u)?{...m,...u}:u}return hs(l)?l:void 0}}}function KE(t){let e=[];return{preferences:(t===null?void 0:tC(t,VE,"",e))??{},issues:e}}function vi(t){if(Array.isArray(t))return t.map(vi);if(!ms(t))return t;let e={};for(let[n,o]of Object.entries(t))fd(n)&&o!==void 0&&(e[n]=vi(o));return e}function nC(t,e){let n=vi(t);for(let[o,s]of Object.entries(e)){if(!fd(o)||s===void 0)continue;let i=n[o];n[o]=ms(i)&&ms(s)?nC(i,s):vi(s)}return n}function GE(t){let e={},n;for(let s of t){let i=KE(s).preferences;n=oC(n,i.artifacts?.display),e=nC(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function QE(t,e){if(e===void 0)return t===void 0?void 0:vi(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byMediaType,...e.byMediaType},i={...o?{default:o}:{},...hs(s)?{byMediaType:s}:{}};return hs(i)?i:void 0}function oC(t,e){if(e===void 0)return t===void 0?void 0:vi(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byType,...n.byKind,...e.byType,...e.byKind},i=QE(n.files,e.files),l={...o?{default:o}:{},...hs(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return hs(l)?l:void 0}function XE(t={},e){let n=GE(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let s=t.artifacts??{},i={...s};if(n.artifacts.display!==void 0){let l=oC(s.display,n.artifacts.display);l!==void 0&&(i.display=l)}n.artifacts.filePreview&&(i.filePreview={...s.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...s.layout,...n.artifacts.layout}),o.artifacts=i}return o}function wg(t){let e=t.preferences;return!e||!hs(e)?t:{...t,features:XE(t.features??{},[e])}}function YE(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function JE(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function ZE(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function eT(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function Sg(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let i=/^([\d.]+)/.exec(o);return i?Number(i[1]):8}function rC(t,e,n,o,s,i,l=200){let c=YE(s,200),d=eT(e,n,o,l);d=Math.max(c,d);let u=JE(i);return u!==null&&(d=Math.min(d,u)),ZE(t,c,d)}var{setLoader:pH,load:tT,provide:uH,getSync:nT}=Tt({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var sC=tT;var iC=nT;var xg=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(i=>i.id));return[...n.filter(i=>!o.has(i.id)),...e].sort((i,l)=>(l.priority??0)-(i.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Ag=new xg;var aC=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),oT=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),lC=(t,e,n)=>{if(!aC(t)||!aC(e)||oT.has(n))return e;let o={...t};for(let s of Object.keys(e)){if(e[s]===void 0){delete o[s];continue}let i=n?`${n}.${s}`:s;o[s]=lC(t[s],e[s],i)}return o};function cC(t,e){let n=lC(t,e,"");return Hc(n)}var dC=()=>{let t=new Map,e=(s,i)=>(t.has(s)||t.set(s,new Set),t.get(s).add(i),()=>n(s,i)),n=(s,i)=>{t.get(s)?.delete(i)};return{on:e,off:n,emit:(s,i)=>{t.get(s)?.forEach(l=>{try{l(i)}catch(c){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var rT=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},sT=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let s=n;s<e.length;s+=1){let i=e[s];if(i==="{"&&(o+=1),i==="}"&&(o-=1,o===0))return e.slice(n,s+1)}return null},Eg=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=rT(t),n=sT(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...i}=o;return{type:String(s),payload:i,raw:o}}catch{return null}},Mg=t=>typeof t=="string"?t:t==null?"":String(t),qa={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Mg(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Mg(n.element);if(o&&e.document?.querySelector){let s=e.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Mg(n.text)}}},pC=t=>Array.isArray(t)?t.map(e=>String(e)):[],Tg=t=>{let e=new Set(pC(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(pC(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let i=Array.from(e);t.updateSessionMetadata(l=>({...l,processedActionMessageIds:i}))};return{process:i=>{if(i.streaming||i.message.role!=="assistant"||!i.text||e.has(i.message.id))return null;let l=typeof i.raw=="string"&&i.raw||typeof i.message.rawContent=="string"&&i.message.rawContent||typeof i.text=="string"&&i.text||null;!l&&typeof i.text=="string"&&i.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 c=l?t.parsers.reduce((u,g)=>u||g?.({text:l,message:i.message})||null,null):null;if(!c)return null;e.add(i.message.id),o();let d={action:c,message:i.message};t.emit("action:detected",d);for(let u of t.handlers)if(u)try{let g=()=>{t.emit("action:resubmit",d)},m=u(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:g});if(!m)continue;if(m.handled){let v=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:v,resubmit:m.resubmit}}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:n}};var iT=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},aT=t=>t.map(e=>({...e,streaming:!1})),lT=t=>t.map(e=>({...e,status:"complete"})),uC=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?iT(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?aT(n.messages):void 0,artifacts:n.artifacts?lT(n.artifacts):void 0};o.setItem(t,JSON.stringify(s))}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var cT=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},gC=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return cT(t)},dT=async(t,e)=>{let n=await gC(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await gC(`${t}\0${e}`)}`}};var fC=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,d=0,u=null,g=null,m=new Set,v=()=>{if(n||l)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return l=!0,null}},h=()=>{let w=v();if(!w)return u;try{return w.getItem(o)}catch{return l=!0,u}},T=(w,O)=>{if(c||w===u)return;let K=u;u=w,d+=1;let ie={previousToken:K,token:w,source:O,revision:d};for(let Z of m)Z(ie)},M=w=>{c||w.key!==null&&w.key!==o||T(w.key===null?null:w.newValue??null,"external")},E=(async()=>{let w=await dT(t,e);o=w.storageKey,s=w.leaseKey,i=w.lockName,u=h(),!n&&typeof window<"u"&&window.addEventListener("storage",M)})(),I=w=>new Promise(O=>setTimeout(O,w)),P=()=>{let w=v();if(!w)return null;try{let O=w.getItem(s);if(!O)return null;let K=JSON.parse(O);return typeof K?.expiresAt=="number"&&typeof K?.ownerNonce=="string"?K:null}catch{return null}},N=w=>{let O=v();if(O)try{P()?.ownerNonce===w&&O.removeItem(s)}catch{}},x=w=>new Promise(O=>{let K=setTimeout(ie,w);function ie(){clearTimeout(K),window.removeEventListener("storage",Z),O()}function Z(S){(S.key===null||S.key===s)&&ie()}window.addEventListener("storage",Z)}),R=async w=>{let O=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,K=Date.now()+15e3;for(;Date.now()<K;){let ie=v();if(!ie)break;let Z=Date.now(),S=P();if(S&&S.expiresAt>Z&&S.ownerNonce!==O){await x(Math.min(S.expiresAt-Z,500));continue}try{ie.setItem(s,JSON.stringify({ownerNonce:O,expiresAt:Z+1e4}))}catch{l=!0;break}if(await I(20+Math.random()*40),P()?.ownerNonce!==O){await x(500);continue}g=O;try{return await w()}finally{g=null,N(O)}}return w()};return{ready:E,async get(){return await E,T(h(),"external"),u},async set(w){await E;let O=v();if(O)try{O.setItem(o,w)}catch{l=!0}T(w,"local")},async clear(){await E;let w=v();if(w)try{w.removeItem(o)}catch{l=!0}T(null,"local")},revision(){return d},subscribe(w){return m.add(w),()=>{m.delete(w)}},async withFirstInitLock(w){await E;let O=globalThis.navigator?.locks;return O?.request?O.request(i,()=>w()):v()?R(w):w()},matches(w,O,K){return w===t&&O===e&&K===n},destroy(){c=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",M),g&&N(g)}}};var{setLoader:SH,load:pT}=Tt({fallbackImport:()=>import("./history-view-BD6OXLNA.js")});var kg=pT;var Pg=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},nr=t=>Object.freeze({...t}),mC=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),hC=t=>t?nr(t):null;function yC(t){let{plugins:e,config:n}=t,o=!1,s=!1,i=!1,l=!1,c=null,d=[],u=()=>{for(let x of d.splice(0))try{x()}catch(R){Pg("renderHistoryView cleanup",R)}},g=(x,R)=>{for(let w of e){let O=w[x];if(O)try{let K=O(R);if(K)return K}catch(K){Pg(x,K)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),v={header:x=>l?g("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:nr(x.identityStatus),pendingAction:hC(x.pendingAction),copy:nr(x.copy),actions:Object.freeze({close:M.close,startNewConversation:M.startNewConversation}),defaultRenderer:x.defaultRenderer})):null,conversation:x=>l?g("renderHistoryConversation",Object.freeze({...m(),conversation:mC(x.conversation),active:x.active,pending:x.pending,open:x.open,requestDelete:x.requestDelete,defaultRenderer:x.defaultRenderer})):null,state:x=>l?g("renderHistoryState",Object.freeze({...m(),state:nr(x.state),identityStatus:nr(x.identityStatus),copy:nr(x.copy),...x.retry?{retry:x.retry}:{},...x.startNewConversation?{startNewConversation:x.startNewConversation}:{},defaultRenderer:x.defaultRenderer})):null},h=e.flatMap(x=>(x.railSections??[]).map(R=>({...R,placement:R.placement??"above-conversations",items:[],render:w=>R.render(Object.freeze({collapsed:w,presentation:t.getPresentation(),actions:M}))}))),T=t.createView({slots:v,renderDom:!1,onModelChange:()=>N(),railSections:h}),M=Object.freeze({...T.operations,close:t.close}),E=()=>(l=!0,T.setDomRenderEnabled(!0),T.element),I=x=>Object.freeze({conversations:Object.freeze(x.conversations.map(mC)),activeConversationId:x.activeConversationId,state:nr(x.state),pendingAction:hC(x.pendingAction),identityStatus:nr(x.identityStatus),nextCursor:x.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:nr(T.copy),actions:M,defaultRenderer:E,requestRender:()=>N(),onCleanup:R=>{d.push(R)}}),P=()=>{l=!1;let x=null;for(let w of e)if(w.renderHistoryView){try{x=w.renderHistoryView(I(T.getModel()))}catch(O){Pg("renderHistoryView",O),x=null}if(x)break}let R=!x||x.contains(T.element);return l=R,T.setDomRenderEnabled(R),x??T.element};function N(){if(!(!i||o||s)){s=!0;try{u();let x=P();if(x===c)return;let R=c;c=x,t.onElementChanged(x,R)}finally{s=!1}}}return i=!0,N(),{view:T,get element(){return c??T.element},requestRender:N,dispose:()=>{o=!0,u()}}}var uT=null;function bC(){return uT}var gT=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"]]),fT=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."]]),Ig=t=>fT.get(t)??"Conversation history is unavailable right now.";function mT(t){if(t instanceof ls)return t;if(t instanceof Oe){let e=gT.get(t.code)??"unavailable";return new ls(e,Ig(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new ls("unavailable",Ig("unavailable"))}function vC(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},s=c=>{if(!n.includes(c))throw new ls("unsupported_scope",Ig("unsupported_scope"))},i=async(c,d)=>{s(c);try{return await d()}catch(u){throw mT(u)}},l=c=>{let d=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){d||(d=!0,c.commit(),await t.onActivationCommitted(c.session))},discard(){d||(d=!0,c.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(c){return e().subscribeHistoryIdentityStatus(c)},subscribeAvailability(c){return e().subscribeHistoryAvailability(c)},async list(c){return i(c.context.scope,async()=>{let d=await e().listConversations({...c.cursor?{cursor:c.cursor}:{},...c.limit!==void 0?{limit:c.limit}:{},...c.targetId?{targetId:c.targetId}:{},scope:c.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(c,d){return i(d.context.scope,async()=>{let u=await e().getConversation(c,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),g=Uy(u.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:u.summary,messages:wa([],g),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(c,d){return i(d.context.scope,async()=>l(await e().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await e().prepareNewConversationSession()))},async delete(c,d){await i(d.context.scope,()=>e().deleteConversation(c,{scope:d.context.scope}))},async deleteAll(c){return i(c.context.scope,()=>e().deleteAllConversations({...c.targetId!==void 0?{targetId:c.targetId}:{},scope:c.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var hT="button:not([disabled])";function md(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,s=`persona-history-confirm-desc-${n}`,i=G("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),l=G("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),c=G("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":s},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"}},G("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),G("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:s},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),G("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},i,l));for(let u of[i,l])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";i.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",i.style.background="transparent",i.style.color="inherit",l.style.border="none",l.style.background="var(--persona-danger, #b42318)",l.style.color="var(--persona-danger-fg, #ffffff)";let d=G("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))"}},c);return new Promise(u=>{let g=!1,m=h=>{g||(g=!0,d.removeEventListener("keydown",v,!0),d.remove(),e?.focus(),u(h))};function v(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let T=Array.from(c.querySelectorAll(hT));if(T.length===0)return;let M=T[0],E=T[T.length-1],I=document.activeElement;h.shiftKey&&(I===M||!c.contains(I))?(h.preventDefault(),E.focus()):!h.shiftKey&&I===E&&(h.preventDefault(),M.focus())}d.addEventListener("keydown",v,!0),d.addEventListener("pointerdown",h=>{h.target===d&&m(!1)}),i.addEventListener("click",()=>m(!1)),l.addEventListener("click",()=>m(!0)),t.host.appendChild(d),i.focus()})}import{parse as RH,STR as WH,OBJ as BH}from"partial-json";function CC(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=Xo.get(t.component);if(!i){if(hg.includes(t.component)){ud().catch(()=>{});let c=k("div","persona-w-full");return c.setAttribute("data-persona-artifact-pending","true"),c}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let l={message:o,config:n,updateProps:c=>{s&&s(c)}};try{return i(t.props,l)}catch(c){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,c),null}}function wC(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Lg(t){let e=wC(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function SC(t){let e=wC(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var yT=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function xC(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:i="Share your thoughts (optional)...",submitText:l="Submit",skipText:c="Skip",showComment:d=!0,ratingLabels:u=yT}=t,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let m=null,v=document.createElement("div");v.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=o,h.appendChild(T);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,h.appendChild(M),v.appendChild(h);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let I=[];for(let w=1;w<=5;w++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-star-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${u[w-1]}`),O.title=u[w-1],O.dataset.rating=String(w),O.innerHTML=`
|
|
31
31
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
32
32
|
<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>
|
|
33
33
|
</svg>
|
|
34
|
-
`,D.addEventListener("click",()=>{m=w,O.forEach((K,ie)=>{let Z=ie<w;K.classList.toggle("selected",Z),K.setAttribute("aria-checked",ie===w-1?"true":"false")})}),O.push(D),M.appendChild(D)}b.appendChild(M);let I=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=i,I.rows=3,I.setAttribute("aria-label","Additional comments"),w.appendChild(I),b.appendChild(w)}let z=document.createElement("div");z.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=c,A.addEventListener("click",()=>{n?.(),g.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=l,H.addEventListener("click",async()=>{if(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let w=I?.value.trim()||void 0;await e(m,w),g.remove()}catch(w){H.disabled=!1,H.textContent=l,console.error("[CSAT Feedback] Failed to submit:",w)}}),z.appendChild(A),z.appendChild(H),b.appendChild(z),g.appendChild(b),g}function AC(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:i="What could we do better? (optional)...",submitText:l="Submit",skipText:c="Skip",showComment:d=!0,lowLabel:u="Not likely",highLabel:g="Very likely"}=t,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 b=null,h=document.createElement("div");h.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=o,x.appendChild(T);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,x.appendChild(M),h.appendChild(x);let O=document.createElement("div");O.className="persona-feedback-rating persona-feedback-rating-nps",O.setAttribute("role","radiogroup"),O.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let z=document.createElement("span");z.className="persona-feedback-label-low",z.textContent=u;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=g,I.appendChild(z),I.appendChild(A);let H=document.createElement("div");H.className="persona-feedback-numbers";let w=[];for(let S=0;S<=10;S++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-number-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`Rating ${S} out of 10`),W.textContent=String(S),W.dataset.rating=String(S),S<=6?W.classList.add("persona-feedback-detractor"):S<=8?W.classList.add("persona-feedback-passive"):W.classList.add("persona-feedback-promoter"),W.addEventListener("click",()=>{b=S,w.forEach((R,L)=>{R.classList.toggle("selected",L===S),R.setAttribute("aria-checked",L===S?"true":"false")})}),w.push(W),H.appendChild(W)}O.appendChild(I),O.appendChild(H),h.appendChild(O);let D=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",D=document.createElement("textarea"),D.className="persona-feedback-comment",D.placeholder=i,D.rows=3,D.setAttribute("aria-label","Additional comments"),S.appendChild(D),h.appendChild(S)}let K=document.createElement("div");K.className="persona-feedback-actions";let ie=document.createElement("button");ie.type="button",ie.className="persona-feedback-btn persona-feedback-btn-skip",ie.textContent=c,ie.addEventListener("click",()=>{n?.(),m.remove()});let Z=document.createElement("button");return Z.type="button",Z.className="persona-feedback-btn persona-feedback-btn-submit",Z.textContent=l,Z.addEventListener("click",async()=>{if(b===null){H.classList.add("persona-feedback-shake"),setTimeout(()=>H.classList.remove("persona-feedback-shake"),500);return}Z.disabled=!0,Z.textContent="Submitting...";try{let S=D?.value.trim()||void 0;await e(b,S),m.remove()}catch(S){Z.disabled=!1,Z.textContent=l,console.error("[NPS Feedback] Failed to submit:",S)}}),K.appendChild(ie),K.appendChild(Z),h.appendChild(K),m.appendChild(h),m}var Ci="persona-chat-history",CT=30*1e3,wT=641,wi="data-persona-composer-reason",ST={"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 xT(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let s=o.getAsFile();if(!s)continue;if(s.name){e.push(s);continue}let i=ST[s.type]??"png";e.push(new File([s],`clipboard-image-${Date.now()}.${i}`,{type:s.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function hd(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function AT(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function MT(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Hg=t=>!t||typeof t!="object"?{}:{...t},kC=t=>t.map(e=>({...e,streaming:!1})),PC=(t,e,n)=>{let o=t?.markdown?Mh(t.markdown):null,s=Eh(t?.sanitize);t?.postprocessMessage&&s&&t?.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 i=!1,l=c=>{let d=c.text??"",u=c.message.rawContent??null;if(e){let b=e.process({text:d,raw:u??d,message:c.message,streaming:c.streaming});b!==null&&(d=b.text,b.persist||(c.message.__skipPersist=!0),b.resubmit&&!c.streaming&&n&&n())}let g=Ys()!==null,m;if(t?.postprocessMessage){let b=t.postprocessMessage({...c,text:d,raw:u??c.text??""});m=s?s(b):b}else if(o){let b=c.streaming?ly(d):d,h=o(b);m=s&&g?s(h):h}else m=ic(d);return m};return c=>{try{return l(c)}catch(d){return i||(i=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",d)),ic(c.text??"")}}};function IC(t){let e=k("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",s=t?.iconColor??"rgba(59, 130, 246, 0.6)",i=t?.iconStrokeWidth??.5,l=ge(n,o,s,i);if(l&&e.appendChild(l),t?.label){let c=k("span","persona-drop-overlay-label");c.textContent=t.label,e.appendChild(c)}return e}var ET=(t,e)=>{let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];n[o]=i?{...i,...s}:s}return n},TT=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:ET(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),LC=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=Hc(e),s=()=>{pb({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};s();let i=o.features;o=wg(o);let l=Ag.getForInstance(o.plugins),c=lv(t),d=[],u=!1,g=qv(()=>o),m=null,b=null,h=null,x=!1,T=null,M=r=>{m=r,r.initApprovalUi({webMcpToolTitle:ac});let a=r.createBuiltInApprovalPlugin();b=a.plugin,h=a.teardown},O=()=>{if(m)return m;let r=Gv();return r?(M(r),r):(Kv().then(a=>{x||m||(M(a),T?.())}).catch(()=>{}),null)},I=!1,z=!1,A=null,H=(r,a,p,f)=>{if(!r.querySelector("[data-tv-form]"))return;let y=iC();if(y){y.enhanceWithForms(r,a,p,f);return}sC().then(()=>{I||z||!A||(z=!0,A())}).catch(()=>{})};o.components&&Xo.registerAll(o.components);let w=dC(),K=o.persistState===!1?null:o.storageAdapter??uC(),ie=!!o.clientToken&&typeof o.reconnectStream!="function",Z={},S=null,W,R=new Promise(r=>{W=r}),L,J=!1,U=r=>{if(o.onStateLoaded)try{let a=o.onStateLoaded(r);if(a&&typeof a=="object"&&"state"in a){let{state:p,open:f}=a;return f&&(J=!0),p}return a}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}return r};if(K?.load)try{let r=K.load();if(r&&typeof r.then=="function")S=r.then(a=>U(a??{messages:[],metadata:{}}));else{let p=U(r??{messages:[],metadata:{}});p.metadata&&(Z=Hg(p.metadata)),p.messages?.length&&(o={...o,initialMessages:p.messages}),p.artifacts?.length&&(o={...o,initialArtifacts:p.artifacts,initialSelectedArtifactId:p.selectedArtifactId??null}),L=p.draft}}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",r)}else if(o.onStateLoaded)try{let r=U({messages:[],metadata:{}});r.messages?.length&&(o={...o,initialMessages:r.messages})}catch(r){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",r)}S||W();let ae=()=>Z,re=r=>{Z=r({...Z})??{},Ls()},ue=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Eg],Ee=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[qa.message,qa.messageAndClick],he=Tg({parsers:ue,handlers:Ee,getSessionMetadata:ae,updateSessionMetadata:re,emit:w.emit,documentRef:typeof document<"u"?document:null});he.syncFromMetadata();let ce=o.launcher?.enabled??!0,at=o.launcher?.autoExpand??!1,ye=o.autoFocusInput??!1,N=at,Te=ce,Ue=o.layout?.header?.layout,qt=!1,Le=()=>Ba(o),Fe=()=>ce||Le(),ve=Le()?!1:ce?at:!0,ln=!1,Jn=null,ko=()=>{ln=!0,Jn&&clearTimeout(Jn),Jn=setTimeout(()=>{ln&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ln=!1)},1e4)},vt=PC(o,he,ko),Po=o.features?.showReasoning??!0,j=o.features?.showToolCalls??!0,C=o.features?.showEventStreamToggle??!1,_=o.features?.scrollToBottom??{},V=o.features?.scrollBehavior??{},Q=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",me=`${Q()}event-stream`,Me=null,Pe=o.features?.eventStream?.maxEvents??2e3,Re=null,ot=null,Ve=null,$e=!1,gt=null,zt=!1,kt=null,tn=0,hn=(r,a)=>{Re?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:r,timestamp:Date.now(),payload:JSON.stringify(a)})},bd=(r,a)=>{ot?.processEvent(r,a),Re?hn(r,a):Ve&&(Ve.length>=Pe&&Ve.shift(),Ve.push({type:r,payload:a}))},ja=()=>{Re||!C||(Ve??(Ve=[]),mg().then(r=>{if($e||Re||!C)return;Me=new r.EventStreamStore(me),Re=new r.EventStreamBuffer(Pe,Me),ot=ot??new r.ThroughputTracker,Me.open().then(()=>Re?.restore()).catch(p=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",p)});let a=Ve??[];Ve=null;for(let p of a)ot?.processEvent(p.type,p.payload),hn(p.type,p.payload)}).catch(()=>{}))};C&&ja();let Ct=!1,Ht=null,vd=()=>{},Io=()=>{},Ng=()=>{},Fg=()=>{},Cd=()=>{},qC=()=>zt||Ct&&Ht==="panel",ys={onCopy:r=>{w.emit("message:copy",r),E?.isClientTokenMode()&&E.submitMessageFeedback(r.id,"copy").catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",a)}),o.messageActions?.onCopy?.(r)},onFeedback:r=>{w.emit("message:feedback",r),E?.isClientTokenMode()&&E.submitMessageFeedback(r.messageId,r.type).catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",a)}),o.messageActions?.onFeedback?.(r)}},bs=o.statusIndicator??{},Ug=r=>r==="idle"?bs.idleText??Nt.idle:r==="connecting"?bs.connectingText??Nt.connecting:r==="connected"?bs.connectedText??Nt.connected:r==="error"?bs.errorText??Nt.error:r==="paused"?bs.pausedText??Nt.paused:r==="resuming"?bs.resumingText??Nt.resuming:Nt[r];function Va(r,a,p,f){if(!r.hasAttribute(wi))if(f==="idle"&&p.idleLink){r.textContent="";let y=document.createElement("a");y.href=p.idleLink,y.target="_blank",y.rel="noopener noreferrer",y.textContent=a,y.style.color="inherit",y.style.textDecoration="none",r.appendChild(y)}else r.textContent=a}let Pn=$v({config:o,showClose:Fe()}),{wrapper:Ke,panel:we,pillRoot:jt}=Pn.shell,Be=Pn.panelElements,{container:de,body:te,messagesWrapper:ke,starterSuggestions:wd,transcriptSuggestions:xi,suggestions:or,textarea:le,sendButton:xe,composerForm:Zn,statusText:rt,welcomeHost:yn,welcomeIconHolder:zC,greetingHost:In,introKicker:jC,introTitle:VC,introSubtitle:KC,closeButton:_e,iconHolder:wt,headerTitle:rr,headerSubtitle:Ir,header:Ae,footer:Ie,actionsRow:GC}=Be,Sd=Be.leftActions,Ka=Be.rightActions,po=Be.sendButtonWrapper,$g=Be.setSendButtonMode,ne=Be.micButton,Ln=Be.micButtonWrapper,bt=Be.attachmentButton,bn=Be.attachmentButtonWrapper,ft=Be.attachmentInput,vn=Be.attachmentPreviewsContainer;de.classList.add("persona-relative"),te.classList.add("persona-relative");let QC=12,Ai=()=>_.label??"",XC=()=>_.iconName??"arrow-down",YC=()=>_.enabled!==!1,Hn=()=>V.mode??"anchor-top",sr=()=>Hn()==="follow"||Hn()==="anchor-top"&&Wi,Mi=()=>V.anchorTopOffset??16,JC=()=>V.restorePosition??"bottom",qg=()=>V.pauseOnInteraction===!0,zg=()=>V.showActivityWhilePinned!==!1,jg=()=>V.announce===!0,xd=()=>V.scrollbar??"on-scroll",Rt=k("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");Rt.type="button",Rt.style.display="none",Rt.setAttribute("data-persona-scroll-to-bottom","true");let Ei=k("span","persona-flex persona-items-center"),Ad=k("span",""),Lr=k("span","");Lr.setAttribute("data-persona-scroll-to-bottom-count",""),Lr.style.display="none",Rt.append(Ei,Ad,Lr),de.appendChild(Rt);let Un=k("div","persona-stream-anchor-spacer");Un.setAttribute("aria-hidden","true"),Un.setAttribute("data-persona-anchor-spacer",""),Un.style.flexShrink="0",Un.style.pointerEvents="none",Un.style.height="0px",Un.style.display="none",te.appendChild(Un);let Lo=k("div","persona-sr-only");Lo.setAttribute("aria-live","polite"),Lo.setAttribute("aria-atomic","true"),Lo.setAttribute("role","status"),Lo.setAttribute("data-persona-live-region",""),Object.assign(Lo.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(Lo);let Ti=null,Ga=null,Qa=r=>{!jg()||!r||(Ga=r,Ti===null&&(Ti=setTimeout(()=>{Ti=null,Ga&&jg()&&(Lo.textContent=Ga),Ga=null},400)))},Xa="empty",Ya=0,Md=()=>Ya||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Hr=()=>{let a=Ie.style.display==="none"?0:Ie.offsetHeight;Rt.style.bottom=`${a+Md()+QC}px`};Hr();let Ed=()=>{xs||(Ie.style.marginBottom=Ya>0?`${Ya}px`:"")},Ja=()=>{let r=qu(o,Le()),a=Zo(o),f=Ie.style.display==="none"?0:Ie.offsetHeight,y=a.anchor==="center"&&Xa==="empty"?La(a.anchorComposerTop)??La("44%"):null,v=y===null||Le()?0:sv({columnHeight:de.clientHeight,footerHeight:f,fraction:y});t.style.setProperty("--persona-composer-overlay-height",`${f}px`),t.style.setProperty("--persona-composer-lift",`${r==="overlay"?v:0}px`),Ya=r==="block"?v:0,Ed(),Hr()},Vg=()=>{let r=!!Ai();Rt.setAttribute("aria-label",Ai()||"Jump to latest"),Rt.title=Ai(),Rt.setAttribute("data-persona-scroll-to-bottom-has-label",r?"true":"false"),Ei.innerHTML="";let a=ge(XC(),"14px","currentColor",2);a?(Ei.appendChild(a),Ei.style.display=""):Ei.style.display="none",Ad.textContent=Ai(),Ad.style.display=r?"":"none"};Vg();let Ye=null,Pt=null,be=sb(),ZC=r=>{try{de.dispatchEvent(new CustomEvent("persona:composer:state",{detail:r,bubbles:!0,composed:!0}))}catch{}};be.subscribe(ZC);let uo=()=>{be.setText(le?.value??"")},Rr=()=>{be.setMentionRefs(Pt?.getMentionRefs()??[])},ew=r=>({id:r.id,name:r.file.name,mimeType:r.file.type,size:r.file.size,status:r.status,progress:r.progress,error:r.error}),Kg=r=>{let a=Object.freeze(r.map(ew));be.setAttachments(a);try{o.attachments?.onChange?.(a)}catch(p){console.error("[AgentWidget] attachments.onChange failed:",p)}Zd()};be.setSelectedModelId(o.composer?.selectedModelId);let ki=()=>o.composer?.modes??[],vs=()=>Rb(ki(),o.composer?.modeGroups);{let r=qc(o.composer?.defaultActiveModeIds??[],ki());r.length&&be.setActiveModeIds(r)}function Gg(r){if(be.getState().selectedModelId!==r){be.setSelectedModelId(r),ir?.repaint();try{o.composer?.onModelChange?.(r)}catch(a){console.error("[AgentWidget] composer.onModelChange failed:",a)}}}function Za(r){be.setActiveModeIds(r),Ho?.render(r,vs()),Cs.forEach(a=>a.repaint()),fo?.resolve(),Al(),eo()}function Td(r){Za(Wb(be.getState().activeModeIds,r,ki(),o.composer?.modeGroups))}let ir=null,kd=null,Ho=null,Cs=new Map,ar=null;function go(r){be.setQuote(r),ar?.render(be.getState().quote),eo(),Uf()}let Qg=!1;function Pd(){let r=o.composer?.streamingSubmitBehavior??"block";return r!=="interrupt"?r:o.clientToken?"interrupt":(!Qg&&o.debug===!0&&(Qg=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let lr=null;function ws(r){be.setPendingSubmission(r),lr?.render(be.getState().pendingSubmission),eo()}let tw=r=>{let a=Cs.get(r);if(a)return a;let p=Ob({groupId:r,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===r),getModes:()=>ki().filter(f=>f.groupId===r),getActiveIds:()=>be.getState().activeModeIds,onSelect:f=>Td(f)});return Cs.set(r,p),p},nw=()=>{let r=[],a=be.getState().activeModeIds,p=new Set;if(ki().forEach((f,y)=>{if($c(f.groupId,o.composer?.modeGroups)){let v=f.groupId;if(p.has(v))return;p.add(v);let B=tw(v);B.action.order=_u(y),B.action.label=o.composer?.modeGroups?.find($=>$.id===v)?.label??v,r.push(B.action);return}r.push({id:Lb(f.id),kind:"button",placement:"start",order:_u(y),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:a.includes(f.id),onSelect:()=>Td(f.id)})}),o.composer?.models?.length&&!l.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!ir||kd!==f)&&(kd=f,ir=Pb({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>be.getState().selectedModelId,onSelect:y=>Gg(y),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),r.push(ir.action)}return r},Id=null,Xg=l.find(r=>r.renderHeader);if(Xg?.renderHeader){let r=Xg.renderHeader({config:o,defaultRenderer:()=>{let a=fs({config:o,showClose:Fe()});return Oa(de,a,o),a.header},onClose:()=>pt(!1,"user")});if(r){let a=Ae;a&&(a.replaceWith(r),Ae=r,Pn.header.element=r)}}let Yg=()=>{gt&&(te.style.display="none",Ie.parentNode?.insertBefore(gt.element,Ie),gt.update())},Ld=()=>{if(!Re){ja();return}if(zt=!0,gt?Yg():mg().then(a=>{gt||!zt||!Re||(gt=a.createEventStreamView({buffer:Re,getFullHistory:()=>Re.getAllFromStore(),onClose:()=>Ss(),config:o,plugins:l,getThroughput:()=>ot?.getMetric()??{status:"idle"},renderIconByName:ge}),Yg())}).catch(()=>{Ss()}),Ze){Ze.style.boxShadow=`inset 0 0 0 1.5px ${gn.actionIconColor}`;let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(p=>p&&Ze.classList.add(p))}let r=()=>{if(!zt)return;let a=Date.now();a-tn>=200&&(gt?.update(),tn=a),kt=requestAnimationFrame(r)};tn=0,kt=requestAnimationFrame(r),Ut(),w.emit("eventStream:opened",{timestamp:Date.now()})},Ss=()=>{if(zt){if(zt=!1,gt&>.element.remove(),te.style.display="",Ze){Ze.style.boxShadow="";let r=o.features?.eventStream?.classNames?.toggleButtonActive;r&&r.split(/\s+/).forEach(a=>a&&Ze.classList.remove(a))}kt!==null&&(cancelAnimationFrame(kt),kt=null),Ut(),w.emit("eventStream:closed",{timestamp:Date.now()})}},Ze=null;if(C){let r=o.features?.eventStream?.classNames,a="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"+(r?.toggleButton?" "+r.toggleButton:"");Ze=k("button",a),Ze.style.width="28px",Ze.style.height="28px",Ze.style.color=gn.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let p=en(MC,"18px","currentColor",1.5);p&&Ze.appendChild(p);let f=Be.clearChatButtonWrapper,y=Be.closeButtonWrapper,v=f||y;v&&v.parentNode===Ae?Ae.insertBefore(Ze,v):Ae.appendChild(Ze),Ze.addEventListener("click",()=>{zt?Ss():Ld()})}let Jg=r=>{let a=o.attachments;if(!a?.enabled)return;let p=r.querySelector("[data-persona-composer-attachment-previews]")??r.querySelector(".persona-attachment-previews");if(!p){p=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),p.setAttribute("data-persona-composer-attachment-previews",""),p.style.display="none";let y=r.querySelector("[data-persona-composer-form]");y?.parentNode?y.parentNode.insertBefore(p,y):r.insertBefore(p,r.firstChild)}if(!(r.querySelector("[data-persona-composer-attachment-input]")??r.querySelector('input[type="file"]'))){let y=k("input");y.type="file",y.setAttribute("data-persona-composer-attachment-input",""),y.accept=(a.allowedTypes??Yo).join(","),y.multiple=(a.maxFiles??4)>1,y.style.display="none",y.setAttribute("aria-label",a.buttonTooltipText??"Attach files"),r.appendChild(y)}},xs=!1,Zg=r=>{let a=l.find(y=>y.renderComposer);if(!a?.renderComposer)return null;let p=o.composer,f=u?E.isStreaming():!1;return a.renderComposer({config:o,defaultRenderer:r,requestRender:()=>gh(),storage:g(a.id),onSubmit:y=>{!E||E.isStreaming()||Yl(y.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{bo()||ft?.click()},models:p?.models,selectedModelId:be.getState().selectedModelId??p?.selectedModelId,onModelChange:y=>Gg(y),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Id?.()}:void 0})},ef=Zg(()=>_a({config:o}).footer);ef&&(Pn.replaceComposer(ef),Ie=Pn.composer.footer,xs=!0);let et=null,ow=r=>{Zn=r.form,le=r.input,po=r.sendButton?r.sendButton.parentElement:null,r.sendButton&&(xe=r.sendButton),r.micButton&&(ne=r.micButton,Ln=r.micButton.parentElement),r.found.status&&(rt=r.found.status),r.found.suggestions&&(or=r.found.suggestions),r.attachmentButton&&(bt=r.attachmentButton,bn=r.attachmentButton.parentElement),ft=r.attachmentInput??null,vn=r.attachmentPreviews??null,r.found.actionsRow&&(GC=r.found.actionsRow),Sd=r.found.actionsStart,Ka=r.found.actionsEnd};function Hd(){let r=le;if(!r)return;let a=o.composer?.inputAttributes,p=!a?.ariaLabel&&!(r instanceof HTMLTextAreaElement)?r.getAttribute("aria-label"):null;Bc(r,a),p&&r.setAttribute("aria-label",p),Wc(r,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ka(r)}),yb(r,Rc(o.composer?.maxLines,Le()?5:3))}let tf=r=>{et=ab(r,{debug:o.debug===!0}),et&&ow(et),Hd()};Jg(Ie),tf(Ie),uo();let Pi=kr(o,Le());Pi&&(ke.style.maxWidth=Pi,ke.style.marginLeft="auto",ke.style.marginRight="auto",ke.style.width="100%",In.style.maxWidth=Pi,In.style.marginLeft="auto",In.style.marginRight="auto",In.style.width="100%",wd.style.maxWidth=Pi,xi.style.maxWidth=Pi,xi.style.marginLeft="auto",xi.style.marginRight="auto",xi.style.width="100%");let nf=()=>{let r=kr(o,Le());if(!(!r||Le()))for(let a of[Zn,or,vn,rt])a&&(a.style.maxWidth=r,a.style.marginLeft="auto",a.style.marginRight="auto",a.style.width="100%")};nf();let of=()=>{!o.attachments?.enabled||!ft||!vn||(Ye?Ye.remountPreviews(vn):(Ye=Ma.fromConfig(o.attachments,Kg),Ye.setPreviewsContainer(vn)),et?.addListener(ft,"change",r=>{let a=r.target;Ye?.handleFileSelect(a.files),a.value=""}),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(IC(o.attachments.dropOverlay)))};of();let rw=()=>Pt?.prefetch(),rf=()=>{if(!o.contextMentions?.enabled||!le)return;let r=et?.header??null,a=r?tu(r):void 0;if(Pt=Jb({config:o,textarea:le,anchor:Zn??le,getMessages:()=>E.getMessages(),liveRegionHost:de,chipRow:a}),Pt&&!a){let p=le;p.parentElement?.insertBefore(Pt.contextRow,p)}};rf();let fo=null,sw={getState:()=>be.getState(),getValue:()=>le?.value??"",setValue:r=>{le&&(le.value=r,le.dispatchEvent(new Event("input",{bubbles:!0})),uo())},submit:()=>{$h(et?.form??null)},openAttachmentPicker:()=>{bo()||ft?.click()},toggleVoice:()=>{Id?.()},requestRender:()=>fo?.resolve()},iw=()=>{let r=[];return(Pt?.affordanceButtons??[]).forEach((p,f)=>{r.push({id:`core:mention-${f}`,placement:"start",order:Eo.mention+f,element:p,managed:!0})}),bn&&r.push({id:"core:attachment",placement:"start",order:Eo.attachment,element:bn}),Ln&&r.push({id:"core:mic",placement:"end",order:Eo.mic,element:Ln}),po&&r.push({id:"core:send",placement:"end",order:Eo.send,element:po}),r},sf=()=>{fo?.destroy(),fo=Eb({getBindings:()=>et,collect:()=>({builtIns:iw(),configActions:[...nw(),...o.composer?.actions??[]],plugins:l,contributionContext:{config:o,getState:()=>be.getState(),requestRender:()=>fo?.resolve()},debug:o.debug===!0}),actionContext:sw,getState:()=>be.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(r,a)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${a.actionId}" failed:`,r)}}),fo.resolve()};sf();let Rd=()=>{if(Ho?.destroy(),Ho=null,!vs().length)return;let r=et?.header;r&&(Ho=Ib({row:tu(r),onRemove:a=>Td(a),initialIds:be.getState().activeModeIds}),Ho.render(be.getState().activeModeIds,vs()))};Rd();let af=()=>{ar?.destroy(),ar=null,lr?.destroy(),lr=null;let r=et?.header;r&&(ar=_b({onDismiss:()=>go(void 0)}),r.appendChild(ar.element),ar.render(be.getState().quote),Pd()==="defer-one"&&(lr=Nb({onEdit:()=>WS(),onRemove:()=>ws(void 0)}),r.appendChild(lr.element),lr.render(be.getState().pendingSubmission)))};af();let Wd=jb(),aw=()=>{let r=et?.header?.querySelector(Uh);if(r)return r.childElementCount>0;let a=be.getState();return a.mentionRefs.length>0||qc(a.activeModeIds,vs()).length>0},lf=()=>!1;function eo(){let r=be.getState(),a=Wd.observe(Vb(le),r.text);Ie.toggleAttribute("data-persona-composer-compact",zb({text:r.text,wrapped:a,hasAttachments:r.attachments.length>0,hasChips:aw(),hasQuote:r.quote!==void 0,hasPendingSubmission:r.pendingSubmission!==void 0,dictationActive:lf()}))}function cf(){o.composer?.layout==="single-row"&&!Le()?Ie.setAttribute("data-persona-composer-layout","single-row"):Ie.removeAttribute("data-persona-composer-layout")}cf(),be.subscribe(()=>{fo?.sync(),Zd(),Sl(),eo(),Uf()}),Sl();let df=!1,lw=r=>{if(df||o.debug!==!0)return;let a=["messages","composer"].filter(p=>r[p]);a.length&&(df=!0,console.warn(`[persona] layout.slots.${a.join(" and layout.slots.")} ${a.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 r=o.layout?.slots??{};lw(r);let a=f=>{switch(f){case"body-top":return te.querySelector("[data-persona-intro-card]");case"messages":return ke;case"footer-top":return or;case"composer":return Zn;case"footer-bottom":return rt;default:return null}},p=(f,y)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Ae.insertBefore(y,Ae.firstChild);else if(f==="header-right")Ae.appendChild(y);else{let v=Ae.querySelector(".persona-flex-col");v?v.parentNode?.insertBefore(y,v.nextSibling):Ae.appendChild(y)}break;case"body-top":{let v=te.querySelector("[data-persona-intro-card]");v?v.replaceWith(y):te.insertBefore(y,te.firstChild);break}case"body-bottom":te.appendChild(y);break;case"footer-top":or.replaceWith(y);break;case"footer-bottom":rt.replaceWith(y);break;default:break}};for(let[f,y]of Object.entries(r))if(y)try{let v=y({config:o,defaultContent:()=>a(f)});v&&p(f,v)}catch(v){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${f}":`,v)}})();let pf=r=>{let p=r.target.closest('button[data-expand-header="true"]');if(!p)return;let f=p.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!f)return;let y=f.getAttribute("data-message-id");if(!y)return;let v=p.getAttribute("data-bubble-type");if(v==="reasoning")mi.has(y)?mi.delete(y):mi.add(y),zv(y,f);else if(v==="tool")hi.has(y)?hi.delete(y):hi.add(y),Vv(y,f,o);else if(v==="approval"&&m){let $=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",F=m.approvalDetailsExpansionState.get(y)??$;m.approvalDetailsExpansionState.set(y,!F),m.updateApprovalDetailsUI(y,f,o)}Wt.delete(y)};ke.addEventListener("pointerdown",r=>{r.target.closest('button[data-expand-header="true"]')&&(r.preventDefault(),pf(r))}),ke.addEventListener("keydown",r=>{let a=r.target;(r.key==="Enter"||r.key===" ")&&a.closest('button[data-expand-header="true"]')&&(r.preventDefault(),pf(r))}),ke.addEventListener("copy",r=>{let{clipboardData:a}=r;if(!a)return;let p=ke.getRootNode(),f=typeof p.getSelection=="function"?p.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let y=f.toString(),v=cv(y);!v||v===y||(a.setData("text/plain",v),r.preventDefault())});let Bd=new Map,uf=null,gf="idle",cw={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},dw=(r,a)=>{let{icon:p,label:f}=cw[a];r.setAttribute("aria-label",f),r.title=f,r.setAttribute("aria-pressed",a==="idle"?"false":"true"),r.classList.toggle("persona-message-action-active",a!=="idle"),r.classList.toggle("persona-message-action-loading",a==="loading");let y=ge(p,14,"currentColor",2);y&&(r.innerHTML="",r.appendChild(y))},ff=()=>{ke.querySelectorAll('[data-action="read-aloud"]').forEach(a=>{let f=a.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;dw(a,f&&f===uf?gf:"idle")})};ke.addEventListener("click",r=>{let p=r.target.closest(".persona-message-action-btn[data-action]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.closest("[data-actions-for]");if(!f)return;let y=f.getAttribute("data-actions-for");if(!y)return;let v=p.getAttribute("data-action");if(v==="copy"){let $=E.getMessages().find(F=>F.id===y);if($&&ys.onCopy){let F=$.content||"";navigator.clipboard.writeText(F).then(()=>{p.classList.add("persona-message-action-success");let q=en(EC,14,"currentColor",2);q&&(p.innerHTML="",p.appendChild(q)),setTimeout(()=>{p.classList.remove("persona-message-action-success");let X=en(TC,14,"currentColor",2);X&&(p.innerHTML="",p.appendChild(X))},2e3)}).catch(q=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",q)}),ys.onCopy($)}}else if(v==="read-aloud")E.toggleReadAloud(y);else if(v==="upvote"||v==="downvote"){let $=(Bd.get(y)??null)===v,F=v==="upvote"?"thumbs-up":"thumbs-down";if($){Bd.delete(y),p.classList.remove("persona-message-action-active");let q=ge(F,14,"currentColor",2);q&&(p.innerHTML="",p.appendChild(q))}else{let q=v==="upvote"?"downvote":"upvote",X=f.querySelector(`[data-action="${q}"]`);if(X){X.classList.remove("persona-message-action-active");let ut=ge(q==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ut&&(X.innerHTML="",X.appendChild(ut))}Bd.set(y,v),p.classList.add("persona-message-action-active");let oe=ge(F,14,"currentColor",2);oe&&(oe.setAttribute("fill","currentColor"),p.innerHTML="",p.appendChild(oe)),p.classList.remove("persona-message-action-pop"),p.offsetWidth,p.classList.add("persona-message-action-pop");let Xe=E.getMessages().find(ct=>ct.id===y);Xe&&ys.onFeedback&&ys.onFeedback({type:v,messageId:Xe.id,message:Xe})}}else if(v==="regenerate")el?.regenerate(y);else if(v==="edit")el?.edit(y);else if(v==="quote")el?.quote(y);else if(v?.startsWith(td)){let B=v.slice(td.length),$=o.messageActions?.custom?.find(q=>q.id===B),F=E.getMessages().find(q=>q.id===y);if(!$||!F)return;try{$.onSelect(F)}catch(q){console.error(`[AgentWidget] messageActions.custom "${B}" onSelect failed:`,q)}}});let el=null;ke.addEventListener("click",r=>{let p=r.target.closest("button[data-approval-action]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.closest(".persona-approval-bubble");if(!f)return;let y=f.getAttribute("data-message-id");if(!y)return;let v=p.getAttribute("data-approval-action");if(!v)return;let B=v==="approve"?"approved":"denied",F=E.getMessages().find(X=>X.id===y);if(!F?.approval)return;let q=f.querySelector("[data-approval-buttons]");q&&q.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?E.resolveWebMcpApproval(y,B):E.resolveApproval(F.approval,B)});let qe=null,mf=!1,Ii=null,Wr=()=>{},Li="none",tl=null,$n={artifacts:[],selectedId:null},Ro=!1,to=!1,Hi=!1,As=!1,hf=()=>As||$n.artifacts.some(r=>Sr(o.features?.artifacts,r)==="panel"),nl=()=>$n.artifacts.length>0&&!Ro&&hf(),lt={current:null},Dd=(r,a)=>{let p=E.getArtifactById(a),f=p?.markdown,y=p?.title||"artifact",v=p?.file,B=p?.artifactType??"markdown";if(!f){let q=r.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(q){let oe=E.getMessages().find(pe=>pe.id===q);if(oe?.rawContent)try{let pe=JSON.parse(oe.rawContent);f=pe?.props?.markdown,y=pe?.props?.title||y,pe?.props?.file&&typeof pe.props.file=="object"&&(v=pe.props.file),!p&&typeof pe?.props?.artifactType=="string"&&(B=pe.props.artifactType)}catch{}}}return{markdown:f,title:y,file:v,artifactType:B}};ke.addEventListener("click",r=>{let p=r.target.closest("[data-download-artifact]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:v,title:B,file:$}=Dd(p,f);if(!v)return;let F=er();F&&F.triggerArtifactDownload(F.downloadInfoFor({title:B,markdown:v,file:$}))}),ke.addEventListener("click",r=>{let p=r.target.closest("[data-artifact-custom-action]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-artifact-custom-action");if(!f)return;let y=p.closest("[data-artifact-inline]"),v=y?null:p.closest("[data-open-artifact]"),B=y?y.getAttribute("data-artifact-inline"):v?.getAttribute("data-open-artifact")??null,F=(y?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ct=>ct.id===f);if(!F)return;let{markdown:q,title:X,file:oe,artifactType:pe}=Dd(p,B??""),Xe={artifactId:B,title:X,artifactType:pe,markdown:q,file:oe};try{Promise.resolve(F.onClick(Xe)).catch(()=>{})}catch{}}),ke.addEventListener("click",r=>{let p=r.target.closest("[data-copy-artifact]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-copy-artifact");if(!f)return;let y=E.getArtifactById(f),v=er();if(!v)return;let B="";if(y)B=v.artifactCopyText(y);else{let{markdown:$,file:F,artifactType:q}=Dd(p,f);q==="markdown"&&(B=v.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:$??"",...F?{file:F}:{}}))}B&&navigator.clipboard.writeText(B).then(()=>{let $=en(EC,16,"currentColor",2);$&&(p.replaceChildren($),setTimeout(()=>{let F=en(TC,16,"currentColor",2);F&&p.replaceChildren(F)},1500))}).catch(()=>{})}),ke.addEventListener("click",r=>{let p=r.target.closest("[data-expand-artifact-inline]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-expand-artifact-inline");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(Ro=!1,As=!0,to=!0,Hi=!0,E.selectArtifact(f),no())}),ke.addEventListener("click",r=>{let a=r.target;if(a.closest("[data-download-artifact]")||a.closest("[data-artifact-custom-action]"))return;let p=a.closest("[data-open-artifact]");if(!p)return;let f=p.getAttribute("data-open-artifact");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(r.preventDefault(),r.stopPropagation(),Ro=!1,As=!0,E.selectArtifact(f),no())}),ke.addEventListener("keydown",r=>{if(r.key!=="Enter"&&r.key!==" ")return;let a=r.target;!a.hasAttribute("data-open-artifact")&&!a.hasAttribute("data-expand-artifact-inline")||(r.preventDefault(),a.click())});let Ms=Be.composerOverlay,Es=(r,a,p)=>{let f=a.trim();if(!f||!lt.current)return;let y=r.getAttribute("data-tool-call-id")??"",v=p.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:y,answer:f,answers:p.structured,values:p.values??(p.source==="multi"?f.split(", "):[f]),isFreeText:v,source:p.source},bubbles:!0,composed:!0})),si(Ms,y);let B=lt.current.getMessages().find($=>$.toolCall?.id===y);B?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(B,p.structured??f):lt.current.sendMessage(f)},Br=r=>{let a=lt.current;if(!a)return;let p=r.getAttribute("data-tool-call-id")??"",f=a.getMessages().find(y=>y.toolCall?.id===p);f&&a.persistAskUserQuestionProgress(f,{answers:vc(r,f),currentIndex:Xn(r)})},yf=r=>Object.entries(r).map(([a,p])=>`${a}: ${Array.isArray(p)?p.join(", "):p}`).join(" | "),Od=r=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let a=Xn(r),p=ri(r);if(a>=p-1)return;let f=lt.current?.getMessages().find(y=>y.toolCall?.id===r.getAttribute("data-tool-call-id"));f&&(wc(r,f,o,a+1),Br(r))};Ms.addEventListener("click",r=>{let p=r.target.closest("[data-ask-user-action]");if(!p)return;let f=p.closest("[data-persona-ask-sheet-for]");if(!f)return;let y=p.getAttribute("data-ask-user-action");if(r.preventDefault(),r.stopPropagation(),y==="dismiss"){let v=f.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),si(Ms,v);let B=lt.current?.getMessages().find($=>$.toolCall?.id===v);B?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(B),lt.current?.resolveAskUserQuestion(B,"(dismissed)"));return}if(y==="pick"){let v=p.getAttribute("data-option-label");if(!v)return;let B=f.getAttribute("data-multi-select")==="true",$=xr(f);if($&&B){let F=ps(f)[Xn(f)],q=new Set(Array.isArray(F)?F:[]);q.has(v)?q.delete(v):q.add(v),Ar(f,Array.from(q)),Br(f);return}if($){Ar(f,v),Br(f),Od(f);return}if(B){let F=p.getAttribute("aria-pressed")==="true";p.setAttribute("aria-pressed",F?"false":"true"),p.classList.toggle("persona-ask-pill-selected",!F);let q=f.querySelector('[data-ask-user-action="submit-multi"]');q&&(q.disabled=uu(f).length===0);return}Es(f,v,{source:"pick",values:[v]});return}if(y==="submit-multi"){let v=uu(f);if(v.length===0)return;Es(f,v.join(", "),{source:"multi",values:v});return}if(y==="open-free-text"){let v=f.querySelector('[data-ask-free-text-row="true"]');v&&(v.classList.remove("persona-hidden"),v.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(y==="focus-free-text"){f.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let B=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!B.trim())return;if(xr(f)){Ar(f,B.trim()),Br(f),Od(f);return}Es(f,B,{source:"free-text"});return}if(y==="next"||y==="back"){if(!lt.current)return;let v=f.getAttribute("data-tool-call-id")??"",B=lt.current.getMessages().find(oe=>oe.toolCall?.id===v);if(!B)return;let F=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(F){let oe=ps(f)[Xn(f)];(typeof oe!="string"||oe!==F)&&Ar(f,F)}let q=y==="next"?1:-1,X=Xn(f)+q;wc(f,B,o,X),Br(f);return}if(y==="submit-all"){if(!lt.current)return;let v=f.getAttribute("data-tool-call-id")??"",B=lt.current.getMessages().find(oe=>oe.toolCall?.id===v);if(!B)return;let F=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";F&&Ar(f,F);let q=vc(f,B);lt.current.persistAskUserQuestionProgress(B,{answers:q,currentIndex:Xn(f)});let X=yf(q);Es(f,X||"(submitted)",{source:"submit-all",structured:q});return}if(y==="skip"){if(!lt.current)return;let v=f.getAttribute("data-tool-call-id")??"",B=lt.current.getMessages().find(pe=>pe.toolCall?.id===v);if(!B)return;let $=xr(f),F=Xn(f),q=ri(f),X=F>=q-1;if(!$){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),si(Ms,v),B.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(B),lt.current.resolveAskUserQuestion(B,"(dismissed)"));return}Ar(f,"");let oe=f.querySelector('[data-ask-free-text-input="true"]');if(oe&&(oe.value=""),X){let pe=vc(f,B),Xe=yf(pe);Es(f,Xe||"(skipped)",{source:"submit-all",structured:pe});return}wc(f,B,o,F+1),Br(f);return}}),Ms.addEventListener("keydown",r=>{if(r.key!=="Enter")return;let p=r.target;if(!p.matches?.('[data-ask-free-text-input="true"]'))return;let f=p.closest("[data-persona-ask-sheet-for]");if(!f)return;r.preventDefault();let y=p.value;if(y.trim()){if(xr(f)){Ar(f,y.trim()),Br(f),Od(f);return}Es(f,y,{source:"free-text"})}});let bf=r=>{if(!/^[1-9]$/.test(r.key)||r.metaKey||r.ctrlKey||r.altKey)return;let a=r.target;if(a?.tagName==="INPUT"||a?.tagName==="TEXTAREA"||a?.isContentEditable)return;let p=Ms.querySelector("[data-persona-ask-sheet-for]");if(!p||p.getAttribute("data-ask-layout")!=="rows"||p.getAttribute("data-multi-select")==="true")return;let f=Number(r.key),v=p.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[f-1];v&&(r.preventDefault(),v.click())};document.addEventListener("keydown",bf);let mo=null,mt=null,Ri=null,ol=null,rl=()=>{},vf=!1,sl="",il="";function _d(){ol?.(),ol=null}let pw=()=>{let r=Ns&&ts?.isConnected?ts:null,a=r?r.getBoundingClientRect().width:0;return a<=0?200:a+360},Cf=()=>{if(!mo||!mt)return;let r=t.classList.contains("persona-artifact-welded-split"),a=t.ownerDocument.defaultView??window,p=a.innerWidth<=640;if(!r||t.classList.contains("persona-artifact-narrow-host")||p){mt.style.removeProperty("position"),mt.style.removeProperty("left"),mt.style.removeProperty("top"),mt.style.removeProperty("bottom"),mt.style.removeProperty("width"),mt.style.removeProperty("z-index");return}let f=mo.firstElementChild;if(!f||f===mt)return;let y=10;mt.style.position="absolute",mt.style.top="0",mt.style.bottom="0",mt.style.width=`${y}px`,mt.style.zIndex="5";let v=Sg(mo,a),B=f.offsetWidth+v/2-y/2;mt.style.left=`${Math.max(0,B)}px`},al=()=>{},uw=()=>{let r=t.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,p=o.launcher?.mobileBreakpoint??640;return!a||r.innerWidth>p?!1:ce||Lt(o)},ll=()=>!mn(o)||!nl()||t.classList.contains("persona-artifact-narrow-host")||uw()||(t.ownerDocument.defaultView??window).innerWidth<wT?"none":vg(o)?"detached":"welded",no=()=>{if(!qe||!mn(o))return;Ua(t,o),$a(t,o),al();let r=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,a=we.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",a>0&&a<=r);let p=nl();qe.setVisible(p),qe.update($n),Ro?(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),to=!1,Hi=!1):$n.artifacts.length>0&&hf()?(qe.element.classList.remove("persona-hidden"),qe.setMobileOpen(!0)):(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),to=!1,Hi=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(qe.setExpandToggleVisible(f),qe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),qe.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),qe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),qe.setTabFade(o.features?.artifacts?.layout?.tabFade),qe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!Hi&&(to=!1),to!==vf){let v=qe.element;to?(sl=v.style.width,il=v.style.maxWidth,v.style.removeProperty("width"),v.style.removeProperty("max-width")):(sl&&(v.style.width=sl),il&&(v.style.maxWidth=il),sl="",il=""),vf=to}t.classList.toggle("persona-artifact-expanded",to),qe.setExpanded(to);let y=ll();y!==Li&&(Li=y,Wr()),rl()};if(mn(o)){we.style.position="relative";let r=k("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),a=k("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");r.appendChild(de),mo=a,a.appendChild(r),we.appendChild(a);let p=y=>{mf||qe||(qe=y.createArtifactPane(o,{onSelect:v=>lt.current?.selectArtifact(v),onDismiss:()=>{Ro=!0,no()},onToggleExpand:()=>{let v=!to,B=$n.selectedId??$n.artifacts[$n.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:B,expanded:v})!==!0&&(to=v,v||(Hi=!1),no())}}),qe.element.classList.add("persona-hidden"),a.appendChild(qe.element),qe.backdrop&&we.appendChild(qe.backdrop),rl(),no())},f=er();f?p(f):(yg(()=>{let y=er();y&&p(y)}),ud().catch(()=>{})),rl=()=>{if(!mo||!qe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ri?.(),Ri=null,_d(),mt&&(mt.remove(),mt=null),qe.element.style.removeProperty("width"),qe.element.style.removeProperty("maxWidth");return}if(!mt){let v=k("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let B=t.ownerDocument,$=B.defaultView??window,F=q=>{if(!qe||q.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||$.innerWidth<=640)return;q.preventDefault(),_d();let X=q.clientX,oe=qe.element.getBoundingClientRect().width,pe=o.features?.artifacts?.layout,Xe=ut=>{let Vt=mo.getBoundingClientRect().width,Dt=t.classList.contains("persona-artifact-welded-split"),At=Sg(mo,$),nn=Dt?0:v.getBoundingClientRect().width||6,Je=oe-(ut.clientX-X),on=rC(Je,Vt,At,nn,pe?.resizableMinWidth,pe?.resizableMaxWidth,pw());qe.element.style.width=`${on}px`,qe.element.style.maxWidth="none",Cf()},ct=()=>{B.removeEventListener("pointermove",Xe),B.removeEventListener("pointerup",ct),B.removeEventListener("pointercancel",ct),ol=null;try{v.releasePointerCapture(q.pointerId)}catch{}};ol=ct,B.addEventListener("pointermove",Xe),B.addEventListener("pointerup",ct),B.addEventListener("pointercancel",ct);try{v.setPointerCapture(q.pointerId)}catch{}};v.addEventListener("pointerdown",F),mt=v,mo.insertBefore(v,qe.element),Ri=()=>{v.removeEventListener("pointerdown",F)}}if(mt){let v=nl();mt.classList.toggle("persona-hidden",!v),Cf()}},al=()=>{if(!ce||!qe||(o.launcher?.sidebarMode??!1)||Lt(o)&&Yn(o).reveal==="emerge")return;let v=t.ownerDocument.defaultView??window,B=o.launcher?.mobileFullscreen??!0,$=o.launcher?.mobileBreakpoint??640;if(B&&v.innerWidth<=$||!Jv(o,ce))return;let F=o.launcher?.width??o.launcherWidth??Jo,q=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";nl()?(we.style.width=q,we.style.maxWidth=q):(we.style.width=F,we.style.maxWidth=F)},typeof ResizeObserver<"u"&&(Ii=new ResizeObserver(()=>{no()}),Ii.observe(we))}else we.appendChild(de);Le()&&jt&&(Be.peekBanner&&jt.appendChild(Be.peekBanner),jt.appendChild(Ie)),t.appendChild(Ke),jt&&t.appendChild(jt);let Nd=()=>{if(Le()){we.style.width="100%",we.style.maxWidth="100%";let De=o.launcher?.composerBar??{},Ce=Ke.dataset.state==="expanded",sn=De.expandedSize??"anchored";if(!(Ce&&sn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let An=o.theme?.components?.panel,Mn=di(o),it=(It,En)=>It==null||It===""?En:un(Mn,It)??It,dt="1px solid var(--persona-border)",We="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Go="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=it(An?.border,dt),de.style.borderRadius=it(An?.borderRadius,Go),de.style.boxShadow=it(An?.shadow,We),de.style.overflow="hidden";return}let r=Lt(o),a=o.launcher?.sidebarMode??!1,p=r||a||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,y=o.launcher?.detachedPanel===!0,v=o.theme?.components?.panel,B=di(o),$=(De,Ce)=>De==null||De===""?Ce:un(B,De)??De,F=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,oe=F.innerWidth<=X,pe=q&&oe&&ce,Xe=r&&q&&oe,ct=o.launcher?.position??"bottom-left",ut=ct==="bottom-left"||ct==="top-left",Vt=o.launcher?.zIndex??an,Dt="var(--persona-panel-border, 1px solid var(--persona-border))",At="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",nn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Je=y&&!pe&&!Xe;Je?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let on=Je?Dt:a||pe?"none":Dt,So=Je?At:pe?"none":a?ut?"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))":f?"none":At;r&&!pe&&!Je&&(So="none",on="none");let Ko=Je?nn:a||pe?"0":nn,so=$(v?.border,on),aa=$(v?.shadow,So),as=$(v?.borderRadius,Ko),io=ll(),Yt=io==="detached",ao=io==="welded";t.classList.toggle("persona-artifact-detached-split",Yt),t.classList.toggle("persona-artifact-welded-split",ao);let Xs="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=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&mn(o)&&vg(o)&&f&&!r;t.classList.toggle("persona-artifact-chat-flush",Se);let se=Yt||Se?"none":aa,Mt=Yt?Dt:ao?"none":so,Ot=Yt?nn:as;Se&&(Mt="none",Ot="0");let Jt=v?.borderRadius!=null&&v.borderRadius!=="",_t=Se&&!Jt?"0":as,$t=te.scrollTop;t.style.cssText="",Ke.style.cssText="",we.style.cssText="",de.style.cssText="",te.style.cssText="",xs||(Ie.style.cssText=""),zt&&(te.style.display="none"),(p||f)&&(t.style.minWidth="0");let Et=()=>{if($t<=0)return;(te.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(te.scrollTop===$t)return;let Ce=te.scrollHeight-te.clientHeight;Ce<=0||(te.scrollTop=Math.min($t,Ce))})};if(pe){Ke.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"),Ke.style.cssText=`
|
|
34
|
+
`,O.addEventListener("click",()=>{m=w,I.forEach((K,ie)=>{let Z=ie<w;K.classList.toggle("selected",Z),K.setAttribute("aria-checked",ie===w-1?"true":"false")})}),I.push(O),E.appendChild(O)}v.appendChild(E);let P=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=i,P.rows=3,P.setAttribute("aria-label","Additional comments"),w.appendChild(P),v.appendChild(w)}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=c,x.addEventListener("click",()=>{n?.(),g.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=l,R.addEventListener("click",async()=>{if(m===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let w=P?.value.trim()||void 0;await e(m,w),g.remove()}catch(w){R.disabled=!1,R.textContent=l,console.error("[CSAT Feedback] Failed to submit:",w)}}),N.appendChild(x),N.appendChild(R),v.appendChild(N),g.appendChild(v),g}function AC(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:i="What could we do better? (optional)...",submitText:l="Submit",skipText:c="Skip",showComment:d=!0,lowLabel:u="Not likely",highLabel:g="Very likely"}=t,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 v=null,h=document.createElement("div");h.className="persona-feedback-content";let T=document.createElement("div");T.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=o,T.appendChild(M);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,T.appendChild(E),h.appendChild(T);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-nps",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let N=document.createElement("span");N.className="persona-feedback-label-low",N.textContent=u;let x=document.createElement("span");x.className="persona-feedback-label-high",x.textContent=g,P.appendChild(N),P.appendChild(x);let R=document.createElement("div");R.className="persona-feedback-numbers";let w=[];for(let S=0;S<=10;S++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-number-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`Rating ${S} out of 10`),B.textContent=String(S),B.dataset.rating=String(S),S<=6?B.classList.add("persona-feedback-detractor"):S<=8?B.classList.add("persona-feedback-passive"):B.classList.add("persona-feedback-promoter"),B.addEventListener("click",()=>{v=S,w.forEach((W,H)=>{W.classList.toggle("selected",H===S),W.setAttribute("aria-checked",H===S?"true":"false")})}),w.push(B),R.appendChild(B)}I.appendChild(P),I.appendChild(R),h.appendChild(I);let O=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",O=document.createElement("textarea"),O.className="persona-feedback-comment",O.placeholder=i,O.rows=3,O.setAttribute("aria-label","Additional comments"),S.appendChild(O),h.appendChild(S)}let K=document.createElement("div");K.className="persona-feedback-actions";let ie=document.createElement("button");ie.type="button",ie.className="persona-feedback-btn persona-feedback-btn-skip",ie.textContent=c,ie.addEventListener("click",()=>{n?.(),m.remove()});let Z=document.createElement("button");return Z.type="button",Z.className="persona-feedback-btn persona-feedback-btn-submit",Z.textContent=l,Z.addEventListener("click",async()=>{if(v===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}Z.disabled=!0,Z.textContent="Submitting...";try{let S=O?.value.trim()||void 0;await e(v,S),m.remove()}catch(S){Z.disabled=!1,Z.textContent=l,console.error("[NPS Feedback] Failed to submit:",S)}}),K.appendChild(ie),K.appendChild(Z),h.appendChild(K),m.appendChild(h),m}var Ci="persona-chat-history",CT=30*1e3,wT=641,wi="data-persona-composer-reason",ST={"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 xT(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let s=o.getAsFile();if(!s)continue;if(s.name){e.push(s);continue}let i=ST[s.type]??"png";e.push(new File([s],`clipboard-image-${Date.now()}.${i}`,{type:s.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function hd(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function AT(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function MT(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Hg=t=>!t||typeof t!="object"?{}:{...t},kC=t=>t.map(e=>({...e,streaming:!1})),PC=(t,e,n)=>{let o=t?.markdown?Mh(t.markdown):null,s=Eh(t?.sanitize);t?.postprocessMessage&&s&&t?.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 i=!1,l=c=>{let d=c.text??"",u=c.message.rawContent??null;if(e){let v=e.process({text:d,raw:u??d,message:c.message,streaming:c.streaming});v!==null&&(d=v.text,v.persist||(c.message.__skipPersist=!0),v.resubmit&&!c.streaming&&n&&n())}let g=Ys()!==null,m;if(t?.postprocessMessage){let v=t.postprocessMessage({...c,text:d,raw:u??c.text??""});m=s?s(v):v}else if(o){let v=c.streaming?ly(d):d,h=o(v);m=s&&g?s(h):h}else m=ic(d);return m};return c=>{try{return l(c)}catch(d){return i||(i=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",d)),ic(c.text??"")}}};function IC(t){let e=k("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",s=t?.iconColor??"rgba(59, 130, 246, 0.6)",i=t?.iconStrokeWidth??.5,l=ge(n,o,s,i);if(l&&e.appendChild(l),t?.label){let c=k("span","persona-drop-overlay-label");c.textContent=t.label,e.appendChild(c)}return e}var ET=(t,e)=>{let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];n[o]=i?{...i,...s}:s}return n},TT=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:ET(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),LC=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=Hc(e),s=()=>{pb({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};s();let i=o.features;o=wg(o);let l=Ag.getForInstance(o.plugins),c=lv(t),d=[],u=!1,g=qv(()=>o),m=null,v=null,h=null,T=!1,M=null,E=r=>{m=r,r.initApprovalUi({webMcpToolTitle:ac});let a=r.createBuiltInApprovalPlugin();v=a.plugin,h=a.teardown},I=()=>{if(m)return m;let r=Gv();return r?(E(r),r):(Kv().then(a=>{T||m||(E(a),M?.())}).catch(()=>{}),null)},P=!1,N=!1,x=null,R=(r,a,p,f)=>{if(!r.querySelector("[data-tv-form]"))return;let y=iC();if(y){y.enhanceWithForms(r,a,p,f);return}sC().then(()=>{P||N||!x||(N=!0,x())}).catch(()=>{})};o.components&&Xo.registerAll(o.components);let w=dC(),K=o.persistState===!1?null:o.storageAdapter??uC(),ie=!!o.clientToken&&typeof o.reconnectStream!="function",Z={},S=null,B,W=new Promise(r=>{B=r}),H,J=!1,$=r=>{if(o.onStateLoaded)try{let a=o.onStateLoaded(r);if(a&&typeof a=="object"&&"state"in a){let{state:p,open:f}=a;return f&&(J=!0),p}return a}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}return r};if(K?.load)try{let r=K.load();if(r&&typeof r.then=="function")S=r.then(a=>$(a??{messages:[],metadata:{}}));else{let p=$(r??{messages:[],metadata:{}});p.metadata&&(Z=Hg(p.metadata)),p.messages?.length&&(o={...o,initialMessages:p.messages}),p.artifacts?.length&&(o={...o,initialArtifacts:p.artifacts,initialSelectedArtifactId:p.selectedArtifactId??null}),H=p.draft}}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",r)}else if(o.onStateLoaded)try{let r=$({messages:[],metadata:{}});r.messages?.length&&(o={...o,initialMessages:r.messages})}catch(r){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",r)}S||B();let ae=()=>Z,re=r=>{Z=r({...Z})??{},Ls()},ue=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Eg],Ee=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[qa.message,qa.messageAndClick],he=Tg({parsers:ue,handlers:Ee,getSessionMetadata:ae,updateSessionMetadata:re,emit:w.emit,documentRef:typeof document<"u"?document:null});he.syncFromMetadata();let ce=o.launcher?.enabled??!0,at=o.launcher?.autoExpand??!1,ye=o.autoFocusInput??!1,F=at,Te=ce,Ue=o.layout?.header?.layout,qt=!1,Le=()=>Ba(o),Fe=()=>ce||Le(),ve=Le()?!1:ce?at:!0,ln=!1,Zn=null,Po=()=>{ln=!0,Zn&&clearTimeout(Zn),Zn=setTimeout(()=>{ln&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ln=!1)},1e4)},vt=PC(o,he,Po),Io=o.features?.showReasoning??!0,j=o.features?.showToolCalls??!0,C=o.features?.showEventStreamToggle??!1,_=o.features?.scrollToBottom??{},V=o.features?.scrollBehavior??{},Q=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",me=`${Q()}event-stream`,Me=null,Pe=o.features?.eventStream?.maxEvents??2e3,Re=null,ot=null,Ve=null,$e=!1,gt=null,zt=!1,kt=null,tn=0,hn=(r,a)=>{Re?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:r,timestamp:Date.now(),payload:JSON.stringify(a)})},bd=(r,a)=>{ot?.processEvent(r,a),Re?hn(r,a):Ve&&(Ve.length>=Pe&&Ve.shift(),Ve.push({type:r,payload:a}))},ja=()=>{Re||!C||(Ve??(Ve=[]),mg().then(r=>{if($e||Re||!C)return;Me=new r.EventStreamStore(me),Re=new r.EventStreamBuffer(Pe,Me),ot=ot??new r.ThroughputTracker,Me.open().then(()=>Re?.restore()).catch(p=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",p)});let a=Ve??[];Ve=null;for(let p of a)ot?.processEvent(p.type,p.payload),hn(p.type,p.payload)}).catch(()=>{}))};C&&ja();let Ct=!1,Ht=null,vd=()=>{},Lo=()=>{},Ng=()=>{},Fg=()=>{},Cd=()=>{},qC=()=>zt||Ct&&Ht==="panel",ys={onCopy:r=>{w.emit("message:copy",r),A?.isClientTokenMode()&&A.submitMessageFeedback(r.id,"copy").catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",a)}),o.messageActions?.onCopy?.(r)},onFeedback:r=>{w.emit("message:feedback",r),A?.isClientTokenMode()&&A.submitMessageFeedback(r.messageId,r.type).catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",a)}),o.messageActions?.onFeedback?.(r)}},bs=o.statusIndicator??{},Ug=r=>r==="idle"?bs.idleText??Nt.idle:r==="connecting"?bs.connectingText??Nt.connecting:r==="connected"?bs.connectedText??Nt.connected:r==="error"?bs.errorText??Nt.error:r==="paused"?bs.pausedText??Nt.paused:r==="resuming"?bs.resumingText??Nt.resuming:Nt[r];function Va(r,a,p,f){if(!r.hasAttribute(wi))if(f==="idle"&&p.idleLink){r.textContent="";let y=document.createElement("a");y.href=p.idleLink,y.target="_blank",y.rel="noopener noreferrer",y.textContent=a,y.style.color="inherit",y.style.textDecoration="none",r.appendChild(y)}else r.textContent=a}let Pn=$v({config:o,showClose:Fe()}),{wrapper:Ke,panel:we,pillRoot:jt}=Pn.shell,Be=Pn.panelElements,{container:de,body:te,messagesWrapper:ke,starterSuggestions:wd,transcriptSuggestions:xi,suggestions:or,textarea:le,sendButton:xe,composerForm:eo,statusText:rt,welcomeHost:yn,welcomeIconHolder:zC,greetingHost:In,introKicker:jC,introTitle:VC,introSubtitle:KC,closeButton:_e,iconHolder:wt,headerTitle:rr,headerSubtitle:Ir,header:Ae,footer:Ie,actionsRow:GC}=Be,Sd=Be.leftActions,Ka=Be.rightActions,uo=Be.sendButtonWrapper,$g=Be.setSendButtonMode,ne=Be.micButton,Ln=Be.micButtonWrapper,bt=Be.attachmentButton,bn=Be.attachmentButtonWrapper,ft=Be.attachmentInput,vn=Be.attachmentPreviewsContainer;de.classList.add("persona-relative"),te.classList.add("persona-relative");let QC=12,Ai=()=>_.label??"",XC=()=>_.iconName??"arrow-down",YC=()=>_.enabled!==!1,Hn=()=>V.mode??"anchor-top",sr=()=>Hn()==="follow"||Hn()==="anchor-top"&&Wi,Mi=()=>V.anchorTopOffset??16,JC=()=>V.restorePosition??"bottom",qg=()=>V.pauseOnInteraction===!0,zg=()=>V.showActivityWhilePinned!==!1,jg=()=>V.announce===!0,xd=()=>V.scrollbar??"on-scroll",Rt=k("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");Rt.type="button",Rt.style.display="none",Rt.setAttribute("data-persona-scroll-to-bottom","true");let Ei=k("span","persona-flex persona-items-center"),Ad=k("span",""),Lr=k("span","");Lr.setAttribute("data-persona-scroll-to-bottom-count",""),Lr.style.display="none",Rt.append(Ei,Ad,Lr),de.appendChild(Rt);let Un=k("div","persona-stream-anchor-spacer");Un.setAttribute("aria-hidden","true"),Un.setAttribute("data-persona-anchor-spacer",""),Un.style.flexShrink="0",Un.style.pointerEvents="none",Un.style.height="0px",Un.style.display="none",te.appendChild(Un);let Ho=k("div","persona-sr-only");Ho.setAttribute("aria-live","polite"),Ho.setAttribute("aria-atomic","true"),Ho.setAttribute("role","status"),Ho.setAttribute("data-persona-live-region",""),Object.assign(Ho.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(Ho);let Ti=null,Ga=null,Qa=r=>{!jg()||!r||(Ga=r,Ti===null&&(Ti=setTimeout(()=>{Ti=null,Ga&&jg()&&(Ho.textContent=Ga),Ga=null},400)))},Xa="empty",Ya=0,Md=()=>Ya||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Hr=()=>{let a=Ie.style.display==="none"?0:Ie.offsetHeight;Rt.style.bottom=`${a+Md()+QC}px`};Hr();let Ed=()=>{xs||(Ie.style.marginBottom=Ya>0?`${Ya}px`:"")},Ja=()=>{let r=qu(o,Le()),a=Zo(o),f=Ie.style.display==="none"?0:Ie.offsetHeight,y=a.anchor==="center"&&Xa==="empty"?La(a.anchorComposerTop)??La("44%"):null,b=y===null||Le()?0:sv({columnHeight:de.clientHeight,footerHeight:f,fraction:y});t.style.setProperty("--persona-composer-overlay-height",`${f}px`),t.style.setProperty("--persona-composer-lift",`${r==="overlay"?b:0}px`),Ya=r==="block"?b:0,Ed(),Hr()},Vg=()=>{let r=!!Ai();Rt.setAttribute("aria-label",Ai()||"Jump to latest"),Rt.title=Ai(),Rt.setAttribute("data-persona-scroll-to-bottom-has-label",r?"true":"false"),Ei.innerHTML="";let a=ge(XC(),"14px","currentColor",2);a?(Ei.appendChild(a),Ei.style.display=""):Ei.style.display="none",Ad.textContent=Ai(),Ad.style.display=r?"":"none"};Vg();let Ye=null,Pt=null,be=sb(),ZC=r=>{try{de.dispatchEvent(new CustomEvent("persona:composer:state",{detail:r,bubbles:!0,composed:!0}))}catch{}};be.subscribe(ZC);let go=()=>{be.setText(le?.value??"")},Rr=()=>{be.setMentionRefs(Pt?.getMentionRefs()??[])},ew=r=>({id:r.id,name:r.file.name,mimeType:r.file.type,size:r.file.size,status:r.status,progress:r.progress,error:r.error}),Kg=r=>{let a=Object.freeze(r.map(ew));be.setAttachments(a);try{o.attachments?.onChange?.(a)}catch(p){console.error("[AgentWidget] attachments.onChange failed:",p)}Zd()};be.setSelectedModelId(o.composer?.selectedModelId);let ki=()=>o.composer?.modes??[],vs=()=>Rb(ki(),o.composer?.modeGroups);{let r=qc(o.composer?.defaultActiveModeIds??[],ki());r.length&&be.setActiveModeIds(r)}function Gg(r){if(be.getState().selectedModelId!==r){be.setSelectedModelId(r),ir?.repaint();try{o.composer?.onModelChange?.(r)}catch(a){console.error("[AgentWidget] composer.onModelChange failed:",a)}}}function Za(r){be.setActiveModeIds(r),Ro?.render(r,vs()),Cs.forEach(a=>a.repaint()),mo?.resolve(),Al(),to()}function Td(r){Za(Wb(be.getState().activeModeIds,r,ki(),o.composer?.modeGroups))}let ir=null,kd=null,Ro=null,Cs=new Map,ar=null;function fo(r){be.setQuote(r),ar?.render(be.getState().quote),to(),Uf()}let Qg=!1;function Pd(){let r=o.composer?.streamingSubmitBehavior??"block";return r!=="interrupt"?r:o.clientToken?"interrupt":(!Qg&&o.debug===!0&&(Qg=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let lr=null;function ws(r){be.setPendingSubmission(r),lr?.render(be.getState().pendingSubmission),to()}let tw=r=>{let a=Cs.get(r);if(a)return a;let p=Ob({groupId:r,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===r),getModes:()=>ki().filter(f=>f.groupId===r),getActiveIds:()=>be.getState().activeModeIds,onSelect:f=>Td(f)});return Cs.set(r,p),p},nw=()=>{let r=[],a=be.getState().activeModeIds,p=new Set;if(ki().forEach((f,y)=>{if($c(f.groupId,o.composer?.modeGroups)){let b=f.groupId;if(p.has(b))return;p.add(b);let D=tw(b);D.action.order=_u(y),D.action.label=o.composer?.modeGroups?.find(q=>q.id===b)?.label??b,r.push(D.action);return}r.push({id:Lb(f.id),kind:"button",placement:"start",order:_u(y),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:a.includes(f.id),onSelect:()=>Td(f.id)})}),o.composer?.models?.length&&!l.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!ir||kd!==f)&&(kd=f,ir=Pb({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>be.getState().selectedModelId,onSelect:y=>Gg(y),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),r.push(ir.action)}return r},Id=null,Xg=l.find(r=>r.renderHeader);if(Xg?.renderHeader){let r=Xg.renderHeader({config:o,defaultRenderer:()=>{let a=fs({config:o,showClose:Fe()});return Oa(de,a,o),a.header},onClose:()=>pt(!1,"user")});if(r){let a=Ae;a&&(a.replaceWith(r),Ae=r,Pn.header.element=r)}}let Yg=()=>{gt&&(te.style.display="none",Ie.parentNode?.insertBefore(gt.element,Ie),gt.update())},Ld=()=>{if(!Re){ja();return}if(zt=!0,gt?Yg():mg().then(a=>{gt||!zt||!Re||(gt=a.createEventStreamView({buffer:Re,getFullHistory:()=>Re.getAllFromStore(),onClose:()=>Ss(),config:o,plugins:l,getThroughput:()=>ot?.getMetric()??{status:"idle"},renderIconByName:ge}),Yg())}).catch(()=>{Ss()}),Ze){Ze.style.boxShadow=`inset 0 0 0 1.5px ${gn.actionIconColor}`;let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(p=>p&&Ze.classList.add(p))}let r=()=>{if(!zt)return;let a=Date.now();a-tn>=200&&(gt?.update(),tn=a),kt=requestAnimationFrame(r)};tn=0,kt=requestAnimationFrame(r),Ut(),w.emit("eventStream:opened",{timestamp:Date.now()})},Ss=()=>{if(zt){if(zt=!1,gt&>.element.remove(),te.style.display="",Ze){Ze.style.boxShadow="";let r=o.features?.eventStream?.classNames?.toggleButtonActive;r&&r.split(/\s+/).forEach(a=>a&&Ze.classList.remove(a))}kt!==null&&(cancelAnimationFrame(kt),kt=null),Ut(),w.emit("eventStream:closed",{timestamp:Date.now()})}},Ze=null;if(C){let r=o.features?.eventStream?.classNames,a="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"+(r?.toggleButton?" "+r.toggleButton:"");Ze=k("button",a),Ze.style.width="28px",Ze.style.height="28px",Ze.style.color=gn.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let p=en(MC,"18px","currentColor",1.5);p&&Ze.appendChild(p);let f=Be.clearChatButtonWrapper,y=Be.closeButtonWrapper,b=f||y;b&&b.parentNode===Ae?Ae.insertBefore(Ze,b):Ae.appendChild(Ze),Ze.addEventListener("click",()=>{zt?Ss():Ld()})}let Jg=r=>{let a=o.attachments;if(!a?.enabled)return;let p=r.querySelector("[data-persona-composer-attachment-previews]")??r.querySelector(".persona-attachment-previews");if(!p){p=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),p.setAttribute("data-persona-composer-attachment-previews",""),p.style.display="none";let y=r.querySelector("[data-persona-composer-form]");y?.parentNode?y.parentNode.insertBefore(p,y):r.insertBefore(p,r.firstChild)}if(!(r.querySelector("[data-persona-composer-attachment-input]")??r.querySelector('input[type="file"]'))){let y=k("input");y.type="file",y.setAttribute("data-persona-composer-attachment-input",""),y.accept=(a.allowedTypes??Yo).join(","),y.multiple=(a.maxFiles??4)>1,y.style.display="none",y.setAttribute("aria-label",a.buttonTooltipText??"Attach files"),r.appendChild(y)}},xs=!1,Zg=r=>{let a=l.find(y=>y.renderComposer);if(!a?.renderComposer)return null;let p=o.composer,f=u?A.isStreaming():!1;return a.renderComposer({config:o,defaultRenderer:r,requestRender:()=>gh(),storage:g(a.id),onSubmit:y=>{!A||A.isStreaming()||Yl(y.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{vo()||ft?.click()},models:p?.models,selectedModelId:be.getState().selectedModelId??p?.selectedModelId,onModelChange:y=>Gg(y),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Id?.()}:void 0})},ef=Zg(()=>_a({config:o}).footer);ef&&(Pn.replaceComposer(ef),Ie=Pn.composer.footer,xs=!0);let et=null,ow=r=>{eo=r.form,le=r.input,uo=r.sendButton?r.sendButton.parentElement:null,r.sendButton&&(xe=r.sendButton),r.micButton&&(ne=r.micButton,Ln=r.micButton.parentElement),r.found.status&&(rt=r.found.status),r.found.suggestions&&(or=r.found.suggestions),r.attachmentButton&&(bt=r.attachmentButton,bn=r.attachmentButton.parentElement),ft=r.attachmentInput??null,vn=r.attachmentPreviews??null,r.found.actionsRow&&(GC=r.found.actionsRow),Sd=r.found.actionsStart,Ka=r.found.actionsEnd};function Hd(){let r=le;if(!r)return;let a=o.composer?.inputAttributes,p=!a?.ariaLabel&&!(r instanceof HTMLTextAreaElement)?r.getAttribute("aria-label"):null;Bc(r,a),p&&r.setAttribute("aria-label",p),Wc(r,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ka(r)}),yb(r,Rc(o.composer?.maxLines,Le()?5:3))}let tf=r=>{et=ab(r,{debug:o.debug===!0}),et&&ow(et),Hd()};Jg(Ie),tf(Ie),go();let Pi=kr(o,Le());Pi&&(ke.style.maxWidth=Pi,ke.style.marginLeft="auto",ke.style.marginRight="auto",ke.style.width="100%",In.style.maxWidth=Pi,In.style.marginLeft="auto",In.style.marginRight="auto",In.style.width="100%",wd.style.maxWidth=Pi,xi.style.maxWidth=Pi,xi.style.marginLeft="auto",xi.style.marginRight="auto",xi.style.width="100%");let nf=()=>{let r=kr(o,Le());if(!(!r||Le()))for(let a of[eo,or,vn,rt])a&&(a.style.maxWidth=r,a.style.marginLeft="auto",a.style.marginRight="auto",a.style.width="100%")};nf();let of=()=>{!o.attachments?.enabled||!ft||!vn||(Ye?Ye.remountPreviews(vn):(Ye=Ma.fromConfig(o.attachments,Kg),Ye.setPreviewsContainer(vn)),et?.addListener(ft,"change",r=>{let a=r.target;Ye?.handleFileSelect(a.files),a.value=""}),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(IC(o.attachments.dropOverlay)))};of();let rw=()=>Pt?.prefetch(),rf=()=>{if(!o.contextMentions?.enabled||!le)return;let r=et?.header??null,a=r?tu(r):void 0;if(Pt=Jb({config:o,textarea:le,anchor:eo??le,getMessages:()=>A.getMessages(),liveRegionHost:de,chipRow:a}),Pt&&!a){let p=le;p.parentElement?.insertBefore(Pt.contextRow,p)}};rf();let mo=null,sw={getState:()=>be.getState(),getValue:()=>le?.value??"",setValue:r=>{le&&(le.value=r,le.dispatchEvent(new Event("input",{bubbles:!0})),go())},submit:()=>{$h(et?.form??null)},openAttachmentPicker:()=>{vo()||ft?.click()},toggleVoice:()=>{Id?.()},requestRender:()=>mo?.resolve()},iw=()=>{let r=[];return(Pt?.affordanceButtons??[]).forEach((p,f)=>{r.push({id:`core:mention-${f}`,placement:"start",order:To.mention+f,element:p,managed:!0})}),bn&&r.push({id:"core:attachment",placement:"start",order:To.attachment,element:bn}),Ln&&r.push({id:"core:mic",placement:"end",order:To.mic,element:Ln}),uo&&r.push({id:"core:send",placement:"end",order:To.send,element:uo}),r},sf=()=>{mo?.destroy(),mo=Eb({getBindings:()=>et,collect:()=>({builtIns:iw(),configActions:[...nw(),...o.composer?.actions??[]],plugins:l,contributionContext:{config:o,getState:()=>be.getState(),requestRender:()=>mo?.resolve()},debug:o.debug===!0}),actionContext:sw,getState:()=>be.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(r,a)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${a.actionId}" failed:`,r)}}),mo.resolve()};sf();let Rd=()=>{if(Ro?.destroy(),Ro=null,!vs().length)return;let r=et?.header;r&&(Ro=Ib({row:tu(r),onRemove:a=>Td(a),initialIds:be.getState().activeModeIds}),Ro.render(be.getState().activeModeIds,vs()))};Rd();let af=()=>{ar?.destroy(),ar=null,lr?.destroy(),lr=null;let r=et?.header;r&&(ar=_b({onDismiss:()=>fo(void 0)}),r.appendChild(ar.element),ar.render(be.getState().quote),Pd()==="defer-one"&&(lr=Nb({onEdit:()=>WS(),onRemove:()=>ws(void 0)}),r.appendChild(lr.element),lr.render(be.getState().pendingSubmission)))};af();let Wd=jb(),aw=()=>{let r=et?.header?.querySelector(Uh);if(r)return r.childElementCount>0;let a=be.getState();return a.mentionRefs.length>0||qc(a.activeModeIds,vs()).length>0},lf=()=>!1;function to(){let r=be.getState(),a=Wd.observe(Vb(le),r.text);Ie.toggleAttribute("data-persona-composer-compact",zb({text:r.text,wrapped:a,hasAttachments:r.attachments.length>0,hasChips:aw(),hasQuote:r.quote!==void 0,hasPendingSubmission:r.pendingSubmission!==void 0,dictationActive:lf()}))}function cf(){o.composer?.layout==="single-row"&&!Le()?Ie.setAttribute("data-persona-composer-layout","single-row"):Ie.removeAttribute("data-persona-composer-layout")}cf(),be.subscribe(()=>{mo?.sync(),Zd(),Sl(),to(),Uf()}),Sl();let df=!1,lw=r=>{if(df||o.debug!==!0)return;let a=["messages","composer"].filter(p=>r[p]);a.length&&(df=!0,console.warn(`[persona] layout.slots.${a.join(" and layout.slots.")} ${a.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 r=o.layout?.slots??{};lw(r);let a=f=>{switch(f){case"body-top":return te.querySelector("[data-persona-intro-card]");case"messages":return ke;case"footer-top":return or;case"composer":return eo;case"footer-bottom":return rt;default:return null}},p=(f,y)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Ae.insertBefore(y,Ae.firstChild);else if(f==="header-right")Ae.appendChild(y);else{let b=Ae.querySelector(".persona-flex-col");b?b.parentNode?.insertBefore(y,b.nextSibling):Ae.appendChild(y)}break;case"body-top":{let b=te.querySelector("[data-persona-intro-card]");b?b.replaceWith(y):te.insertBefore(y,te.firstChild);break}case"body-bottom":te.appendChild(y);break;case"footer-top":or.replaceWith(y);break;case"footer-bottom":rt.replaceWith(y);break;default:break}};for(let[f,y]of Object.entries(r))if(y)try{let b=y({config:o,defaultContent:()=>a(f)});b&&p(f,b)}catch(b){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${f}":`,b)}})();let pf=r=>{let p=r.target.closest('button[data-expand-header="true"]');if(!p)return;let f=p.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!f)return;let y=f.getAttribute("data-message-id");if(!y)return;let b=p.getAttribute("data-bubble-type");if(b==="reasoning")mi.has(y)?mi.delete(y):mi.add(y),zv(y,f);else if(b==="tool")hi.has(y)?hi.delete(y):hi.add(y),Vv(y,f,o);else if(b==="approval"&&m){let q=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",U=m.approvalDetailsExpansionState.get(y)??q;m.approvalDetailsExpansionState.set(y,!U),m.updateApprovalDetailsUI(y,f,o)}Wt.delete(y)};ke.addEventListener("pointerdown",r=>{r.target.closest('button[data-expand-header="true"]')&&(r.preventDefault(),pf(r))}),ke.addEventListener("keydown",r=>{let a=r.target;(r.key==="Enter"||r.key===" ")&&a.closest('button[data-expand-header="true"]')&&(r.preventDefault(),pf(r))}),ke.addEventListener("copy",r=>{let{clipboardData:a}=r;if(!a)return;let p=ke.getRootNode(),f=typeof p.getSelection=="function"?p.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let y=f.toString(),b=cv(y);!b||b===y||(a.setData("text/plain",b),r.preventDefault())});let Bd=new Map,uf=null,gf="idle",cw={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},dw=(r,a)=>{let{icon:p,label:f}=cw[a];r.setAttribute("aria-label",f),r.title=f,r.setAttribute("aria-pressed",a==="idle"?"false":"true"),r.classList.toggle("persona-message-action-active",a!=="idle"),r.classList.toggle("persona-message-action-loading",a==="loading");let y=ge(p,14,"currentColor",2);y&&(r.innerHTML="",r.appendChild(y))},ff=()=>{ke.querySelectorAll('[data-action="read-aloud"]').forEach(a=>{let f=a.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;dw(a,f&&f===uf?gf:"idle")})};ke.addEventListener("click",r=>{let p=r.target.closest(".persona-message-action-btn[data-action]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.closest("[data-actions-for]");if(!f)return;let y=f.getAttribute("data-actions-for");if(!y)return;let b=p.getAttribute("data-action");if(b==="copy"){let q=A.getMessages().find(U=>U.id===y);if(q&&ys.onCopy){let U=q.content||"";navigator.clipboard.writeText(U).then(()=>{p.classList.add("persona-message-action-success");let z=en(EC,14,"currentColor",2);z&&(p.innerHTML="",p.appendChild(z)),setTimeout(()=>{p.classList.remove("persona-message-action-success");let X=en(TC,14,"currentColor",2);X&&(p.innerHTML="",p.appendChild(X))},2e3)}).catch(z=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",z)}),ys.onCopy(q)}}else if(b==="read-aloud")A.toggleReadAloud(y);else if(b==="upvote"||b==="downvote"){let q=(Bd.get(y)??null)===b,U=b==="upvote"?"thumbs-up":"thumbs-down";if(q){Bd.delete(y),p.classList.remove("persona-message-action-active");let z=ge(U,14,"currentColor",2);z&&(p.innerHTML="",p.appendChild(z))}else{let z=b==="upvote"?"downvote":"upvote",X=f.querySelector(`[data-action="${z}"]`);if(X){X.classList.remove("persona-message-action-active");let ut=ge(z==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ut&&(X.innerHTML="",X.appendChild(ut))}Bd.set(y,b),p.classList.add("persona-message-action-active");let oe=ge(U,14,"currentColor",2);oe&&(oe.setAttribute("fill","currentColor"),p.innerHTML="",p.appendChild(oe)),p.classList.remove("persona-message-action-pop"),p.offsetWidth,p.classList.add("persona-message-action-pop");let Xe=A.getMessages().find(ct=>ct.id===y);Xe&&ys.onFeedback&&ys.onFeedback({type:b,messageId:Xe.id,message:Xe})}}else if(b==="regenerate")el?.regenerate(y);else if(b==="edit")el?.edit(y);else if(b==="quote")el?.quote(y);else if(b?.startsWith(td)){let D=b.slice(td.length),q=o.messageActions?.custom?.find(z=>z.id===D),U=A.getMessages().find(z=>z.id===y);if(!q||!U)return;try{q.onSelect(U)}catch(z){console.error(`[AgentWidget] messageActions.custom "${D}" onSelect failed:`,z)}}});let el=null;ke.addEventListener("click",r=>{let p=r.target.closest("button[data-approval-action]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.closest(".persona-approval-bubble");if(!f)return;let y=f.getAttribute("data-message-id");if(!y)return;let b=p.getAttribute("data-approval-action");if(!b)return;let D=b==="approve"?"approved":"denied",U=A.getMessages().find(X=>X.id===y);if(!U?.approval)return;let z=f.querySelector("[data-approval-buttons]");z&&z.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),U.approval.toolType==="webmcp"?A.resolveWebMcpApproval(y,D):A.resolveApproval(U.approval,D)});let qe=null,mf=!1,Ii=null,Wr=()=>{},Li="none",tl=null,$n={artifacts:[],selectedId:null},Wo=!1,no=!1,Hi=!1,As=!1,hf=()=>As||$n.artifacts.some(r=>Sr(o.features?.artifacts,r)==="panel"),nl=()=>$n.artifacts.length>0&&!Wo&&hf(),lt={current:null},Dd=(r,a)=>{let p=A.getArtifactById(a),f=p?.markdown,y=p?.title||"artifact",b=p?.file,D=p?.artifactType??"markdown";if(!f){let z=r.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(z){let oe=A.getMessages().find(pe=>pe.id===z);if(oe?.rawContent)try{let pe=JSON.parse(oe.rawContent);f=pe?.props?.markdown,y=pe?.props?.title||y,pe?.props?.file&&typeof pe.props.file=="object"&&(b=pe.props.file),!p&&typeof pe?.props?.artifactType=="string"&&(D=pe.props.artifactType)}catch{}}}return{markdown:f,title:y,file:b,artifactType:D}};ke.addEventListener("click",r=>{let p=r.target.closest("[data-download-artifact]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:b,title:D,file:q}=Dd(p,f);if(!b)return;let U=er();U&&U.triggerArtifactDownload(U.downloadInfoFor({title:D,markdown:b,file:q}))}),ke.addEventListener("click",r=>{let p=r.target.closest("[data-artifact-custom-action]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-artifact-custom-action");if(!f)return;let y=p.closest("[data-artifact-inline]"),b=y?null:p.closest("[data-open-artifact]"),D=y?y.getAttribute("data-artifact-inline"):b?.getAttribute("data-open-artifact")??null,U=(y?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ct=>ct.id===f);if(!U)return;let{markdown:z,title:X,file:oe,artifactType:pe}=Dd(p,D??""),Xe={artifactId:D,title:X,artifactType:pe,markdown:z,file:oe};try{Promise.resolve(U.onClick(Xe)).catch(()=>{})}catch{}}),ke.addEventListener("click",r=>{let p=r.target.closest("[data-copy-artifact]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-copy-artifact");if(!f)return;let y=A.getArtifactById(f),b=er();if(!b)return;let D="";if(y)D=b.artifactCopyText(y);else{let{markdown:q,file:U,artifactType:z}=Dd(p,f);z==="markdown"&&(D=b.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:q??"",...U?{file:U}:{}}))}D&&navigator.clipboard.writeText(D).then(()=>{let q=en(EC,16,"currentColor",2);q&&(p.replaceChildren(q),setTimeout(()=>{let U=en(TC,16,"currentColor",2);U&&p.replaceChildren(U)},1500))}).catch(()=>{})}),ke.addEventListener("click",r=>{let p=r.target.closest("[data-expand-artifact-inline]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-expand-artifact-inline");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(Wo=!1,As=!0,no=!0,Hi=!0,A.selectArtifact(f),oo())}),ke.addEventListener("click",r=>{let a=r.target;if(a.closest("[data-download-artifact]")||a.closest("[data-artifact-custom-action]"))return;let p=a.closest("[data-open-artifact]");if(!p)return;let f=p.getAttribute("data-open-artifact");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(r.preventDefault(),r.stopPropagation(),Wo=!1,As=!0,A.selectArtifact(f),oo())}),ke.addEventListener("keydown",r=>{if(r.key!=="Enter"&&r.key!==" ")return;let a=r.target;!a.hasAttribute("data-open-artifact")&&!a.hasAttribute("data-expand-artifact-inline")||(r.preventDefault(),a.click())});let Ms=Be.composerOverlay,Es=(r,a,p)=>{let f=a.trim();if(!f||!lt.current)return;let y=r.getAttribute("data-tool-call-id")??"",b=p.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:y,answer:f,answers:p.structured,values:p.values??(p.source==="multi"?f.split(", "):[f]),isFreeText:b,source:p.source},bubbles:!0,composed:!0})),si(Ms,y);let D=lt.current.getMessages().find(q=>q.toolCall?.id===y);D?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(D,p.structured??f):lt.current.sendMessage(f)},Br=r=>{let a=lt.current;if(!a)return;let p=r.getAttribute("data-tool-call-id")??"",f=a.getMessages().find(y=>y.toolCall?.id===p);f&&a.persistAskUserQuestionProgress(f,{answers:vc(r,f),currentIndex:Yn(r)})},yf=r=>Object.entries(r).map(([a,p])=>`${a}: ${Array.isArray(p)?p.join(", "):p}`).join(" | "),Od=r=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let a=Yn(r),p=ri(r);if(a>=p-1)return;let f=lt.current?.getMessages().find(y=>y.toolCall?.id===r.getAttribute("data-tool-call-id"));f&&(wc(r,f,o,a+1),Br(r))};Ms.addEventListener("click",r=>{let p=r.target.closest("[data-ask-user-action]");if(!p)return;let f=p.closest("[data-persona-ask-sheet-for]");if(!f)return;let y=p.getAttribute("data-ask-user-action");if(r.preventDefault(),r.stopPropagation(),y==="dismiss"){let b=f.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),si(Ms,b);let D=lt.current?.getMessages().find(q=>q.toolCall?.id===b);D?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(D),lt.current?.resolveAskUserQuestion(D,"(dismissed)"));return}if(y==="pick"){let b=p.getAttribute("data-option-label");if(!b)return;let D=f.getAttribute("data-multi-select")==="true",q=xr(f);if(q&&D){let U=ps(f)[Yn(f)],z=new Set(Array.isArray(U)?U:[]);z.has(b)?z.delete(b):z.add(b),Ar(f,Array.from(z)),Br(f);return}if(q){Ar(f,b),Br(f),Od(f);return}if(D){let U=p.getAttribute("aria-pressed")==="true";p.setAttribute("aria-pressed",U?"false":"true"),p.classList.toggle("persona-ask-pill-selected",!U);let z=f.querySelector('[data-ask-user-action="submit-multi"]');z&&(z.disabled=uu(f).length===0);return}Es(f,b,{source:"pick",values:[b]});return}if(y==="submit-multi"){let b=uu(f);if(b.length===0)return;Es(f,b.join(", "),{source:"multi",values:b});return}if(y==="open-free-text"){let b=f.querySelector('[data-ask-free-text-row="true"]');b&&(b.classList.remove("persona-hidden"),b.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(y==="focus-free-text"){f.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let D=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!D.trim())return;if(xr(f)){Ar(f,D.trim()),Br(f),Od(f);return}Es(f,D,{source:"free-text"});return}if(y==="next"||y==="back"){if(!lt.current)return;let b=f.getAttribute("data-tool-call-id")??"",D=lt.current.getMessages().find(oe=>oe.toolCall?.id===b);if(!D)return;let U=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(U){let oe=ps(f)[Yn(f)];(typeof oe!="string"||oe!==U)&&Ar(f,U)}let z=y==="next"?1:-1,X=Yn(f)+z;wc(f,D,o,X),Br(f);return}if(y==="submit-all"){if(!lt.current)return;let b=f.getAttribute("data-tool-call-id")??"",D=lt.current.getMessages().find(oe=>oe.toolCall?.id===b);if(!D)return;let U=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";U&&Ar(f,U);let z=vc(f,D);lt.current.persistAskUserQuestionProgress(D,{answers:z,currentIndex:Yn(f)});let X=yf(z);Es(f,X||"(submitted)",{source:"submit-all",structured:z});return}if(y==="skip"){if(!lt.current)return;let b=f.getAttribute("data-tool-call-id")??"",D=lt.current.getMessages().find(pe=>pe.toolCall?.id===b);if(!D)return;let q=xr(f),U=Yn(f),z=ri(f),X=U>=z-1;if(!q){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),si(Ms,b),D.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(D),lt.current.resolveAskUserQuestion(D,"(dismissed)"));return}Ar(f,"");let oe=f.querySelector('[data-ask-free-text-input="true"]');if(oe&&(oe.value=""),X){let pe=vc(f,D),Xe=yf(pe);Es(f,Xe||"(skipped)",{source:"submit-all",structured:pe});return}wc(f,D,o,U+1),Br(f);return}}),Ms.addEventListener("keydown",r=>{if(r.key!=="Enter")return;let p=r.target;if(!p.matches?.('[data-ask-free-text-input="true"]'))return;let f=p.closest("[data-persona-ask-sheet-for]");if(!f)return;r.preventDefault();let y=p.value;if(y.trim()){if(xr(f)){Ar(f,y.trim()),Br(f),Od(f);return}Es(f,y,{source:"free-text"})}});let bf=r=>{if(!/^[1-9]$/.test(r.key)||r.metaKey||r.ctrlKey||r.altKey)return;let a=r.target;if(a?.tagName==="INPUT"||a?.tagName==="TEXTAREA"||a?.isContentEditable)return;let p=Ms.querySelector("[data-persona-ask-sheet-for]");if(!p||p.getAttribute("data-ask-layout")!=="rows"||p.getAttribute("data-multi-select")==="true")return;let f=Number(r.key),b=p.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[f-1];b&&(r.preventDefault(),b.click())};document.addEventListener("keydown",bf);let ho=null,mt=null,Ri=null,ol=null,rl=()=>{},vf=!1,sl="",il="";function _d(){ol?.(),ol=null}let pw=()=>{let r=Ns&&ts?.isConnected?ts:null,a=r?r.getBoundingClientRect().width:0;return a<=0?200:a+360},Cf=()=>{if(!ho||!mt)return;let r=t.classList.contains("persona-artifact-welded-split"),a=t.ownerDocument.defaultView??window,p=a.innerWidth<=640;if(!r||t.classList.contains("persona-artifact-narrow-host")||p){mt.style.removeProperty("position"),mt.style.removeProperty("left"),mt.style.removeProperty("top"),mt.style.removeProperty("bottom"),mt.style.removeProperty("width"),mt.style.removeProperty("z-index");return}let f=ho.firstElementChild;if(!f||f===mt)return;let y=10;mt.style.position="absolute",mt.style.top="0",mt.style.bottom="0",mt.style.width=`${y}px`,mt.style.zIndex="5";let b=Sg(ho,a),D=f.offsetWidth+b/2-y/2;mt.style.left=`${Math.max(0,D)}px`},al=()=>{},uw=()=>{let r=t.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,p=o.launcher?.mobileBreakpoint??640;return!a||r.innerWidth>p?!1:ce||Lt(o)},ll=()=>!mn(o)||!nl()||t.classList.contains("persona-artifact-narrow-host")||uw()||(t.ownerDocument.defaultView??window).innerWidth<wT?"none":vg(o)?"detached":"welded",oo=()=>{if(!qe||!mn(o))return;Ua(t,o),$a(t,o),al();let r=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,a=we.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",a>0&&a<=r);let p=nl();qe.setVisible(p),qe.update($n),Wo?(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),no=!1,Hi=!1):$n.artifacts.length>0&&hf()?(qe.element.classList.remove("persona-hidden"),qe.setMobileOpen(!0)):(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),no=!1,Hi=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(qe.setExpandToggleVisible(f),qe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),qe.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),qe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),qe.setTabFade(o.features?.artifacts?.layout?.tabFade),qe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!Hi&&(no=!1),no!==vf){let b=qe.element;no?(sl=b.style.width,il=b.style.maxWidth,b.style.removeProperty("width"),b.style.removeProperty("max-width")):(sl&&(b.style.width=sl),il&&(b.style.maxWidth=il),sl="",il=""),vf=no}t.classList.toggle("persona-artifact-expanded",no),qe.setExpanded(no);let y=ll();y!==Li&&(Li=y,Wr()),rl()};if(mn(o)){we.style.position="relative";let r=k("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),a=k("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");r.appendChild(de),ho=a,a.appendChild(r),we.appendChild(a);let p=y=>{mf||qe||(qe=y.createArtifactPane(o,{onSelect:b=>lt.current?.selectArtifact(b),onDismiss:()=>{Wo=!0,oo()},onToggleExpand:()=>{let b=!no,D=$n.selectedId??$n.artifacts[$n.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:D,expanded:b})!==!0&&(no=b,b||(Hi=!1),oo())}}),qe.element.classList.add("persona-hidden"),a.appendChild(qe.element),qe.backdrop&&we.appendChild(qe.backdrop),rl(),oo())},f=er();f?p(f):(yg(()=>{let y=er();y&&p(y)}),ud().catch(()=>{})),rl=()=>{if(!ho||!qe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ri?.(),Ri=null,_d(),mt&&(mt.remove(),mt=null),qe.element.style.removeProperty("width"),qe.element.style.removeProperty("maxWidth");return}if(!mt){let b=k("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");b.setAttribute("role","separator"),b.setAttribute("aria-orientation","vertical"),b.setAttribute("aria-label","Resize artifacts panel"),b.tabIndex=0;let D=t.ownerDocument,q=D.defaultView??window,U=z=>{if(!qe||z.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||q.innerWidth<=640)return;z.preventDefault(),_d();let X=z.clientX,oe=qe.element.getBoundingClientRect().width,pe=o.features?.artifacts?.layout,Xe=ut=>{let Vt=ho.getBoundingClientRect().width,Dt=t.classList.contains("persona-artifact-welded-split"),At=Sg(ho,q),nn=Dt?0:b.getBoundingClientRect().width||6,Je=oe-(ut.clientX-X),on=rC(Je,Vt,At,nn,pe?.resizableMinWidth,pe?.resizableMaxWidth,pw());qe.element.style.width=`${on}px`,qe.element.style.maxWidth="none",Cf()},ct=()=>{D.removeEventListener("pointermove",Xe),D.removeEventListener("pointerup",ct),D.removeEventListener("pointercancel",ct),ol=null;try{b.releasePointerCapture(z.pointerId)}catch{}};ol=ct,D.addEventListener("pointermove",Xe),D.addEventListener("pointerup",ct),D.addEventListener("pointercancel",ct);try{b.setPointerCapture(z.pointerId)}catch{}};b.addEventListener("pointerdown",U),mt=b,ho.insertBefore(b,qe.element),Ri=()=>{b.removeEventListener("pointerdown",U)}}if(mt){let b=nl();mt.classList.toggle("persona-hidden",!b),Cf()}},al=()=>{if(!ce||!qe||(o.launcher?.sidebarMode??!1)||Lt(o)&&Jn(o).reveal==="emerge")return;let b=t.ownerDocument.defaultView??window,D=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640;if(D&&b.innerWidth<=q||!Jv(o,ce))return;let U=o.launcher?.width??o.launcherWidth??Jo,z=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";nl()?(we.style.width=z,we.style.maxWidth=z):(we.style.width=U,we.style.maxWidth=U)},typeof ResizeObserver<"u"&&(Ii=new ResizeObserver(()=>{oo()}),Ii.observe(we))}else we.appendChild(de);Le()&&jt&&(Be.peekBanner&&jt.appendChild(Be.peekBanner),jt.appendChild(Ie)),t.appendChild(Ke),jt&&t.appendChild(jt);let Nd=()=>{if(Le()){we.style.width="100%",we.style.maxWidth="100%";let De=o.launcher?.composerBar??{},Ce=Ke.dataset.state==="expanded",sn=De.expandedSize??"anchored";if(!(Ce&&sn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let An=o.theme?.components?.panel,Mn=di(o),it=(It,En)=>It==null||It===""?En:un(Mn,It)??It,dt="1px solid var(--persona-border)",We="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Go="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=it(An?.border,dt),de.style.borderRadius=it(An?.borderRadius,Go),de.style.boxShadow=it(An?.shadow,We),de.style.overflow="hidden";return}let r=Lt(o),a=o.launcher?.sidebarMode??!1,p=r||a||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,y=o.launcher?.detachedPanel===!0,b=o.theme?.components?.panel,D=di(o),q=(De,Ce)=>De==null||De===""?Ce:un(D,De)??De,U=t.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,oe=U.innerWidth<=X,pe=z&&oe&&ce,Xe=r&&z&&oe,ct=o.launcher?.position??"bottom-left",ut=ct==="bottom-left"||ct==="top-left",Vt=o.launcher?.zIndex??an,Dt="var(--persona-panel-border, 1px solid var(--persona-border))",At="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",nn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Je=y&&!pe&&!Xe;Je?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let on=Je?Dt:a||pe?"none":Dt,xo=Je?At:pe?"none":a?ut?"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))":f?"none":At;r&&!pe&&!Je&&(xo="none",on="none");let Ko=Je?nn:a||pe?"0":nn,io=q(b?.border,on),aa=q(b?.shadow,xo),as=q(b?.borderRadius,Ko),ao=ll(),Yt=ao==="detached",lo=ao==="welded";t.classList.toggle("persona-artifact-detached-split",Yt),t.classList.toggle("persona-artifact-welded-split",lo);let Xs="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=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&mn(o)&&vg(o)&&f&&!r;t.classList.toggle("persona-artifact-chat-flush",Se);let se=Yt||Se?"none":aa,Mt=Yt?Dt:lo?"none":io,Ot=Yt?nn:as;Se&&(Mt="none",Ot="0");let Jt=b?.borderRadius!=null&&b.borderRadius!=="",_t=Se&&!Jt?"0":as,$t=te.scrollTop;t.style.cssText="",Ke.style.cssText="",we.style.cssText="",de.style.cssText="",te.style.cssText="",xs||(Ie.style.cssText=""),zt&&(te.style.display="none"),(p||f)&&(t.style.minWidth="0");let Et=()=>{if($t<=0)return;(te.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(te.scrollTop===$t)return;let Ce=te.scrollHeight-te.clientHeight;Ce<=0||(te.scrollTop=Math.min($t,Ce))})};if(pe){Ke.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"),Ke.style.cssText=`
|
|
35
35
|
position: fixed !important;
|
|
36
36
|
inset: 0 !important;
|
|
37
37
|
width: 100% !important;
|
|
@@ -67,7 +67,7 @@ _Details: ${n.message}_`:o}var xu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
67
67
|
overflow: hidden !important;
|
|
68
68
|
border-radius: 0 !important;
|
|
69
69
|
border: none !important;
|
|
70
|
-
`,te.style.flex="1 1 0%",te.style.minHeight="0",te.style.overflowY="auto",Ie.style.flexShrink="0",Ed(),qt=!0,Et();return}let He=o?.launcher?.width??o?.launcherWidth??Jo;if(!a&&!r)f&&p?(we.style.width="100%",we.style.maxWidth="100%"):(we.style.width=He,we.style.maxWidth=He);else if(r)if(
|
|
70
|
+
`,te.style.flex="1 1 0%",te.style.minHeight="0",te.style.overflowY="auto",Ie.style.flexShrink="0",Ed(),qt=!0,Et();return}let He=o?.launcher?.width??o?.launcherWidth??Jo;if(!a&&!r)f&&p?(we.style.width="100%",we.style.maxWidth="100%"):(we.style.width=He,we.style.maxWidth=He);else if(r)if(Jn(o).reveal==="emerge"&&!y){let Ce=Jn(o).width;we.style.width=Ce,we.style.maxWidth=Ce}else we.style.width="100%",we.style.maxWidth="100%";if(al(),we.style.boxShadow=se,we.style.borderRadius=_t,Yt?we.style.border="none":lo&&(we.style.border=io),de.style.border=Mt,de.style.borderRadius=Ot,de.style.boxShadow=Yt&&!Se?Xs:"",Se&&(de.style.background="transparent",te.style.background="transparent",Ie.style.background="transparent",Ie.style.borderTop="none"),lo){let De=o.features?.artifacts?.layout;tl=De?.unifiedSplitOuterRadius?.trim()||De?.paneBorderRadius?.trim()||as}else tl=null;if(r&&!pe&&!Je&&!Yt&&!lo&&b?.border===void 0&&(de.style.border="none",Jn(o).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.style.borderRight="1px solid var(--persona-border)"),r&&!pe&&lo&&b?.border===void 0&&(Jn(o).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),p&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",f&&(t.style.width="100%"),Ke.style.display="flex",Ke.style.flexDirection="column",Ke.style.flex="1 1 0%",Ke.style.minHeight="0",Ke.style.maxHeight="100%",Ke.style.height="100%",f&&(Ke.style.overflow="hidden"),we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.height="100%",Yt||(we.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",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.overflowY="auto",Ie.style.flexShrink="0"),f&&(Je||Yt||Se)&&!r&&(Se||(Ke.style.padding="var(--persona-panel-inset)"),Ke.style.background="var(--persona-panel-canvas-bg)"),Ke.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"),!a&&!f&&!r&&(Fn[ct]??Fn["bottom-right"]).split(" ").forEach(Ce=>Ke.classList.add(Ce)),a){let De=o.launcher?.sidebarWidth??"420px";y?Ke.style.cssText=`
|
|
71
71
|
position: fixed !important;
|
|
72
72
|
top: var(--persona-panel-inset) !important;
|
|
73
73
|
bottom: var(--persona-panel-inset) !important;
|
|
@@ -106,7 +106,7 @@ _Details: ${n.message}_`:o}var xu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
106
106
|
padding: 0 !important;
|
|
107
107
|
box-shadow: ${se} !important;
|
|
108
108
|
border-radius: ${_t} !important;
|
|
109
|
-
${Yt?"border: none !important;":
|
|
109
|
+
${Yt?"border: none !important;":lo?`border: ${io} !important;`:""}
|
|
110
110
|
`,we.style.setProperty("width","100%","important"),we.style.setProperty("max-width","100%","important"),de.style.cssText=`
|
|
111
111
|
display: flex !important;
|
|
112
112
|
flex-direction: column !important;
|
|
@@ -125,7 +125,7 @@ _Details: ${n.message}_`:o}var xu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
125
125
|
border-top: none !important;
|
|
126
126
|
padding: 8px 16px 12px 16px !important;
|
|
127
127
|
${Se?"background: transparent !important;":""}
|
|
128
|
-
`)}if(!f&&!r){let De="max-height: -moz-available !important; max-height: stretch !important;",Ce=a?"":"padding-top: 1.25em !important;",sn=a?"":`z-index: ${o.launcher?.zIndex??an} !important;`;Ke.style.cssText+=De+Ce+sn}Ed(),Et()},Fd=()=>{t.style.setProperty("--persona-content-max-width",kr(o,Le()))},wf=!1,Sf=()=>{let r=qu(o,Le());Le()&&o.composer?.placement&&o.debug===!0&&!wf&&(wf=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let a=Zo(o);t.setAttribute("data-persona-composer-placement",r),t.setAttribute("data-persona-conversation-state",Xa),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",a.composerGap??Kc),Ja()},xf=()=>{if(Le())return;let r=Lt(o),a=o.launcher?.sidebarMode??!1;if(r||a||(o.launcher?.fullHeight??!1)||!ce)return;let f=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,v=o.launcher?.mobileBreakpoint??640;if(y&&f.innerWidth<=v)return;let B=f.innerHeight,$=64,F=o.launcher?.heightOffset??0,q=Math.max(200,B-$),X=Math.min(640,q);we.style.height=`${Math.max(200,X-F)}px`};Nd(),Ia(t,o),Ua(t,o),$a(t,o),Fd(),Sf(),Wr=()=>{Nd(),xf(),Ia(t,o),Ua(t,o),$a(t,o),Fd(),Sf(),tl?t.style.setProperty("--persona-artifact-welded-outer-radius",tl):t.style.removeProperty("--persona-artifact-welded-outer-radius"),Io(),vd()};let fe=[];fe.push(()=>{mf=!0}),fe.push(()=>{d.forEach(r=>r()),c.destroy()}),fe.push(()=>{document.removeEventListener("keydown",bf)}),fe.push(()=>{Ti!==null&&clearTimeout(Ti)});let ho=null,yo=null;fe.push(()=>{ho?.(),ho=null,yo?.(),yo=null}),Ii&&fe.push(()=>{Ii?.disconnect(),Ii=null}),fe.push(()=>{Ri?.(),Ri=null,_d(),mt&&(mt.remove(),mt=null),qe?.element.style.removeProperty("width"),qe?.element.style.removeProperty("maxWidth"),qe?.destroy()}),C&&fe.push(()=>{$e=!0,Ve=null,kt!==null&&(cancelAnimationFrame(kt),kt=null),gt?.destroy(),gt=null,Re?.destroy(),Re=null,Me=null});let Dr=null,Af=()=>{Dr&&(Dr(),Dr=null),o.colorScheme==="auto"&&(Dr=Vc(()=>{Ia(t,o)}))};Af(),fe.push(()=>{Dr&&(Dr(),Dr=null)}),fe.push(()=>{x=!0,h?.()}),fe.push(()=>{I=!0});let Mf=!1;fe.push(()=>{Mf=!0});let Ud=(r,a)=>{let p=ua(r,a);return p||!Jh.includes(r)?p:(hv().then(f=>{if(Mf)return;ou(f.wipe),ou(f.glyphCycle);let y=ua(r,a);y&&ma(y,t)}).catch(()=>{}),null)},cl=o.features?.streamAnimation;if(cl?.type&&cl.type!=="none"){let r=Ud(cl.type,cl.plugins);r&&ma(r,t),fe.push(()=>Zh(t))}let Wo=Da(or),Ef=Da(wd),Tf=Da(xi),Or=[Wo,Ef,Tf];fe.push(()=>{Or.forEach(r=>r.destroy())});let _r=null,E,Nr=null,kf=!1,Pf=0,If=null,Lf=r=>r.reduce((a,p)=>p.role==="user"?a+1:a,0),Hf=r=>{for(let a=r.length-1;a>=0;a--)if(va(r[a]))return r[a].id??null;return null},Rf=!1,gw=()=>{Rf||o.debug!==!0||(Rf=!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".'))},Wf=!1,Bf=!1,Df=(r,a)=>{Wf||o.debug!==!0||!a.enabled||a.expose||kf||Bf&&(E.isStreaming()||r.some(va)||(Wf=!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.")))},Ts=r=>{if(!E)return;let a=r??E.getMessages(),p=q=>{q.render([],E,le,a)},f=q=>{Or.forEach(X=>{X!==q&&p(X)})};Nr&&(Lf(a)>Pf||Hf(a)!==If)&&(Nr=null);let y=Er(o);Df(a,y);let v=y.enabled?Ly(a):null,B=Nr??v,$=Nr?"host":"agent";if(B){let q=o.suggestions?.followUps,X=q?.placement??(q?"auto":"composer"),pe=(X==="auto"?Le()?"composer":"after-message":X)==="after-message"?Tf:Wo;f(pe),pe.render(B,E,le,a,o.suggestionChipsConfig,{source:$,surface:"followUp",variant:q?.variant??"chip",behavior:q?.behavior??"send",overflow:q?.overflow??"wrap",maxItems:q?.maxItems??4,config:o,plugins:l,submitPrompt:Xl});return}if(a.some(q=>q.role==="user")){Or.forEach(p);return}let F=o.suggestions?.starters;if(F){let q=fi(Zo(o),a),X=F.placement??"auto",oe=X==="auto"?q?"welcome":"composer":X;if(oe==="welcome"&&!q){gw(),Or.forEach(p);return}let pe=oe==="welcome"?Ef:Wo;f(pe),pe.render(F.items??o.suggestionChips,E,le,a,o.suggestionChipsConfig,{surface:"starter",variant:F.variant??"card",behavior:F.behavior??"send",overflow:F.overflow??"wrap",maxItems:F.maxItems??4,config:o,plugins:l,submitPrompt:Xl});return}f(Wo),Wo.render(o.suggestionChips,E,le,a,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:l,submitPrompt:Xl})},Of=()=>{Nr&&(Nr=null,Ts())},fw=r=>{let a=Array.isArray(r)?[...r]:[];if(!a.length){Of();return}let p=E?E.getMessages():[];Nr=a,kf=!0,Pf=Lf(p),If=Hf(p),Ts(p)},Rn=!1,Wt=uv(),ks=new Map,Fr=new Map,cr=new Map,Ur=null,dr=null;function $r(){if(!Ur)return;let r=Ur;Ur=null,dr?.destroy(),dr=null,Wt.delete(r),de.querySelector(`#wrapper-${r}`)?.removeAttribute("data-preserve-runtime"),E&&qn(ke,E.getMessages(),vt)}let qr=0,mw=Ys()!==null,Wn=Kh(),Bn=0,pr=null,Cn=!1,dl=!1,ur=0,Ft=null,zr=null,$d=!1,Ps=!1,jr=null,Wi=!0,pl=!1,Is=null,ul=!1,Vr=()=>{ul=!0,vw()},qd=null,hw=4,Bo=24,yw=80,bw=1e3,Do=null,_f=()=>{t.setAttribute("data-persona-scrollbar",xd()),xd()!=="on-scroll"&&(Do!==null&&clearTimeout(Do),Do=null,te.removeAttribute("data-persona-scrollbar-visible"))},vw=()=>{xd()==="on-scroll"&&(te.setAttribute("data-persona-scrollbar-visible",""),Do!==null&&clearTimeout(Do),Do=setTimeout(()=>{Do=null,cs(te,Bo)&&te.removeAttribute("data-persona-scrollbar-visible")},bw))};_f(),fe.push(()=>{Do!==null&&clearTimeout(Do)});let zd=new Map,ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};lf=()=>ze.active,eo();let Nf=o.voiceRecognition?.autoResume??!1,Oo=r=>{w.emit("voice:state",{active:ze.active,source:r,timestamp:Date.now()})},oo=()=>{re(r=>({...r,voiceState:{active:ze.active,timestamp:Date.now(),manuallyDeactivated:ze.manuallyDeactivated}}))},Cw=()=>{if(o.voiceRecognition?.enabled===!1)return;let r=Hg(Z.voiceState),a=!!r.active,p=Number(r.timestamp??0);ze.manuallyDeactivated=!!r.manuallyDeactivated,a&&Date.now()-p<CT&&setTimeout(()=>{ze.active||(ze.manuallyDeactivated=!1,Tn(o.voiceRecognition?.provider)?E.toggleVoice().then(()=>{ze.active=E.isVoiceActive(),Oo("restore"),E.isVoiceActive()&&Gs()}):Zl("restore"))},1e3)},ww=()=>E?kC(E.getMessages()).filter(r=>!r.__skipPersist):[],gl=null,Ff=(r,a)=>{typeof console<"u"&&console.error(r,a)},fl=(r,a)=>{let p=()=>{try{let B=r();return!B||typeof B.then!="function"?null:Promise.resolve(B).catch($=>{Ff(a,$)})}catch(B){return Ff(a,B),null}},f=gl,y=f?f.then(()=>p()??void 0):p();if(!y)return;let v=y.finally(()=>{gl===v&&(gl=null)});gl=v};function Ls(r){if(!K?.save)return;let a=r?kC(r):E?ww():[],p=ie&&E?.getResumableHandle();p&&(Z={...Z,durableResume:{executionId:p.executionId,after:p.lastEventId}});let f={messages:a,metadata:Z,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId,...Kr?{draft:Kr}:{}};fl(()=>K.save(f),"[AgentWidget] Failed to persist state:")}let Kr,ml=()=>!K?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Bi=qb({write:()=>{if(!ml())return;let r=be.getState(),a=Ub({text:r.text,mentionRefs:r.mentionRefs,contentSegments:Fp(),selectedModelId:r.selectedModelId,activeModeIds:r.activeModeIds,quote:r.quote});JSON.stringify(a)!==JSON.stringify(Kr)&&(Kr=a,Ls())}});function Uf(){ml()&&Bi.schedule()}function jd(){Bi.flush()}function $f(r){if(!ml())return;let a=$b(r,{mentionSourceIds:(o.contextMentions?.sources??[]).map(p=>p.id),modelIds:(o.composer?.models??[]).map(p=>p.id),modes:o.composer?.modes??[]});a&&(Kr=r,le&&!le.value&&(le.value=a.text,le.dispatchEvent(new Event("input",{bubbles:!0})),uo()),a.selectedModelId&&(be.setSelectedModelId(a.selectedModelId),ir?.repaint()),Za(a.activeModeIds??[]),a.quote&&go(a.quote),Bi.cancel())}function hl(){Bi.cancel(),Kr&&(Kr=void 0,ml()&&Ls())}let Hs=null,qf=()=>Ke.querySelector("#persona-scroll-container")||te,Rs=()=>{Hs!==null&&(cancelAnimationFrame(Hs),Hs=null),Cn=!1},zf=()=>{pr!==null&&(cancelAnimationFrame(pr),pr=null),dl=!1,Rs()},Sw=()=>Rn&&Kd()&&(Hn()!=="anchor-top"||zg()),Vd=()=>{let r=Ai()||"Jump to latest",a=Sw();Rt.toggleAttribute("data-persona-scroll-to-bottom-streaming",a),ur>0?(Lr.textContent=String(ur),Lr.style.display="",Rt.setAttribute("aria-label",`${r} (${ur} new)`)):(Lr.textContent="",Lr.style.display="none",Rt.setAttribute("aria-label",a?`${r} (response streaming below)`:r))},jf=()=>{ur!==0&&(ur=0,Vd())},xw=()=>{let r=Ft?.spacerHeight??0;return r<=0?cs(te,Bo):Cl(r)-te.scrollTop-te.clientHeight<=Bo},Kd=()=>sr()?!Wn.isFollowing():!xw(),Gd=()=>!!E&&E.getMessages().length>0,Ut=()=>{if(!YC()||qC()){Rt.parentNode&&Rt.remove(),Rt.style.display="none";return}Rt.parentNode!==de&&de.appendChild(Rt),Hr();let a=Qo(te)>0&&Kd()&&Gd();a?Vd():jf(),Rt.style.display=a?"":"none"},Di=()=>{Wn.pause()&&(zf(),Ut())},wn=()=>{Wn.resume(),jf(),Ut()},gr=(r=!1)=>{sr()&&Gd()&&Wn.isFollowing()&&(!r&&!Rn||(pr!==null&&(cancelAnimationFrame(pr),pr=null),dl=!0,pr=requestAnimationFrame(()=>{pr=null,dl=!1,Wn.isFollowing()&&Aw(qf(),r?220:140)})))},Vf=(r,a,p,f=()=>!0)=>{let y=r.scrollTop,v=a(),B=v-y;if(Rs(),Math.abs(B)<1){Cn=!0,r.scrollTop=v,Bn=r.scrollTop,Cn=!1;return}let $=performance.now();Cn=!0;let F=X=>1-Math.pow(1-X,3),q=X=>{if(!f()){Rs();return}let oe=a();oe!==v&&(v=oe,B=v-y);let pe=X-$,Xe=Math.min(pe/p,1),ct=F(Xe),ut=y+B*ct;r.scrollTop=ut,Bn=r.scrollTop,Xe<1?Hs=requestAnimationFrame(q):(r.scrollTop=v,Bn=r.scrollTop,Hs=null,Cn=!1)};Hs=requestAnimationFrame(q)},Aw=(r,a=500)=>{let p=Qo(r)-r.scrollTop;if(Math.abs(p)<1){Bn=r.scrollTop;return}if(Math.abs(p)>=yw){Rs(),Cn=!0,r.scrollTop=Qo(r),Bn=r.scrollTop,Cn=!1;return}Vf(r,()=>Qo(r),a,()=>Wn.isFollowing())},yl=()=>{if(!Gd()){Ut();return}let r=qf();Cn=!0,r.scrollTop=Qo(r),Bn=r.scrollTop,Cn=!1,Ut()},Gr=r=>{let a=0,p=r;for(;p&&p!==te;)a+=p.offsetTop,p=p.offsetParent;return a},Mw=()=>{let r=te.getRootNode();return(typeof r.getSelection=="function"?r.getSelection():null)??te.ownerDocument.getSelection()},bl=()=>Xh(Mw(),te),Qd=()=>{if(JC()!=="last-user-turn")return!1;let r=E?.getMessages()??[];if(r.length<2)return!1;let a=[...r].reverse().find(v=>v.role==="user");if(!a)return!1;let p=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a.id):a.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=te.querySelector(`[data-message-id="${p}"]`);if(!f)return!1;let y=Math.min(Math.max(0,Gr(f)-Mi()),Qo(te));return Cn=!0,te.scrollTop=y,Bn=te.scrollTop,Cn=!1,Hn()==="follow"&&!cs(te,Bo)&&Wn.pause(),Ut(),!0},vl=r=>{let a=Math.max(0,Math.round(r));Un.style.height=`${a}px`,Un.style.display=a>0?"":"none",Ft&&(Ft.spacerHeight=Math.max(0,r))},Cl=r=>{let a=parseFloat(getComputedStyle(te).paddingBottom)||0,p=0;for(let y of Array.from(te.children)){if(y===Un||y.offsetHeight===0)continue;let v=Gr(y)+y.offsetHeight;v>p&&(p=v)}let f=te.scrollHeight-r;return p>0?Math.min(p+a,f):f},Ew=()=>{if(!Ft||Ft.spacerHeight<=0)return;let r=Cl(Ft.spacerHeight),a=Math.max(0,Math.round(te.scrollTop)+te.clientHeight-r+Bo);a<Ft.spacerHeight&&(vl(a),Ut())},ro=()=>{zr!==null&&(cancelAnimationFrame(zr),zr=null),Rs(),Ft=null,Un.style.height="0px",Un.style.display="none"},Kf=r=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Xd=r=>te.querySelector(`[data-message-id="${Kf(r)}"]`),Gf=r=>{zr!==null&&cancelAnimationFrame(zr),zr=requestAnimationFrame(()=>{zr=null;let a=Kf(r),p=te.querySelector(`[data-message-id="${a}"]`);if(!p)return;let f=Gr(p),y=Ft?.spacerHeight??0,v=Cl(y),{targetScrollTop:B,spacerHeight:$}=nu({anchorOffsetTop:f,topOffset:Mi(),viewportHeight:te.clientHeight,contentHeight:v,slack:Bo});Ft={initialSpacerHeight:$,contentHeightAtAnchor:v,spacerHeight:$},vl($),Vf(te,()=>p.isConnected?Math.max(0,Gr(p)-Mi()):B,220)})},Sn=()=>{if(Hn()!=="anchor-top"||!Ft||!Is)return;let r=Xd(Is);if(!r)return;Rs();let a=Ft.spacerHeight,p=Cl(a),{targetScrollTop:f,spacerHeight:y}=nu({anchorOffsetTop:Gr(r),topOffset:Mi(),viewportHeight:te.clientHeight,contentHeight:p,slack:Bo});Ft={initialSpacerHeight:y,contentHeightAtAnchor:p,spacerHeight:y},vl(y),Cn=!0,te.scrollTop=f,Bn=te.scrollTop,Cn=!1,Ut()},Tw=()=>{if(sr()){if(!Wn.isFollowing()||cs(te,1))return;gr(!Rn);return}if(Ft&&Ft.initialSpacerHeight>0){let r=te.scrollHeight-Ft.spacerHeight,a=Yh({initialSpacerHeight:Ft.initialSpacerHeight,contentHeightAtAnchor:Ft.contentHeightAtAnchor,currentContentHeight:r});a!==Ft.spacerHeight&&vl(a)}Ut()},kw=r=>{let a=Hn();a==="follow"?(wn(),gr(!0)):a==="anchor-top"&&(Wi=!1,pl=!0,ul=!1,Is=r,Gf(r))},Pw=()=>{if(Hn()==="anchor-top"){if(pl){Wi=!1;return}Wi=!0,ro(),wn(),gr(!0)}},Iw=96,Lw=r=>{if(jr===null)return!0;let a=Xd(jr),p=Xd(r);if(!a||!p)return!0;let f=Gr(p)-Gr(a);return Mi()+f>te.clientHeight-Iw},Hw=r=>{if(Hn()!=="anchor-top"||!pl||ul||bl())return;let a=jr===null;for(let p of r){if(!a){p.id===jr&&(a=!0);continue}if(Vh(p)){if(p.id===Is||!Lw(p.id))return;Is=p.id,Gf(p.id);return}}},Rw=r=>{let a=new Map;r.forEach(p=>{let f=zd.get(p.id);a.set(p.id,{streaming:p.streaming,role:p.role}),!f&&p.role==="assistant"&&(w.emit("assistant:message",p),!Ps&&(Hn()!=="anchor-top"||zg())&&Kd()&&(ur+=1,Vd(),Ut(),Qa(ur===1?"1 new message below.":`${ur} new messages below.`))),p.role==="assistant"&&f?.streaming&&p.streaming===!1&&w.emit("assistant:complete",p),p.variant==="approval"&&p.approval&&(f?p.approval.status!=="pending"&&w.emit("approval:resolved",{approval:p.approval,decision:p.approval.status}):w.emit("approval:requested",{approval:p.approval,message:p}))}),zd.clear(),a.forEach((p,f)=>{zd.set(f,p)})},Oi=(r,a)=>{let p=a==="user"?"user":"assistant",f=o.layout?.messages?.[p],y=f?.width??"content",v=f?.maxWidth??(y==="full"?"100%":void 0);r.classList.add("persona-message-row"),r.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),r.classList.add(`persona-message-row-${a}`,`persona-message-width-${y}`),r.classList.toggle("persona-justify-end",a==="user"),r.setAttribute("data-message-role",a),r.setAttribute("data-message-width",y),v?r.style.setProperty("--persona-message-row-max-width",v):r.style.removeProperty("--persona-message-row-max-width")},_o=(r,a)=>{let p=document.createElement("div");return p.className="persona-flex",p.id=`wrapper-${r}`,p.setAttribute("data-wrapper-id",r),Oi(p,a),p},Ww=(r,a,p)=>{let f=document.createElement("div"),v=(()=>{let P=l.find(Ne=>Ne.renderLoadingIndicator);if(P?.renderLoadingIndicator)return P.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),B=(P,Ne)=>Ne==null?!1:typeof Ne=="string"?(P.textContent=Ne,!0):(P.appendChild(Ne),!0),$=new Set,F=new Map,q=new Set,X=l.some(P=>P.renderAskUserQuestion),oe=[],pe=[],Xe=o.enableComponentStreaming!==!1,ct=o.approval!==!1,ut=[],Vt=o.messageActions,Dt=Vt?.showRegenerate===!0&&Vt.enabled!==!1&<.current?.isStreaming()!==!0?Zy(a):null,At=Vt?.showEdit===!0&&Vt.enabled!==!1,nn=Vt?.showQuote===!0&&Vt.enabled!==!1,Je=null,on=o.features?.reasoningDisplay?.completedVisibility,So=P=>on==="removed"?!0:on==="removed-when-short"?Lh(P,o.features?.reasoningDisplay?.shortThinkThreshold):!1,Ko=o.features?.toolCallDisplay?.completedVisibility==="removed",so=P=>P.variant==="reasoning"&&P.reasoning?.status==="complete"?So(P.reasoning):Ko&&P.variant==="tool"&&P.toolCall?.status==="complete";if(a.forEach(P=>{if(so(P))return;if($.add(P.id),F.set(P.id,P.role),Ur===P.id&&dr){let Ce=_o(P.id,P.role);Ce.setAttribute("data-persona-message-edit-stub","true"),Ce.setAttribute("data-preserve-runtime","true"),f.appendChild(Ce),Je={messageId:P.id,element:dr.element};return}let Ne=X&&ds(P),Se=ct&&P.variant==="approval"&&!!P.approval,se=!Ne&&P.role==="assistant"&&!P.variant&&Xe&&Lg(P);!Se&&cr.has(P.id)&&(r.querySelector(`#wrapper-${P.id}`)?.removeAttribute("data-preserve-runtime"),cr.delete(P.id)),!se&&Fr.has(P.id)&&(r.querySelector(`#wrapper-${P.id}`)?.removeAttribute("data-preserve-runtime"),Fr.delete(P.id));let Mt=ds(P)?`:${P.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${P.agentMetadata?.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot={canRegenerate:Dt===P.id,canEdit:At&&yu(P),canQuote:nn&&!P.variant&&(P.content?.trim().length??0)>0},Jt=`${Ot.canRegenerate?"r":""}${Ot.canEdit?"e":""}${Ot.canQuote?"q":""}`,_t=pv(P,qr)+Mt+`:${Jt}`,$t=Ne||Se||se?null:gv(Wt,P.id,_t);if($t){f.appendChild($t.cloneNode(!0)),ds(P)&&P.toolCall?.id&&P.agentMetadata?.awaitingLocalTool===!0&&!P.agentMetadata?.askUserQuestionAnswered&&(q.add(P.toolCall.id),Cc(P,o,Be.composerOverlay));return}let Et=null,rn=l.find(Ce=>!!(P.variant==="reasoning"&&Ce.renderReasoning||P.variant==="tool"&&Ce.renderToolCall||!P.variant&&Ce.renderMessage)),He=o.layout?.messages;if(ds(P)&&P.agentMetadata?.askUserQuestionAnswered===!0){ks.delete(P.id),r.querySelector(`#wrapper-${P.id}`)?.removeAttribute("data-preserve-runtime");return}if(va(P)&&Er(o).enabled)return;if(ds(P)&&o.features?.askUserQuestion?.enabled!==!1){let Ce=l.find(sn=>typeof sn.renderAskUserQuestion=="function");if(Ce&<.current){let sn=ks.get(P.id),Cr=sn!==_t,An=null;if(Cr){let{payload:dt,complete:We}=oi(P),Go=P.id,It=()=>lt.current?.getMessages().find(En=>En.id===Go);An=Ce.renderAskUserQuestion({message:P,payload:dt,complete:We,resolve:En=>{let la=It();la&<.current?.resolveAskUserQuestion(la,En)},dismiss:()=>{let En=It();En?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(En),lt.current?.resolveAskUserQuestion(En,"(dismissed)"))},config:o})}let Mn=sn!=null;if(Cr&&An===null&&!Mn){P.agentMetadata?.awaitingLocalTool===!0&&!P.agentMetadata?.askUserQuestionAnswered&&(q.add(P.toolCall.id),Cc(P,o,Be.composerOverlay));return}let it=_o(P.id,P.role);it.setAttribute("data-ask-plugin-stub","true"),it.setAttribute("data-preserve-runtime","true"),f.appendChild(it),oe.push({messageId:P.id,fingerprint:_t,bubble:An});return}else{P.agentMetadata?.awaitingLocalTool===!0&&!P.agentMetadata?.askUserQuestionAnswered&&(q.add(P.toolCall.id),Cc(P,o,Be.composerOverlay));return}}else if(Se){let Ce=O();if(!Ce){f.appendChild(_o(P.id,P.role));return}let sn=l.find(it=>typeof it.renderApproval=="function")??b,An=cr.get(P.id)!==_t,Mn=null;if(An&&sn?.renderApproval){let it=P.id,dt=(We,Go)=>{let It=lt.current?.getMessages().find(En=>En.id===it);It?.approval&&(It.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(It.id,We):lt.current?.resolveApproval(It.approval,We,Go))};Mn=sn.renderApproval({message:P,defaultRenderer:()=>Ce.createApprovalBubble(P,o),config:o,approve:We=>dt("approved",We),deny:We=>dt("denied",We)})}if(An&&Mn===null)r.querySelector(`#wrapper-${P.id}`)?.removeAttribute("data-preserve-runtime"),cr.delete(P.id),Et=Ce.createApprovalBubble(P,o);else{let it=_o(P.id,P.role);it.setAttribute("data-approval-plugin-stub","true"),it.setAttribute("data-preserve-runtime","true"),f.appendChild(it),ut.push({messageId:P.id,fingerprint:_t,bubble:Mn});return}}else if(rn)if(P.variant==="reasoning"&&P.reasoning&&rn.renderReasoning){if(!Po)return;Et=rn.renderReasoning({message:P,defaultRenderer:()=>ug(P,o),config:o})}else if(P.variant==="tool"&&P.toolCall&&rn.renderToolCall){if(!j)return;Et=rn.renderToolCall({message:P,defaultRenderer:()=>fg(P,o),config:o})}else rn.renderMessage&&(Et=rn.renderMessage({message:P,defaultRenderer:()=>{let Ce=tg(P,p,He,o.messageActions,ys,{loadingIndicatorRenderer:v,widgetConfig:o,actionEligibility:Ot});return P.role!=="user"&&H(Ce,P,o,E),Ce},config:o}));if(!Et&&se){let Ce=SC(P);if(Ce){let sn=Fr.get(P.id),Cr=sn!==_t,An=o.wrapComponentDirectiveInBubble!==!1&&Xo.getOptions(Ce.component)?.bubbleChrome!==!1,Mn=null;if(Cr){let it=CC(Ce,{config:o,message:P,transform:p});if(it&&Ce.component==="PersonaArtifactInline"){let dt=it.hasAttribute("data-artifact-inline")?it:it.querySelector("[data-artifact-inline]"),We=dt?.getAttribute("data-artifact-inline")??"",Go=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(We):We,It=We?r.querySelector(`#wrapper-${P.id}`)?.querySelector(`[data-artifact-inline="${Go}"]`)??null:null;dt&&It&&It!==dt&&er()?.hasLiveInlineArtifactBlock(It)&&(dt===it?it=It:dt.replaceWith(It))}if(it)if(An){let dt=document.createElement("div");if(dt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),dt.id=`bubble-${P.id}`,dt.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let We=document.createElement("div");We.className="persona-mb-3 persona-text-sm persona-leading-relaxed",We.innerHTML=p({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),dt.appendChild(We)}dt.appendChild(it),Mn=dt}else{let dt=document.createElement("div");if(dt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",dt.id=`bubble-${P.id}`,dt.setAttribute("data-message-id",P.id),dt.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let We=document.createElement("div");We.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",We.innerHTML=p({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),dt.appendChild(We)}dt.appendChild(it),Mn=dt}}if(Mn||sn!=null){let it=_o(P.id,P.role);it.setAttribute("data-component-directive-stub","true"),it.setAttribute("data-preserve-runtime","true"),f.appendChild(it),pe.push({messageId:P.id,fingerprint:_t,bubble:Mn});return}}}if(!Et)if(P.variant==="reasoning"&&P.reasoning){if(!Po)return;Et=ug(P,o)}else if(P.variant==="tool"&&P.toolCall){if(!j)return;Et=fg(P,o)}else if(P.variant==="approval"&&P.approval){if(o.approval===!1)return;let Ce=O();if(!Ce)return;Et=Ce.createApprovalBubble(P,o)}else{let Ce=o.layout?.messages;Ce?.renderUserMessage&&P.role==="user"?Et=Ce.renderUserMessage({message:P,config:o,streaming:!!P.streaming}):Ce?.renderAssistantMessage&&P.role==="assistant"?Et=Ce.renderAssistantMessage({message:P,config:o,streaming:!!P.streaming}):Et=tg(P,p,Ce,o.messageActions,ys,{loadingIndicatorRenderer:v,widgetConfig:o,actionEligibility:Ot}),P.role!=="user"&&Et&&H(Et,P,o,E)}let De=_o(P.id,P.role);De.appendChild(Et),fv(Wt,P.id,_t,De),f.appendChild(De)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Se=Ne.getAttribute("data-persona-ask-sheet-for");Se&&!q.has(Se)&&si(Be.composerOverlay,Se)}),o.features?.toolCallDisplay?.grouped){let P=[],Ne=[],Se=o.features.toolCallDisplay.groupedMode==="summary";a.forEach(se=>{if(se.variant==="tool"&&se.toolCall&&j){if(Ko&&se.toolCall.status==="complete")return;Ne.push(se);return}se.variant==="reasoning"&&(!Po||se.reasoning?.status==="complete"&&So(se.reasoning))||((Ne.length>1||Se&&Ne.length>0)&&P.push(Ne),Ne=[])}),(Ne.length>1||Se&&Ne.length>0)&&P.push(Ne),P.forEach(se=>{let Mt=se.map(He=>Array.from(f.children).find(De=>De instanceof HTMLElement&&De.getAttribute("data-wrapper-id")===He.id)).filter(He=>!!He);if(Mt.length<(Se?1:2))return;let Ot=_o(`tool-group-${se[0].id}`,"assistant");Ot.setAttribute("data-persona-tool-group-row","true");let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let _t=document.createElement("div");_t.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",_t.id=`tool-group-summary-${se[0].id}`;let $t=`Called ${se.length} ${se.length===1?"tool":"tools"}`,Et=o.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(He=>He.toolCall).filter(He=>!!He),defaultSummary:$t,config:o});B(_t,Et)||(_t.textContent=$t);let rn=document.createElement("div");rn.className="persona-tool-group-stack persona-flex persona-flex-col",rn.id=`tool-group-stack-${se[0].id}`,rn.setAttribute("data-persona-tool-group-stack","true"),Jt.appendChild(_t),Se||Jt.appendChild(rn),Ot.appendChild(Jt),Mt[0].before(Ot),Mt.forEach((He,De)=>{if(Se){He.remove();return}He.style.setProperty("--persona-message-row-max-width","100%");let Ce=document.createElement("div");Ce.className="persona-tool-group-item persona-relative",Ce.setAttribute("data-persona-tool-group-item","true"),De<Mt.length-1&&Ce.setAttribute("data-persona-tool-group-connector","true"),Ce.appendChild(He),rn.appendChild(Ce)})})}mv(Wt,$);let aa=P=>P.variant==="tool"&&!j||P.variant==="reasoning"&&!Po||so(P),as=a.some(P=>P.role==="assistant"&&P.streaming&&!aa(P)),io=a.length-1;for(;io>=0&&aa(a[io]);)io--;let Yt=io>=0?a[io]:void 0,ao=io<a.length-1,Xs=Yt?.role==="assistant"&&!Yt.streaming&&Yt.variant!=="approval"&&!ao;if(Rn&&a.some(P=>P.role==="user")&&!as&&!Xs){let P={config:o,streaming:!0,location:"standalone",defaultRenderer:Na},Ne=l.find(se=>se.renderLoadingIndicator),Se=null;if(Ne?.renderLoadingIndicator&&(Se=Ne.renderLoadingIndicator(P)),Se===null&&o.loadingIndicator?.render&&(Se=o.loadingIndicator.render(P)),Se===null&&(Se=Na()),Se){let se=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1,Ot=o.layout?.messages?.layout??"bubble";se.className=Mt?Fa("assistant",Ot).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),se.setAttribute("data-typing-indicator","true"),Mt&&(se.style.color="var(--persona-message-assistant-text, var(--persona-text))",Ot!=="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 Jt=_o("typing-indicator","assistant");Jt.appendChild(se),f.appendChild(Jt)}}if(!Rn&&a.length>0){let P=a[a.length-1],Ne={config:o,lastMessage:P,messageCount:a.length},Se=l.find(Mt=>Mt.renderIdleIndicator),se=null;if(Se?.renderIdleIndicator&&(se=Se.renderIdleIndicator(Ne)),se===null&&o.loadingIndicator?.renderIdle&&(se=o.loadingIndicator.renderIdle(Ne)),se){let Mt=document.createElement("div"),Ot=o.loadingIndicator?.showBubble!==!1;Mt.className=Ot?["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(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild(se);let Jt=_o("idle-indicator","assistant");Jt.appendChild(Mt),f.appendChild(Jt)}}if(uy(f),Yc(r,f),su(r),Je){let{messageId:P,element:Ne}=Je,Se=r.querySelector(`#wrapper-${P}`);Se&&Ne.parentElement!==Se&&(Oi(Se,F.get(P)??"user"),Se.replaceChildren(Ne))}if(oe.length>0)for(let{messageId:P,fingerprint:Ne,bubble:Se}of oe){let se=r.querySelector(`#wrapper-${P}`);se&&(Oi(se,F.get(P)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Ne),ks.set(P,Ne)))}if(ks.size>0)for(let P of ks.keys())$.has(P)||ks.delete(P);if(pe.length>0)for(let{messageId:P,fingerprint:Ne,bubble:Se}of pe){let se=r.querySelector(`#wrapper-${P}`);se&&(Oi(se,F.get(P)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Ne),Fr.set(P,Ne)))}if(Fr.size>0)for(let P of Fr.keys())$.has(P)||Fr.delete(P);if(ut.length>0)for(let{messageId:P,fingerprint:Ne,bubble:Se}of ut){let se=r.querySelector(`#wrapper-${P}`);se&&(Oi(se,F.get(P)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Ne),cr.set(P,Ne)))}if(cr.size>0)for(let P of cr.keys())$.has(P)||cr.delete(P)},Yd=!1,wl=()=>{Yd||(Yd=!0,Ah().catch(()=>{Yd=!1}))},qn=(r,a,p)=>{a.length>0&&wl(),Ww(r,a,p),ff()},_i=null,Bw=()=>{if(_i)return;let r=p=>{let f=p.composedPath();f.includes(Ke)||jt&&f.includes(jt)||pt(!1,"user")};_i=r,(t.ownerDocument??document).addEventListener("pointerdown",r,!0)},Qf=()=>{if(!_i)return;(t.ownerDocument??document).removeEventListener("pointerdown",_i,!0),_i=null};fe.push(()=>Qf());let Ni=null,Dw=()=>{if(Ni)return;let r=p=>{p.key==="Escape"&&(p.isComposing||pt(!1,"user"))};Ni=r,(t.ownerDocument??document).addEventListener("keydown",r,!0)},Xf=()=>{if(!Ni)return;(t.ownerDocument??document).removeEventListener("keydown",Ni,!0),Ni=null};fe.push(()=>Xf());let Fi=!1,Yf=new Set,Ow=()=>{let r=o.launcher?.composerBar?.peek?.streamAnimation;return r||o.features?.streamAnimation},Ws=()=>{if(!Le())return;let r=Be.peekBanner,a=Be.peekTextNode;if(!r||!a)return;if(ve){r.classList.remove("persona-pill-peek--visible");return}let p=E?.getMessages()??[],f;for(let Dt=p.length-1;Dt>=0;Dt--){let At=p[Dt];if(At.role==="assistant"&&At.content){f=At;break}}if(!f){r.classList.remove("persona-pill-peek--visible");return}let y=f.content,v=!!f.streaming,B=Ow(),$=mc(B),F=$.type!=="none"?Ud($.type,B?.plugins):null,q=F?.isAnimating?.(f)===!0,X=F!==null&&(v||q);X&&F&&!Yf.has(F.name)&&(ma(F,t),Yf.add(F.name));let oe=X&&F?.containerClass?F.containerClass:null,pe=a.dataset.personaPeekStreamClass??null;pe&&pe!==oe&&(a.classList.remove(pe),delete a.dataset.personaPeekStreamClass),oe&&pe!==oe&&(a.classList.add(oe),a.dataset.personaPeekStreamClass=oe),X?(a.style.setProperty("--persona-stream-step",`${$.speed}ms`),a.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(a.style.removeProperty("--persona-stream-step"),a.style.removeProperty("--persona-stream-duration"));let Xe=X?hc(y,$.buffer,F,f,v):y;if(X&&$.placeholder==="skeleton"&&v&&(!Xe||!Xe.trim())){let Dt=document.createElement("div"),At=fa();At.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(At),Yc(a,Dt)}else{let Dt=Math.max(0,Xe.length-100),At=Xe.length>100?Xe.slice(-100):Xe,nn=ic(At);if(!X||!F){let Je=Xe.length>100?`\u2026${At}`:At;a.textContent!==Je&&(a.textContent=Je)}else{let Je=nn;(F.wrap==="char"||F.wrap==="word")&&(Je=ga(nn,F.wrap,`peek-${f.id}`,{skipTags:F.skipTags,startIndex:Dt}));let on=document.createElement("div");if(on.innerHTML=Je,F.useCaret&&At.length>0){let So=yc(),Ko=on.querySelectorAll(".persona-stream-char, .persona-stream-word"),so=Ko[Ko.length-1];so?.parentNode?so.parentNode.insertBefore(So,so.nextSibling):on.appendChild(So)}Yc(a,on),F.onAfterRender?.({container:a,bubble:r,messageId:f.id,message:f,speed:$.speed,duration:$.duration})}}let Vt=Rn||Fi;r.classList.toggle("persona-pill-peek--visible",Vt)};if(Le()){let r=Be.peekBanner;if(r){let f=y=>{y.preventDefault(),y.stopPropagation(),pt(!0,"user")};r.addEventListener("pointerdown",f),fe.push(()=>{r.removeEventListener("pointerdown",f)})}let a=()=>{Fi||(Fi=!0,Ws())},p=()=>{Fi&&(Fi=!1,Ws())};we.addEventListener("pointerenter",a),we.addEventListener("pointerleave",p),fe.push(()=>{we.removeEventListener("pointerenter",a),we.removeEventListener("pointerleave",p)}),jt&&(jt.addEventListener("pointerenter",a),jt.addEventListener("pointerleave",p),fe.push(()=>{jt.removeEventListener("pointerenter",a),jt.removeEventListener("pointerleave",p)}))}let _w=r=>{let a=o.launcher?.composerBar??{},p=a.expandedSize??"anchored",f=a.bottomOffset??"16px",y=a.collapsedMaxWidth,v=a.expandedMaxWidth??"880px",B=a.expandedTopOffset??"5vh",$=a.modalMaxWidth??"880px",F=a.modalMaxHeight??"min(90vh, 800px)",q="calc(100vw - 32px)",X="var(--persona-pill-area-height, 80px)",oe=Ke.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",jt){let pe=jt.style;pe.bottom=f,pe.width=y??""}if(r&&p!=="fullscreen"){if(p==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=$,oe.maxWidth=q,oe.maxHeight=F,oe.height=F;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${f} + ${X})`,oe.top=B,oe.width=v,oe.maxWidth=q}},Ui=()=>{if(ve&&wl(),!Fe())return;if(Le()){let q=(o.launcher?.composerBar??{}).expandedSize??"anchored",X=ve?"expanded":"collapsed";Ke.dataset.state=X,Ke.dataset.expandedSize=q,jt&&(jt.dataset.state=X,jt.dataset.expandedSize=q),Ke.style.removeProperty("display"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),_w(ve),de.style.display=ve?"flex":"none",Wr(),ve?(Bw(),Dw()):(Qf(),Xf()),Ws();return}let r=Lt(o),a=t.ownerDocument.defaultView??window,p=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,y=a.innerWidth<=p,v=f&&y&&ce,B=Yn(o).reveal;ve?(Ke.style.removeProperty("display"),Ke.style.display=r?"flex":"",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0"),we.classList.add("persona-scale-100","persona-opacity-100"),St?(St.setPanelOpen(!0),St.element.style.display="none"):dn&&(dn.style.display="none")):(r?r&&(B==="overlay"||B==="push")&&!v?(Ke.style.removeProperty("display"),Ke.style.display="flex",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ke.style.setProperty("display","none","important"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ke.style.display="",Ke.classList.add("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100"),we.classList.add("persona-scale-95","persona-opacity-0")),St?(St.setPanelOpen(!1),St.element.style.display=r?"none":""):dn&&(dn.style.display=r?"none":""))},pt=(r,a="user")=>{if(!Fe()||ve===r)return;let p=ve;ve=r,Ui();let f=(()=>{let v=o.launcher?.sidebarMode??!1,B=t.ownerDocument.defaultView??window,$=o.launcher?.mobileFullscreen??!0,F=o.launcher?.mobileBreakpoint??640,q=B.innerWidth<=F,X=Lt(o)&&$&&q,oe=Le()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return v||$&&q&&ce||X||oe})();if(ve&&f){if(!ho){let v=t.getRootNode(),B=v instanceof ShadowRoot?v.host:t.closest(".persona-host");B&&(ho=Vu(B,o.launcher?.zIndex??an))}yo||(yo=Ku(t.ownerDocument))}else ve||(ho?.(),ho=null,yo?.(),yo=null);ve&&(ra(),Qd()||(Hn()==="follow"?gr(!0):yl()));let y={open:ve,source:a,timestamp:Date.now()};ve&&!p?w.emit("widget:opened",y):!ve&&p&&w.emit("widget:closed",y),w.emit("widget:state",{open:ve,launcherEnabled:ce,voiceActive:ze.active,streaming:E.isStreaming()})},fr={inputDisabled:!1,sendDisabled:!1},bo=()=>fr.inputDisabled,Jd=()=>Tn(o.voiceRecognition?.provider)&&!!E&&(E.isBargeInActive()||["listening","processing","speaking"].includes(E.getVoiceStatus())),Qr=()=>fr.inputDisabled||fr.sendDisabled,Nw=()=>(fr.inputDisabled?fr.inputReason:void 0)??(fr.sendDisabled?fr.sendReason:void 0);function Zd(){if(!xe)return;if(be.getState().phase==="streaming"){xe.disabled=!1;return}let r=Ye?!Ye.isReady():!1;xe.disabled=Qr()||r}function Sl(){if(!po)return;let r=be.getState(),a=o.sendButton?.visibility==="when-text"&&r.phase!=="streaming"&&r.text.trim().length===0&&r.attachments.length===0;po.toggleAttribute("data-persona-send-hidden",a)}function Fw(){let r=Nw();if(Le()){let a=Zn??Ie;r?a.setAttribute("title",r):a.removeAttribute("title"),Ie.toggleAttribute(wi,!!r);return}if(r){rt.setAttribute("role","status"),rt.setAttribute("aria-live","polite"),rt.setAttribute(wi,""),rt.textContent=r;return}if(rt.hasAttribute(wi)&&(rt.removeAttribute("role"),rt.removeAttribute("aria-live"),rt.removeAttribute(wi),u)){let a=E.getStatus();Va(rt,Ug(a),o.statusIndicator??{},a)}}function ep(){let r=Iu(o.composer?.inputDisabled),a=Iu(o.composer?.sendDisabled);fr={inputDisabled:r.disabled,inputReason:r.reason,sendDisabled:a.disabled,sendReason:a.reason},be.setInputDisabled(r.disabled),be.setSendDisabled(a.disabled);let p=be.getState().phase==="streaming",f=r.disabled,y=p||f;le&&(le instanceof HTMLTextAreaElement?le.disabled=f:le.setAttribute("contenteditable",f?"false":"true"),le.setAttribute("aria-disabled",f?"true":"false")),bt&&(bt.disabled=f),ft&&(ft.disabled=f);for(let v of Pt?.affordanceButtons??[])v.querySelectorAll("button").forEach(B=>{B.disabled=f});ne&&(ne.disabled=f||p&&!Jd()),Or.forEach(v=>{v.elements.forEach(B=>{B.toggleAttribute("data-disabled",y),B instanceof HTMLButtonElement||B.setAttribute("aria-disabled",y?"true":"false")}),v.buttons.forEach(B=>{B.disabled=y})}),sp.forEach(v=>{v.toggleAttribute("data-disabled",y),v instanceof HTMLButtonElement?v.disabled=y:v.setAttribute("aria-disabled",y?"true":"false"),v.querySelectorAll("button").forEach(B=>{B.disabled=y})}),Ie.dataset.personaComposerStreaming=p?"true":"false",Ie.dataset.personaComposerInputDisabled=f?"true":"false",Ie.dataset.personaComposerSendDisabled=Qr()?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(v=>{(v instanceof HTMLButtonElement||v instanceof HTMLInputElement||v instanceof HTMLTextAreaElement||v instanceof HTMLSelectElement)&&(v.disabled=p)}),Zd(),Fw()}let $i=r=>{be.setStreaming(r),$g(r?"stop":"send"),ep()},Xr=()=>{ze.active||le&&le.focus()};w.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Xr(),200)});let Yr=null,qi=!1,tp=!yn.hidden,mr=null,np=!S,xl=null;fe.push(()=>{xl?.cancel(),xl=null});let Uw=r=>{let a=Wv(r);if(a===Xa)return;Xa=a,t.setAttribute("data-persona-conversation-state",a);let p=Md();Ja(),np&&(xl?.cancel(),xl=Hv(Ie,a==="active"?p:Md(),a==="active"?"drop":"rise")),Sn()},Jf=null,Zf,em=null,Bs=null,op=!1,zi=r=>{let a=Zo(o),p=`${a.variant}|${a.dismiss}|${a.anchor??"bottom"}|${a.align??""}|${a.iconPlacement}|${a.kicker??""}|${a.title}|${a.subtitle}`;(p!==Jf||a.icon!==Zf)&&(Jf=p,Zf=a.icon,od({host:yn,iconHolder:zC,kicker:jC,title:VC,subtitle:KC,starterSuggestions:wd},a));let f=a.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${a.message}`;f!==em&&(em=f,rd(In,a.message,o));let y=r??(E?E.getMessages():o.initialMessages);Uw(y);let v=qi,B=!v&&fi(a,y),$=B!==tp;if(tp=B,Bs){mr?.cancel(),mr=null,v!==op&&(op=v,v?rg(te,yn,null):og(te,yn,Bs)),gi(te,yn,!v);return}if($&&!B&&!v&&a.dismiss==="on-first-message"&&np){mr=Lv(yn,q=>{mr===q&&(mr=null),!tp&&!Bs&&(gi(te,yn,!1),Sn()),q?.cancel()});return}if(mr){if(!B&&!v)return;mr.cancel(),mr=null}let F=!yn.hidden;gi(te,yn,B),!B&&F&&Sn()},rp=[],sp=[],ip=!1,tm=null,nm,om=()=>{sp.length=0;let r=rp.splice(0,rp.length);for(let a of r)try{a()}catch(p){console.warn("[persona] renderWelcome cleanup threw",p)}};fe.push(om);let $w=(r,a)=>{let p=Qu(r,a);if(!p)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),k("span");let f=o.suggestions?.starters,y=Xu({item:{...p,behavior:p.behavior??f?.behavior??"send"},index:a,surface:"starter",source:"config",variant:f?.variant??"card",streaming:u?E.isStreaming():!1,config:o,plugins:l,chipsConfig:o.suggestionChipsConfig,session:E,getTextarea:()=>le,eventTarget:yn,submitPrompt:Xl});return sp.push(y),y},ap=()=>{if(ip)return;ip=!0;let r=Zo(o);tm=`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`,nm=r.icon;try{om(),rg(te,yn,Bs),Bs=null,op=!1;let a=E?E.getMessages():o.initialMessages,p=fi(r,a),f=0,y=null;for(let v of l)if(v.renderWelcome&&(y=v.renderWelcome({config:r,variant:r.variant,visible:p,defaultRenderer:()=>yn,sendMessage:B=>{if(!E||E.isStreaming())return;let $=B.trim();$&&E.sendMessage($)},requestRender:()=>ap(),renderStarter:B=>$w(B,f++),storage:g(v.id),onCleanup:B=>{rp.push(B)}}),y))break;y&&y!==yn&&(Bs=y,og(te,yn,y))}finally{ip=!1}zi()},qw=()=>{let r=Zo(o);`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`===tm&&r.icon===nm||ap()},Al=()=>{zi(),xs||(le.placeholder=Db(be.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!E?.isStreaming()&&(xe.textContent=o.copy?.sendButtonLabel??"Send")),le.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',le.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},zw=!!o.setStoredConversationId,Ds=r=>re(a=>{let p={...a};return delete p[r],p}),Ml=r=>{let a=Z[r];return typeof a=="string"?a:null},rm=()=>{let r=Z.durableResume;if(!r||typeof r!="object")return null;let a=r;return typeof a.executionId=="string"&&a.executionId.length>0&&typeof a.after=="string"&&a.after.length>0?{executionId:a.executionId,after:a.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Ml("sessionId"),setStoredSessionId:r=>{re(a=>({...a,sessionId:r}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Ds("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ml("conversationId")),setStoredConversationId:o.setStoredConversationId??(r=>{re(a=>({...a,conversationId:r}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Ds("conversationId"))});let sm=()=>o.clientToken??null,im=r=>fC(r,Q(),o.persistState===!1),am=sm(),No=am?im(am):null,Fo={...No?{visitorStore:No}:{},historyBootstrapReady:R,getStoredMessageCursor:()=>Ml("historyMessageCursor"),setStoredMessageCursor:r=>{if(r===null){Ds("historyMessageCursor");return}re(a=>({...a,historyMessageCursor:r}))},getPendingDisplayProjections:()=>{let r=Z.pendingDisplayProjections;if(!r||typeof r!="object")return null;let a=r;return typeof a.conversationId!="string"||!Array.isArray(a.messageIds)?null:{conversationId:a.conversationId,messageIds:a.messageIds.filter(p=>typeof p=="string")}},setPendingDisplayProjections:r=>{if(!r){Ds("pendingDisplayProjections");return}re(a=>({...a,pendingDisplayProjections:r}))},getStoredResumableHandle:rm,setStoredResumableHandle:r=>{if(!r){Ds("durableResume");return}re(a=>({...a,durableResume:r}))},shouldResumeDurableConversation:()=>ie&&rm()!==null,...zw?{}:{getStoredConversationRevision:()=>Ml("conversationRevision"),setStoredConversationRevision:r=>{if(r===null){Ds("conversationRevision");return}re(a=>({...a,conversationRevision:r}))}}};if(ie){let r=o.onExecutionState,a=t.ownerDocument.defaultView,p=!1,f=()=>p=!0,y=()=>p=!1;a?.addEventListener("pagehide",f),a?.addEventListener("pageshow",y),fe.push(()=>{a?.removeEventListener("pagehide",f),a?.removeEventListener("pageshow",y)}),o={...o,reconnectStream:o.reconnectStream??(v=>E.getClient().reconnectClientTokenStream(v)),onExecutionState:v=>{(v||!p)&&Fo.setStoredResumableHandle?.(v?{executionId:v.executionId,after:v.lastEventId}:null),r?.(v)}}}let jw=()=>{let r=sm();if(r&&No?.matches(r,Q(),o.persistState===!1)||!r&&!No)return;No?.destroy(),No=r?im(r):null;let a={...Fo};No?a.visitorStore=No:delete a.visitorStore,Fo=a,E.setHistoryInternals(Fo)},Jr=null,Vw=()=>{Jr==null&&(Jr=setInterval(()=>{let r=ke.querySelectorAll("[data-tool-elapsed]");if(r.length===0){clearInterval(Jr),Jr=null;return}let a=Date.now();r.forEach(p=>{let f=Number(p.getAttribute("data-tool-elapsed"));f&&(p.textContent=Rh(a-f))})},100))},lp=(r,a)=>{if(Object.is(r,a))return!0;if(r===null||a===null||typeof r!="object"||typeof a!="object")return!1;if(Array.isArray(r)||Array.isArray(a))return!Array.isArray(r)||!Array.isArray(a)||r.length!==a.length?!1:r.every((B,$)=>lp(B,a[$]));let p=r,f=a,y=Object.keys(p),v=Object.keys(f);return y.length===v.length&&y.every(B=>Object.prototype.hasOwnProperty.call(f,B)&&lp(p[B],f[B]))},lm=r=>{let{content:a,rawContent:p,llmContent:f,...y}=r;return y},cp=r=>r.role==="assistant"&&r.streaming===!0&&!r.variant&&!r.toolCall&&!r.tools&&!r.approval&&!r.reasoning&&!r.contentParts&&!r.stopReason&&!Lg(r),Kw=(r,a,p)=>{if(r.length!==a.length)return!1;let f=r[p.index],y=a[p.index];return!f||!y||f.id!==p.id||y.id!==p.id?!1:(!Object.is(f.content,y.content)||!Object.is(f.rawContent,y.rawContent)||!Object.is(f.llmContent,y.llmContent))&&cp(f)&&cp(y)&&lp(lm(f),lm(y))},dp=null,Os=null,Zr=null,Uo=null,pp=null,Gw=r=>{if(!ie)return Ls(r);pp=r,queueMicrotask(()=>{pp===r&&(pp=null,Ls(r))})},El=r=>{dp=r;let a,p;Os=null;for(let y=r.length-1;y>=0;y-=1){let v=r[y];if(!a&&v.role==="user"&&(a=v),!p&&v.role==="assistant"&&(p=v),!Os&&cp(v)&&(Os={index:y,id:v.id}),a&&p&&Os)break}qn(ke,r,vt),er()?.updateInlineArtifactBlocks(ke,$n.artifacts,{suppressTransition:Rn}),Vw(),zi(r),Ts(r),gr(!Rn),Rw(r),r.length===0&&(ro(),Wi=!0,pl=!1,Is=null,ul=!1),!$d||Ps?($d=!0,jr=a?.id??null,qd=p?.id??null):a&&a.id!==jr?(jr=a.id,kw(a.id)):p&&p.id!==qd&&Pw(),p&&(qd=p.id),Hw(r);let f=ze.lastUserMessageId;a&&a.id!==f&&(ze.lastUserMessageId=a.id,w.emit("user:message",a)),ze.lastUserMessageWasVoice=!!a?.viaVoice,Gw(r),Ws()},up=()=>{Uo!==null&&(cancelAnimationFrame(Uo),Uo=null);let r=Zr;Zr=null,r&&El(r)},cm=()=>{Uo!==null&&cancelAnimationFrame(Uo),Uo=null,Zr=null},Qw=r=>{let a=Zr??dp;if(Rn&&a&&Os&&Kw(a,r,Os)){Zr=r,Uo===null&&(Uo=requestAnimationFrame(()=>{Uo=null;let p=Zr;Zr=null,p&&El(p)}));return}if(r.length===0){cm(),El(r);return}up(),El(r)};E=new kc(o,{onMessagesChanged(r){Qw(r)},onStatusChanged(r){let a=o.statusIndicator??{};Va(rt,(f=>f==="idle"?a.idleText??Nt.idle:f==="connecting"?a.connectingText??Nt.connecting:f==="connected"?a.connectedText??Nt.connected:f==="error"?a.errorText??Nt.error:f==="paused"?a.pausedText??Nt.paused:f==="resuming"?a.resumingText??Nt.resuming:Nt[f])(r),a,r),Cd()},onStreamingChanged(r){r||(E?.getMessages().length===0?cm():up()),Rn=r,$i(r),Cd(),E&&qn(ke,E.getMessages(),vt),r||(gr(!0),Ew(),Bf=!0,E&&Df(E.getMessages(),Er(o))),Ut(),Qa(r?"Responding\u2026":"Response complete."),Ws()},onVoiceStatusChanged(r){if(w.emit("voice:status",{status:r,timestamp:Date.now()}),!(r!=="disconnected"&&!Tn(o.voiceRecognition?.provider)))switch(r){case"listening":Vo(),Gs();break;case"processing":Vo(),YS();break;case"speaking":Vo(),JS();break;default:r==="idle"&&E.isBargeInActive()?(Vo(),Gs(),ne?.setAttribute("aria-label","End voice session")):(ze.active=!1,Vo(),Oo("system"),oo());break}},onArtifactsState(r){$n=r,r.artifacts.length===0&&(As=!1),er()?.updateInlineArtifactBlocks(ke,r.artifacts,{suppressTransition:Rn}),no(),Ls()},onHistoryStateChanged(r){Ng(r)},onHistoryNotice(r){Fg(r)},onReconnect(r){let{executionId:a,lastEventId:p}=r.handle;r.phase==="paused"?w.emit("stream:paused",{executionId:a,after:p}):r.phase==="resuming"?w.emit("stream:resuming",{executionId:a,after:p,attempt:r.attempt??1}):w.emit("stream:resumed",{executionId:a,after:p})}},Fo),lt.current=E,fe.push(()=>E.cancel()),fe.push(()=>{E.destroy(),No?.destroy()});let gp=null;if(E.onReadAloudChange((r,a)=>{uf=r,gf=a,ff();let p=r??gp;r&&(gp=r);let f=p?E.getMessages().find(y=>y.id===p)??null:null;w.emit("message:read-aloud",{messageId:p,message:f,state:a,timestamp:Date.now()}),a==="idle"&&(gp=null)}),u=!0,$d=!0,o.voiceRecognition?.enabled===!0&&Tn(o.voiceRecognition.provider))try{E.setupVoice()}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",r)}let Xw=720,Yw=250,Qe=ru(o.features?.history?.copy),Dn=null,fp=!1,st=null,Tl=null,kl="conversation",mp=null,cn=null,vo=null,Pl=E.getHistoryState(),hp=null,ji=0,yp=null,Il=null,Ll=null,bp=`persona-history-${Math.random().toString(36).slice(2,8)}`,vp=()=>o.features?.history?.enabled===!0,Co=()=>vp()&&!!Dn&&!fp,dm=()=>{let r=E.getStatus();return Rn||r==="paused"||r==="resuming"},Cp=()=>{let r=o.features?.history?.scope;if(r)return r;let a=o.getIdentityProof?"verified-user":"browser",p=Dn?.capabilities.scopes;return!p||p.includes(a)?a:p[0]??a},_s=()=>Tl?.scope??Cp(),pm=()=>E.getClientSession()?.targetId??null,um=r=>`${r.state}:${"reason"in r?r.reason:""}`,Jw=r=>{let a=um(r);a!==hp&&(hp=a,w.emit("history:identityStatusChanged",{status:r,timestamp:Date.now()}))},Hl=r=>{r&&(Lo.textContent="",Lo.textContent=r)},gm=null,fm=null,Zw=()=>{if(!vp())return null;let r=bC();if(r)return r();let a=o.features?.history?.provider;return a?typeof a!="function"?a:(gm!==a&&(gm=a,fm=a()),fm):E.isClientTokenMode()?vC({client:E.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:p=>E.bindActivatedSession(p),getClient:()=>E.getClient()}):null},mm=()=>{Il?.(),Il=null,Ll?.(),Ll=null,fp=!1,Dn=Zw();let r={...Fo};Dn?r.historyProvider=Dn:delete r.historyProvider,Fo=r,E.setHistoryInternals(Fo),Dn&&(Il=Dn.subscribeAvailability?.(a=>{fp=!a,a||xn({restoreFocus:!1}),yr()})??null,Ll=Dn.subscribeIdentityStatus(a=>Jw(a)),hp=um(Dn.getIdentityStatus()))},wp=()=>{let r=o.features?.history?.presentation??"panel";if(r==="panel"||r==="auto"&&!(!ce||Lt(o)))return"panel";let a=mo??de;return(a.getBoundingClientRect().width||a.clientWidth)>=Xw?"rail":"panel"},zn=(r,a)=>{a?(r.setAttribute("aria-hidden","true"),r.setAttribute("inert","")):(r.removeAttribute("aria-hidden"),r.removeAttribute("inert"))},Rl="data-persona-history-suppressed",On=null,hr=null,es=null,Vi=null,Sp=null,hm="",ym=()=>Ae===Sp?hm:o.layout?.showHeader===!1?"none":"",eS=()=>Ht==="panel"&&!!es&&Vi===es.element&&o.layout?.showHeader!==!1&&ym()!=="none",tS=()=>{for(let r of Array.from(Ae.children))r!==On&&r.setAttribute(Rl,"")},nS=()=>{for(let r of Array.from(de.querySelectorAll(`[${Rl}]`)))r.removeAttribute(Rl)},oS=()=>{let r=es;if(!r)return;if(Array.from(Ae.children).some(f=>f!==On&&!f.hasAttribute(Rl))){hr&&hr!==Ae&&(hr.style.removeProperty("min-height"),hr=null);let f=Ae.offsetHeight;f>0&&(Ae.style.minHeight=`${f}px`,hr=Ae)}On||(On=k("div","persona-history-header-host")),r.setHeaderPlacement("external");let p=r.getHeaderElement();p.parentNode!==On&&On.replaceChildren(p),On.parentNode!==Ae&&Ae.appendChild(On),tS()},bm=()=>{hr&&(hr.style.removeProperty("min-height"),hr=null),On&&(es?.setHeaderPlacement("inline"),On.remove(),On=null,nS())},Wl=null,xp=()=>{if(Wl){if(te.style.display="none",zn(te,!0),Ie.hidden=!0,zn(Ie,!0),eS()){oS(),Ae.style.display=ym(),zn(Ae,!1);return}bm(),Ae.style.display="none",zn(Ae,!0)}};vd=xp;let rS=r=>{let a=te.style.display,p=Ie.hidden,f=Ie,y=Ae,v=Ae.style.display;Sp=y,hm=v,Wl=()=>{Wl=null,bm(),Sp=null,te.style.display=a,zn(te,!1),f.hidden=p,zn(f,!1),Ie!==f&&(Ie.hidden=!1,zn(Ie,!1)),y.style.display=v,zn(y,!1),Ae!==y&&(Ae.style.display=o.layout?.showHeader===!1?"none":"",zn(Ae,!1))},Ie.parentNode?.insertBefore(r,Ie),xp()},Ns=null,ts=null,Ki=null,Fs=null,vm=()=>[Ae,Be.closeButtonWrapper,Be.clearChatButtonWrapper,te,Ie],sS=52,Bl=()=>o.features?.history?.rail?.collapsible!==!1,Us=()=>o.features?.history?.rail?.side==="right"?"right":"left",Ap=200,Mp=400,Ep=r=>Math.min(Mp,Math.max(Ap,Math.round(r))),iS=()=>o.features?.history?.rail?.resizable===!0,Gi,aS=()=>{if(Gi===void 0&&(Gi=null,o.persistState!==!1))try{let r=Number(window.localStorage.getItem(`${Q()}rail-width`));r&&(Gi=r)}catch{}return Gi},Qi=()=>Ep(aS()??o.features?.history?.rail?.width??260),lS=r=>{if(Gi=r,o.persistState!==!1)try{window.localStorage.setItem(`${Q()}rail-width`,String(r))}catch{}},Dl=()=>Bl()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Bt=!1,Cm=r=>{let a=k("img");return a.src=r,a.alt="",a.setAttribute("aria-hidden","true"),a},cS=()=>{let r=o.features?.history?.rail?.brand;if(!r)return;let a=!1,p;return f=>{if(r.render)try{return r.render({collapsed:f})??null}catch(y){return a||(a=!0,console.warn("[persona] history rail brand threw",y)),null}return p===void 0&&(r.iconUrl?p=Cm(r.iconUrl):p=r.icon?ge(r.icon,20):null),p?p.cloneNode(!0):null}},dS=()=>o.features?.history?.rail?.sections?.map(r=>{let a=!1,p=f=>{a||(a=!0,console.warn("[persona] history rail section threw",r.id,f))};return{id:r.id,title:r.title,placement:r.placement??"above-conversations",items:r.items.map(f=>{let y;return{id:f.id,label:f.label,badge:f.badge,iconNode:()=>{if(y!==void 0)return y;try{f.renderIcon?y=f.renderIcon()??null:f.iconUrl?y=Cm(f.iconUrl):y=f.icon?ge(f.icon,20):null}catch(v){p(v),y=null}return y},onSelect:()=>{try{f.onSelect()}catch(v){p(v)}}}})}})??[],pS=r=>{let a=dS();for(let p of r)a.some(f=>f.id===p.id)?console.warn("[persona] duplicate history rail section id",p.id):a.push(p);return a.length?a:void 0},Xi=null,wm=()=>`${Q()}rail-collapsed`,Tp=()=>{if(Xi===null&&(Xi=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let r=window.localStorage.getItem(wm());r&&(Xi=r==="1")}catch{}return Xi},kp=r=>{if(Xi=r,o.persistState!==!1)try{window.localStorage.setItem(wm(),r?"1":"0")}catch{}},Yi=()=>Ht==="rail"&&Bl()&&!Dl()&&Tp(),Pp=()=>{},Sm=()=>{if(Dl()){Pp();return}kp(!Tp()),st?.view.setCollapsed(Yi()),Io(),Sn()},Ip=()=>{let r=o.features?.history?.rail?.collapseShortcut;return!r||!Qc(r)?null:{combo:r,hint:Xc(r),aria:Ha(r)}},xm=()=>{d.forEach(a=>a()),d=[];let r=Ip();r&&d.push(c.register({id:"history-rail-collapse",combo:r.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Ct&&Ht==="rail"&&Bl()||qs(),run:()=>Dl()?Pp():Sm()}));for(let a of o.layout?.header?.trailingActions??[])a.shortcut&&d.push(c.register({id:`header-action-${a.id}`,combo:a.shortcut,run:()=>{let p=t.querySelector(`[data-persona-header-action="${a.id}"]`);p?p.click():o.layout?.header?.onAction?.(a.id)}}));for(let a of l)for(let p of a.shortcuts??[])d.push(c.register({...p,id:`${a.id}:${p.id}`}))};xm();let uS=300,Ol="var(--persona-history-overlay-margin,8px)",jn=null,$o=null,_l=0,qo=null,$s=null,ns=!1,Lp=0,Am=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,qs=()=>Co()&&Dl()&&(Ht??wp())==="rail",gS=()=>Ct&&!Bt,Ji=()=>{$s!==null&&clearTimeout($s),$s=null},fS=()=>{kg().catch(()=>{})},Mm=()=>{Ji(),Bt&&($s=setTimeout(()=>{$s=null,!(ns||!Bt)&&(qo?.contains(document.activeElement)||xn({restoreFocus:!1}))},uS))},mS=(r,a)=>{let p=qo?.getBoundingClientRect();if(!p)return!1;let f=jn?.getBoundingClientRect(),y=f?Math.min(f.top,p.top):p.top;return r>=p.left&&r<=p.right&&a>=y&&a<=p.bottom||!!f&&r>=f.left&&r<=f.right&&a>=f.top&&a<=f.bottom},Hp=r=>{Bt&&(ns=mS(r.clientX,r.clientY),ns?Ji():$s===null&&Mm())},Em=r=>{Ct||!qs()||(Bt=!0,ea({invoker:jn,keyboard:r?.keyboard===!0}).then(()=>{Ct?!ns&&document.activeElement!==jn&&xn():Bt=!1}))},Tm=()=>{let r=Vi?.querySelector('[data-persona-history-focus="collapse"]');r&&(r.setAttribute("aria-label",Bt?Qe.expandLabel:Qe.collapseLabel),r.setAttribute("aria-expanded",Bt?"false":"true"))},km=()=>{kp(!1);let r=st;if(!Bt||!r){ea({invoker:jn});return}let a=document.activeElement===jn;Bt=!1,Nl(),r.element.remove(),Wp(r.element),Tm(),a&&Ul(),Sn(),yr()},hS=()=>{kp(!0),xn()};Pp=()=>{!Ct||Bt?km():hS()};let yS=()=>{let r=Ip(),a=gs({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":bp,...r?{"aria-keyshortcuts":r.aria}:{}}}),p=a.button;p.addEventListener("mouseenter",()=>{ns=!0,Ji(),!(Am()||Date.now()<Lp)&&Em()}),p.addEventListener("mouseleave",()=>{ns=!1,Lp=0,Mm()}),p.addEventListener("focus",()=>{Ct||fS()}),p.addEventListener("click",f=>{Co()&&(f.detail!==0&&Am()&&!Ct?Em():km())}),jn=p,$o=a.wrapper},Zi=()=>{if($o&&!$o.isConnected&&($o=null,jn=null),!qs()){$o?.remove(),$o=null,jn=null;return}jn||yS();let r=$o,a=jn;if(!r||!a)return;let p=Us()!=="right"?Ae.firstChild:null;(p??Ae.lastChild)!==r&&Ae.insertBefore(r,p),r.style.display=gS()||_l>0?"none":"",a.setAttribute("aria-label",Qe.expandLabel),a.setAttribute("aria-expanded",Ct?"true":"false"),qo&&Io()},Pm=r=>{if(!Bt)return;let a=r.target;a instanceof Node&&(qo?.contains(a)||$o?.contains(a)||a instanceof Element&&a.closest('.persona-dropdown-menu,[role="alertdialog"]')||xn({restoreFocus:!1}))};document.addEventListener("pointerdown",Pm,!0),fe.push(()=>{document.removeEventListener("pointerdown",Pm,!0),document.removeEventListener("pointermove",Hp),zs?.(),Ji()});let Rp=null,zs=null,Im=16,Lm=r=>{lS(Ep(r)),Io(),Sn()},bS=()=>{let r=k("div","persona-rail-resizer");return r.tabIndex=0,r.setAttribute("role","separator"),r.setAttribute("aria-orientation","vertical"),r.setAttribute("aria-valuemin",String(Ap)),r.setAttribute("aria-valuemax",String(Mp)),r.addEventListener("pointerdown",a=>{let p=ts;if(!p||a.button!==0)return;a.preventDefault(),zs?.();let f=a.clientX,y=p.getBoundingClientRect().width||Qi(),v=Us()==="right"?-1:1,B=y,$=t.ownerDocument;p.style.transition="none";let F=X=>{B=Ep(y+v*(X.clientX-f)),p.style.flex=`0 0 ${B}px`,r.setAttribute("aria-valuenow",String(B))},q=()=>{zs=null,$.removeEventListener("pointermove",F),$.removeEventListener("pointerup",q),$.removeEventListener("pointercancel",q),p.style.removeProperty("transition");try{r.releasePointerCapture(a.pointerId)}catch{}Lm(B)};zs=q,$.addEventListener("pointermove",F),$.addEventListener("pointerup",q),$.addEventListener("pointercancel",q);try{r.setPointerCapture(a.pointerId)}catch{}}),r.addEventListener("keydown",a=>{let p=Us()==="right"?-Im:Im,f=Qi(),y=a.key==="ArrowRight"?f+p:a.key==="ArrowLeft"?f-p:a.key==="Home"?Ap:a.key==="End"?Mp:null;y!==null&&(a.preventDefault(),Lm(y))}),r},vS=(r,a)=>{if(!iS()||Yi()){zs?.(),Rp?.remove();return}let p=Rp??bS();Rp=p,p.setAttribute("aria-label",Qe.resizeLabel),p.setAttribute("aria-valuenow",String(Qi())),p.nextElementSibling!==a&&r.insertBefore(p,a)};Io=()=>{st?.view.setRailSide(Us());let r=Us()==="right",a=qo;if(a){let $=jn?jn.getBoundingClientRect().bottom-de.getBoundingClientRect().top:0;a.style.top=`calc(${Math.max(0,Math.round($))}px + ${Ol})`,a.style.width=`${Qi()}px`,a.style.left=r?"":Ol,a.style.right=r?Ol:""}let p=ts,f=Ns,y=Ki;if(!p||!f||!y)return;p.style.flex=`0 0 ${Yi()?sS:Qi()}px`;let v="1px solid var(--persona-divider,#e5e7eb)";p.style.borderRight=r?"":v,p.style.borderLeft=r?v:"";let B=r?y:p;f.firstElementChild!==B&&f.append(B,r?p:y),vS(f,r?p:y)};let Hm=r=>{if(Fs&&ts){Fs.replaceWith(r),Fs=null,Io();return}let a=k("div","persona-history-rail-shell");a.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let p=k("div","persona-history-rail-conversation");p.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let f=k("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",de.insertBefore(a,Ae.parentNode===de?Ae:te);for(let y of vm())y?.parentNode===de&&p.appendChild(y);a.append(f,p),f.appendChild(r),Ns=a,ts=f,Ki=p,Io()},CS=()=>{if(Ns)return;let r=k("div","persona-history-rail-placeholder");r.style.cssText="flex:1 1 auto;min-height:0",Fs=r,Hm(r),Sn()},Rm=()=>{Fs&&(Nl(),Sn())},wS=r=>{let a=k("div","persona-history-rail-overlay");a.style.cssText=`position:absolute;bottom:${Ol};display:flex;overflow:hidden;z-index:${uc-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(a),a.appendChild(r),document.addEventListener("pointermove",Hp),qo=a,Io(),Tm()},Nl=()=>{Wl?.(),qo&&(ns&&(Lp=Date.now()+150),document.removeEventListener("pointermove",Hp),qo.remove(),qo=null);let r=Ns;if(r){zs?.();for(let a of vm())a&&r.contains(a)&&de.insertBefore(a,r);r.remove(),Ns=null,ts=null,Ki=null,Fs=null}},Wm=r=>{Vi=r,r.id=bp,r.style.flex="1 1 auto",r.style.minHeight="0"},Wp=r=>{Wm(r),(Ht!=="rail"||Bt)&&Rm(),Ht!=="rail"?rS(r):Bt?wS(r):Hm(r)},Fl=()=>{if(Zi(),jm(),!Ct||!st)return;let r=wp();if(r===Ht)return;let a=document.activeElement,p=a instanceof HTMLElement&&(st.element.contains(a)||On?.contains(a)===!0)?a:null;Nl(),st.element.remove(),st.view.setHeaderPlacement("inline"),Ht=r,st.view.setPresentation(r),st.view.setCollapsed(Yi()),st.requestRender(),st.element.isConnected||Wp(st.element),p?.isConnected?p.focus():Ul(),Ut(),Sn(),yr()},Bm=(r,a)=>On?.querySelector(a)??r.querySelector(a),Ul=()=>{let r=st?.element??Vi;if(!r)return;let a=Bm(r,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(a){a.focus();return}let p=Bm(r,".persona-history-title")??r;p.tabIndex=-1,p.focus()},ea=async r=>{if(!Co()||Ct)return;let a=Dn;if(!a)return;if(!Bt&&qs()&&Tp()){Zi();return}$l();let p=++ji;kl=r?.returnSurface??"conversation",mp=r?.invoker??cn;let f=qs()&&!Bt;f&&(_l+=1,Zi(),CS());let y;try{y=await kg()}catch{Hl(Qe.openHistoryLabel),f&&(_l-=1,p===ji&&(Rm(),Zi()));return}if(f&&(_l-=1),p!==ji||Ct)return;Tl={scope:Cp()},Ht=wp(),Ct=!0;let v=Ht==="panel"&&o.layout?.showHeader!==!1&&Ae.style.display!=="none"?"external":"inline",B=o.features?.history?.rowAvatar,$=Ip(),F=$?{hint:$.hint,aria:$.aria}:null,q={provider:a,context:Tl,targetId:pm(),presentation:Ht,collapsible:Bl(),collapsed:Yi(),railSide:Us(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:cS(),onToggleCollapse:Sm,...F?{collapseShortcut:F}:{},headerPlacement:v,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:B===!1?!1:typeof B=="string"?B:o.launcher?.iconUrl,activeConversationId:E.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:X=>Dp(X,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:X=>os(X),attachTooltip:Qt,onStartNew:()=>Op({focusComposer:!0}),onClose:()=>xn(),onRequestDeleteConversation:X=>zm(X),onRequestClearHistory:()=>TS(),...a.resetDevice?{onRequestResetIdentity:()=>kS()}:{}};st=yC({plugins:l,config:o,getPresentation:()=>Ht??"panel",getReturnSurface:()=>kl,close:()=>xn(),createView:({slots:X,renderDom:oe,onModelChange:pe,railSections:Xe})=>(es=y.createHistoryView({...q,railSections:pS(Xe),slots:X,renderDom:oe,onModelChange:pe,onAnnounce:Hl}),es),onElementChanged:(X,oe)=>{if(!oe?.isConnected)return Wp(X);Wm(X),oe.replaceWith(X),xp()}}),st.view.setNewConversationRequired(Pl.recovery==="new_conversation_required"),r?.focus!==!1&&(Ht!=="rail"||r?.keyboard===!0)&&Ul(),Ut(),Sn(),yr(),w.emit("history:opened",{presentation:Ht,returnSurface:kl,timestamp:Date.now()})},$l=()=>{},xn=r=>{if(!Ct)return;ji+=1;let a=kl,p=mp,f=st,y=r?.restoreFocus!==!1;Ct=!1;let v=!1,B=null,$=()=>{if(!v){if(v=!0,$l=()=>{},B!==null&&clearTimeout(B),Bt=!1,Ji(),Nl(),f?.dispose(),f?.view.destroy(),f?.element.remove(),st===f&&(st=null,es=null,Vi=null,Ht=null,Tl=null,mp=null),Ut(),Sn(),yr(),y){let q=p??cn;q?.isConnected?q.focus():Xr()}w.emit("history:closed",{returnSurface:a,timestamp:Date.now()})}},F=f&&f.element===f.view.element?f.view.playExit():null;if(!F){$();return}$l=$,B=setTimeout($,Yw),F.then($)},Dm=r=>{if(!(r.key!=="Escape"||!Ct||!st)){if(Ht==="rail"){let a=r.target;if(!(a instanceof Node)||!(st.element.contains(a)||Bt&&$o?.contains(a)===!0))return}r.preventDefault(),r.stopPropagation(),xn()}};de.addEventListener("keydown",Dm),fe.push(()=>de.removeEventListener("keydown",Dm));let ql=null,Om=!1,ta=()=>{if(!rr)return;let r=o.layout?.header?.titleSource==="conversation",a=r&&ql?.trim()||null;rr.textContent=a??o.launcher?.title??"Chat Assistant";let p=rr.closest(".persona-combo-btn");if(!p)return;let f=!r||E.getActiveConversationId()!==null;p.setAttribute("data-persona-menu-locked",f?"false":"true"),p.setAttribute("aria-haspopup",f?"true":"false"),f||p.setAttribute("aria-expanded","false"),p.style.cursor=f?"pointer":"default";let y=p.querySelector("svg");y&&(y.style.display=f?"":"none")},SS=r=>{r!==ql&&(ql=r,ta())},os=r=>{Om=r?.starred===!0,SS(r&&r.title.trim()||null),ta()};ta(),de.addEventListener("persona:title-menu-builtin",r=>{let a=r.detail?.actionId,p=E.getActiveConversationId();p&&(a==="delete"?zm(p):a==="star"&&E.canUpdateConversations()&&_p(p,{starred:!Om}).catch(()=>{}))});let zl=0,xS=250,jl=null,Vl=()=>{jl&&clearTimeout(jl),jl=null};fe.push(Vl);let _m=()=>{Vl();let r=Yr;r&&(qi=!0,r.hidden=!1,ke.style.display="none",zi())},Kl=()=>{zl+=1,Vl(),Yr&&(Yr.remove(),Yr=null,qi=!1,ke.style.removeProperty("display"),zn(Ie,!1),zi())},AS=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;ke.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Bp=(r,a)=>G("div",{className:_n("persona-conversation-loading-bubble",a&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:r}}),Nm=()=>G("div",{className:"persona-conversation-loading-body"},Bp("58%",!1),Bp("72%",!0),Bp("44%",!1)),Fm=r=>{Yr?.remove(),Yr=r,r.hidden=!qi,te.insertBefore(r,ke),Vl(),qi||(jl=setTimeout(_m,xS)),zn(Ie,!0)},MS=()=>{let r={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Nm},a=null,p=l.find(f=>f.renderLoadingIndicator);p?.renderLoadingIndicator&&(a=p.renderLoadingIndicator(r)),a===null&&o.loadingIndicator?.render&&(a=o.loadingIndicator.render(r)),Fm(G("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},a??Nm()))},ES=r=>{let a=()=>{Dp(r,{focusComposer:!0}).catch(()=>{})},p=Co()?()=>{Kl(),ea()}:void 0,f=($,F)=>{let q=G("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:$});return q.addEventListener("click",F),q},y=()=>G("div",{className:"persona-conversation-loading-error-body"},G("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),G("div",{className:"persona-conversation-loading-error-actions"},f(Qe.openConversationRetryLabel,a),p?f(Qe.openConversationBackLabel,p):null)),v=Object.freeze({conversationId:r,config:o,copy:Object.freeze({title:Qe.openConversationErrorTitle,retryLabel:Qe.openConversationRetryLabel,backLabel:Qe.openConversationBackLabel}),retry:a,...p?{back:p}:{},defaultRenderer:y}),B=null;for(let $ of l)if($.renderHistoryOpenError){try{B=$.renderHistoryOpenError(v)}catch(F){console.warn("[persona] renderHistoryOpenError threw",F),B=null}if(B)break}Fm(G("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},B??y())),_m()};w.on("history:closed",()=>{Yr&&zn(Ie,!0)});let Dp=async(r,{focusComposer:a=!1}={})=>{let p=_s(),f=!!st;st?.view.setActiveConversationId(r),Kl();let y=zl;MS(),Ct&&(Ht==="panel"||Bt)&&xn({restoreFocus:!1}),Ps=!0;try{await E.openConversation(r,{scope:p})}catch(v){throw y===zl&&ES(r),v}finally{Ps=!1}y===zl&&(Kl(),Wt.clear(),ro(),wn(),Qd()||yl(),AS(),zo(),f||os(null),w.emit("history:conversationOpened",{conversationId:r,title:ql,scope:p,timestamp:Date.now()}),a&&Xr())},Op=async({focusComposer:r=!1}={})=>{Kl(),await E.startNewConversation({scope:_s()}),os(null),Wt.clear(),ro(),wn(),yl(),zo();let a=E.getActiveConversationId();st?.view.setActiveConversationId(a),w.emit("history:conversationStarted",{conversationId:a,timestamp:Date.now()}),Ct&&(Ht==="panel"||Bt)&&xn({restoreFocus:!1}),r&&Xr()},_p=async(r,a)=>{let p=await E.updateConversation(r,{...a,...a.title!==void 0?{title:a.title.trim()}:{}});return st?.view.applyConversationSummary(p),!st&&r===E.getActiveConversationId()&&os(p),p},Um=async r=>{let a=_s(),p=E.getActiveConversationId()===r;await E.deleteConversation(r,{scope:a}),st?.view.removeConversationSummary(r),p&&(os(null),Wt.clear(),ro(),wn(),zo()),w.emit("history:conversationDeleted",{conversationId:r,scope:a,wasActive:p,timestamp:Date.now()})},$m=async r=>{let a=r?.scope??_s(),p=r?.allTargets?null:r?.targetId??pm(),f=await E.clearConversationHistory({...p?{targetId:p}:{},scope:a});return os(null),Wt.clear(),ro(),wn(),zo(),w.emit("history:cleared",{deleted:f.deleted,scope:a,targetId:p,timestamp:Date.now()}),f},qm=async()=>{if(!Dn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let r=!1;try{r=(await E.resetHistoryDevice()).remoteRevocationConfirmed}finally{os(null),E.clearArtifacts(),Wt.clear(),dp=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),Z={},he.syncFromMetadata(),K?.clear&&fl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),ro(),wn(),zo(),xn({restoreFocus:!1}),Xr(),ve||St?.launcher.element.focus()}return Hl(r?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),w.emit("history:identityReset",{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},Np=()=>mo?we:de,zm=async r=>await md({host:Np(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Um(r),"deleted"):"cancelled",TS=async()=>{let r=_s()==="verified-user";return await md({host:Np(),title:Qe.clearHistoryConfirmTitle,description:r?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await $m(),"cleared"):"cancelled"},kS=async()=>{if(!await md({host:Np(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:a}=await qm();return{outcome:"reset",remoteRevocationConfirmed:a}},Vn=k("button","persona-history-earlier");Vn.type="button",Vn.textContent=Qe.showEarlierMessagesLabel,Vn.setAttribute("data-persona-history-earlier",""),Object.assign(Vn.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 zo=()=>{if(!(Co()&&!!Pl.nextMessageCursor&&!!E.getActiveConversationId())){Vn.remove();return}Vn.textContent=Qe.showEarlierMessagesLabel,Vn.parentNode!==te&&te.insertBefore(Vn,te.firstChild)};Vn.addEventListener("click",()=>{let r=E.getActiveConversationId(),a=Pl.nextMessageCursor;if(!r||!a||Vn.disabled)return;Vn.disabled=!0;let p=te.scrollHeight,f=te.scrollTop;E.loadOlderMessages(r,a,{scope:_s()}).then(()=>{te.scrollTop=f+(te.scrollHeight-p),Sn()}).catch(()=>{}).finally(()=>{Vn.disabled=!1,zo()})});let PS=()=>{let r=gs({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 r.button.addEventListener("click",a=>{if(!(!Co()||dm())){if(Ct){xn();return}ea({invoker:r.button,keyboard:a.detail===0})}}),r},jm=()=>{if(!Co()){vo?.remove(),cn=null,vo=null;return}if(vo&&!vo.isConnected&&(cn=null,vo=null),!cn&&Ae){let f=PS();cn=f.button,vo=f.wrapper;let y=Be.clearChatButtonWrapper||Be.closeButtonWrapper;y?.parentNode&&Ae.contains(y)?y.parentNode.insertBefore(vo,y):Ae.appendChild(vo)}if(!cn||!vo)return;let r=qs()||Ct&&Ht==="rail";if(vo.style.display=r?"none":"",r){document.activeElement===cn&&Ul();return}let a=dm();cn.disabled=a,cn.setAttribute("aria-disabled",a?"true":"false");let p=a?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;cn.setAttribute("aria-label",p),(o.features?.history?.presentation??"panel")==="panel"?(cn.removeAttribute("aria-expanded"),cn.removeAttribute("aria-controls")):(cn.setAttribute("aria-expanded",Ct?"true":"false"),cn.setAttribute("aria-controls",bp))},Gl=!1,IS=()=>{let r=Be.clearChatButton;if(r){if(Co()){Gl||(yp=r.getAttribute("aria-label")??"",Gl=!0),r.setAttribute("aria-label",Qe.newConversationLabel),r.removeAttribute("title");return}Gl&&(Gl=!1,yp&&r.setAttribute("aria-label",yp))}},yr=()=>{Qe=ru(o.features?.history?.copy),jm(),Zi(),IS(),zo()};Cd=yr,Ng=r=>{Pl=r,st?.view.setNewConversationRequired(r.recovery==="new_conversation_required"),$i(r.sendBlocked||Rn),zo()},Fg=r=>{(r.code==="history_continuity_reset"||r.code==="conversation_deleted_recovered")&&(Wt.clear(),ro(),wn()),Hl(r.message),st?.view.refresh()},mm(),yr(),fe.push(()=>{Il?.(),Ll?.(),ji+=1,$l(),st?.dispose(),st?.view.destroy(),st=null}),o.clientToken&&E.initClientSession().then(()=>{if(Co())return E.reconcileBootConversation({scope:Cp()})}).then(()=>{zo()}).catch(r=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",r)}),(C||o.onSSEEvent)&&E.setSSEEventCallback((r,a)=>{o.onSSEEvent?.(r,a),bd(r,a)});let Vm=()=>{let r=o.resume??(ie?Fo.getStoredResumableHandle?.():null);r&&typeof o.reconnectStream=="function"&&E.resumeFromHandle(r)};S?S.then(r=>{if(r){if(r.metadata&&(Z=Hg(r.metadata),he.syncFromMetadata()),r.messages?.length){Ps=!0;try{E.hydrateMessages(r.messages)}finally{Ps=!1}wl()}r.artifacts?.length&&E.hydrateArtifacts(r.artifacts,r.selectedArtifactId??null),$f(r.draft)}}).catch(r=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",r)}).finally(()=>{np=!0,W(),Vm()}):($f(L),Vm());let LS=()=>{!Le()||ve||!(o.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},HS=(r,a)=>r?a?{refs:[...r.refs,...a.refs],finalize:async()=>{let[p,f]=await Promise.allSettled([r.finalize(),a.finalize()]),y=[];return p.status==="fulfilled"?y.push(p.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",p.reason),f.status==="fulfilled"?y.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),TT(y)}}:r:a,Fp=()=>{let a=le.getInlineMessageFields?.();return a&&a.contentSegments.some(f=>f.kind==="mention")?a.contentSegments:void 0},jo=!1,rs=null,Ql=()=>{le.value="",le.style.height="auto",uo(),oa()},Up="data-persona-composer-notice",js=null;function RS(r){Qa(r),!(Le()||!rt)&&(rt.hasAttribute(wi)||(rt.setAttribute(Up,""),rt.setAttribute("role","status"),rt.setAttribute("aria-live","polite"),rt.textContent=r,js&&clearTimeout(js),js=setTimeout(()=>{if(js=null,!!rt?.hasAttribute(Up)&&(rt.removeAttribute(Up),rt.removeAttribute("role"),rt.removeAttribute("aria-live"),u)){let a=E.getStatus();Va(rt,Ug(a),o.statusIndicator??{},a)}},4e3)))}function WS(){let r=be.getState().pendingSubmission;r&&(ws(void 0),le&&(le.value=r.text,le.dispatchEvent(new Event("input",{bubbles:!0})),uo()),r.options.selectedModelId&&(be.setSelectedModelId(r.options.selectedModelId),ir?.repaint()),r.options.activeModeIds?.length&&Za(r.options.activeModeIds),r.options.quote&&go(r.options.quote),le?.focus())}let BS=r=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",r)},Km=(r={})=>{let a=(r.overrideText??le?.value??"").trim();return r.resolveInlineCommand&&a?(Pt?.takeInlineCommand(a)??Promise.resolve(null)).then(p=>Gm(r,a,p)):Gm(r,a,null)},Gm=(r,a,p)=>{if(p?.kind==="action"){Ql(),Pt?.clear(),Rr();return}let f=p?.kind==="server"?p.mentions:null,y=p?.kind==="prompt"?p.sendText:a,v=r.pending?.contentParts,B=(Ye?.hasAttachments()??!1)||(v?.length??0)>0;if(!Gb({text:y,hasAttachments:B,attachmentsReady:Ye?.isReady()??!0,hasMentions:Pt?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:bo(),sendDisabled:Qr()}))return;let $=E.isStreaming()?Pd():"block";if($==="defer-one"&&!r.pending){if(be.getState().pendingSubmission){RS("One message is already queued. Edit or remove it first.");return}DS({intent:r,sendText:y,serverMentions:f});return}let F={text:y,mentionRefs:[...Pt?.getMentionRefs()??[],...f?.refs??[]],contentSegments:p?.kind==="prompt"?void 0:Fp(),options:{...be.getState().selectedModelId&&{selectedModelId:be.getState().selectedModelId},...be.getState().activeModeIds.length>0&&{activeModeIds:[...be.getState().activeModeIds]},...be.getState().quote&&{quote:{...be.getState().quote}}},viaVoice:r.viaVoice};r.pending&&(F.options={...r.pending.options},F.contentSegments=r.pending.contentSegments,F.mentionRefs=[...r.pending.mentionRefs],F.viaVoice=r.pending.viaVoice);let q=()=>{if(v?.length)return[...v];if(!Ye?.hasAttachments())return;let ut=[...Ye.getContentParts()];return F.text&&ut.push(Ao(F.text)),ut};F.contentParts=q();let X=()=>{$r(),LS();let ut=Pt?.collectForSubmit()??null,Vt=HS(ut,f),Dt=q();r.consumeDraft!==!1&&Ql();let At={selectedModelId:F.options.selectedModelId,activeModeIds:F.options.activeModeIds},nn=$==="interrupt";nn&&E.cancel(),E.sendMessage(F.text,{contentParts:Dt,mentions:Vt??void 0,contentSegments:F.contentSegments,viaVoice:F.viaVoice,composerOptions:At,...F.options.quote&&{quote:F.options.quote},...nn&&{interrupt:!0}}),Ye?.hasAttachments()&&Ye.clearAttachments(),ut&&Pt?.clear(),Rr();let Je=be.getState().activeModeIds,on=Bb(Je,o.composer?.modes);on.length!==Je.length&&Za(on),be.getState().quote&&go(void 0),hl(),Wd.release(),eo()},oe=o.composer?.onBeforeSend;if(!oe){X();return}let pe=new AbortController;rs=pe;let Xe=ut=>{if(rs=null,ut.status==="error"){BS(ut.error);return}ut.status==="proceed"&&X()},ct=Qb(oe,F,pe.signal);if(!(ct instanceof Promise)){Xe(ct);return}return be.setPreparing(!0),ct.then(Xe).finally(()=>be.setPreparing(!1))};function DS(r){let a=be.getState(),p=Ye?.hasAttachments()??!1,f=p?[...Ye.getContentParts()]:[];p&&r.sendText&&f.push(Ao(r.sendText));let y=Nu({text:r.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Pt?.getMentionRefs()??[],...r.serverMentions?.refs??[]],contentSegments:Fp(),options:{...a.selectedModelId&&{selectedModelId:a.selectedModelId},...a.activeModeIds.length>0&&{activeModeIds:[...a.activeModeIds]},...a.quote&&{quote:{...a.quote}}},viaVoice:r.intent.viaVoice});ws(y),r.intent.consumeDraft!==!1&&Ql(),p&&Ye.clearAttachments(),Pt?.clear(),Rr(),a.quote&&go(void 0),hl(),Wd.release(),eo(),Qa("Message queued. It sends when the response finishes.")}function OS(){let r=be.getState().pendingSubmission;r&&(ws(void 0),Yl(r.text,{consumeDraft:!1,pending:r}))}function _S(r){if(o.messageActions?.showEdit!==!0)return;let a=E.getMessages().find(p=>p.id===r);!a||!yu(a)||Ur!==r&&($r(),Ur=r,dr=Fb({messageId:r,initialText:a.content,onSave:p=>NS(r,p),onCancel:()=>$r()}),Wt.delete(r),qn(ke,E.getMessages(),vt),dr.focus())}function NS(r,a){let p=dr;if(Ur=null,dr=null,p?.destroy(),Wt.delete(r),!E.resubmitFrom(r,{reason:"edit",replacement:{text:a,mentionRefs:[],options:{}}})){qn(ke,E.getMessages(),vt);return}Sn()}function FS(r){if(E.isStreaming())return;let a=hu(E.getMessages(),r);a&&($r(),E.resubmitFrom(a,{reason:"retry"})&&Sn())}el={regenerate:FS,edit:_S,quote:r=>{let p=E.getMessages().find(f=>f.id===r)?.content?.trim();p&&(go({text:p,messageId:r}),le?.focus())}};let na=async r=>{if(!jo){jo=!0;try{await Km({resolveInlineCommand:!0,...r})}finally{jo=!1}}};function Xl(r){Qr()||(Ql(),Yl(r,{consumeDraft:!1}))}let Yl=(r,a)=>{if(jo)return;jo=!0;let p=()=>{jo=!1};try{let f=Km({...a,overrideText:r});f instanceof Promise?f.finally(p):p()}catch(f){throw p(),f}},US=r=>{if(r.preventDefault(),E.isStreaming()){E.cancel(),ot?.reset(),gt?.update();return}jo||na()},$S=()=>o.features?.composerHistory!==!1,$p={...ju},qp=!1,oa=()=>{$p={...ju}},qS=()=>E.getMessages().filter(r=>r.role==="user").map(r=>r.content??"").filter(r=>r.length>0),zS=r=>{if(!le)return;qp=!0,le.value=r,le.dispatchEvent(new Event("input",{bubbles:!0})),qp=!1;let a=le.value.length;le.setSelectionRange(a,a)},jS=r=>{qp||(r.isComposing||Pt?.handleInput(r.inputType??void 0),oa())},VS=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ka(le)}),KS=r=>{if(le&&!bo()&&!(!r.isComposing&&Pt?.handleKeydown(r))){if($S()&&(r.key==="ArrowUp"||r.key==="ArrowDown")&&!r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.isComposing){let a=le.selectionStart===0&&le.selectionEnd===0,p=dv({direction:r.key==="ArrowUp"?"up":"down",history:qS(),currentValue:le.value,atStart:a,state:$p});if($p=p.state,p.handled){r.preventDefault(),p.value!==void 0&&zS(p.value);return}}if(vb(r,VS())){if(E.isStreaming()){if(r.preventDefault(),Pd()==="block"||jo||Qr())return;oa(),na();return}if(jo){r.preventDefault();return}if(Qr()){r.preventDefault();return}oa(),r.preventDefault(),xe.click()}}},Qm=r=>{if(!(r.key!=="Escape"||r.isComposing)&&r.composedPath().includes(de)){if(rs){rs.abort(),rs=null,r.preventDefault(),r.stopImmediatePropagation();return}E.isStreaming()&&(E.cancel(),ot?.reset(),gt?.update(),oa(),r.preventDefault(),r.stopImmediatePropagation())}},GS=async r=>{if(o.attachments?.enabled!==!0||!Ye||bo())return;let a=xT(r.clipboardData);a.length!==0&&(r.preventDefault(),await Ye.handleFiles(a))},Kn=null,wo=!1,Vs=null,ht=null,zp=()=>o.voiceRecognition?.completionBehavior==="review";function ss(r){ne?.setAttribute("data-state",r),r==="recording"?XS():Gp()}let Xm="--persona-voice-level",jp=.5,Ks=null,Vp=-1,Jl=0,Ym=()=>{let r=[],a=Ln??ne?.parentElement??null;return a&&r.push(a),Ie&&r.push(Ie),r},Kp=r=>{let a=Math.round(Math.max(0,Math.min(1,r))*100)/100;if(a!==Vp){Vp=a;for(let p of Ym())p.style.setProperty(Xm,String(a))}},QS=()=>{Vp=-1,Jl=0;for(let r of Ym())r.style.removeProperty(Xm)};function XS(){if(Ks!==null)return;if(typeof requestAnimationFrame!="function"){Kp(u?E.getVoiceLevel()??jp:jp);return}let r=()=>{Ks=requestAnimationFrame(r);let a=u?E.getVoiceLevel():null;if(a===null){Kp(jp);return}Jl+=(a-Jl)*.3,Kp(Jl)};Ks=requestAnimationFrame(r)}function Gp(){Ks!==null&&(cancelAnimationFrame(Ks),Ks=null),QS()}let Jm=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Zl=(r="user")=>{if(wo||E.isStreaming())return;let a=Jm();if(!a)return;Kn=new a;let p=o.voiceRecognition??{},f=p.pauseDuration??2e3;Kn.continuous=p.provider?.browser?.continuous??!0,Kn.interimResults=!0,Kn.lang=p.provider?.browser?.language??"en-US";let y=le.value;Kn.onresult=v=>{let B="",$="";for(let q=0;q<v.results.length;q++){let X=v.results[q],oe=X[0].transcript;X.isFinal?B+=oe+" ":$=oe}let F=y+B+$;le.value=F,uo(),Vs&&clearTimeout(Vs),(B||$)&&(Vs=window.setTimeout(()=>{if(le.value.trim()&&Kn&&wo){if(br(),zp())return;na({viaVoice:!0})}},f))},Kn.onerror=v=>{v.error!=="no-speech"&&br()},Kn.onend=()=>{if(wo){let v=le.value.trim();!zp()&&v&&v!==y.trim()&&na({viaVoice:!0}),br()}};try{if(Kn.start(),wo=!0,ze.active=!0,r!=="system"&&(ze.manuallyDeactivated=!1),Oo(r),oo(),eo(),ne){let v=o.voiceRecognition??{};ht={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:v.iconName??"mic",iconSize:parseFloat(v.iconSize??"")||pn};let B=v.recordingBackgroundColor,$=v.recordingIconColor,F=v.recordingBorderColor;if(ne.classList.add("persona-voice-recording"),ss("recording"),ne.style.backgroundColor=B??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=$??"var(--persona-voice-recording-indicator, #ffffff)",$){let q=ne.querySelector("svg");q&&q.setAttribute("stroke",$)}F&&(ne.style.borderColor=F),ne.setAttribute("aria-label","Stop voice recognition")}}catch{br("system")}},br=(r="user")=>{if(wo){if(wo=!1,Vs&&(clearTimeout(Vs),Vs=null),Kn){try{Kn.stop()}catch{}Kn=null}if(ze.active=!1,Oo(r),oo(),eo(),ne){if(ne.classList.remove("persona-voice-recording"),ss("idle"),ht){ne.style.backgroundColor=ht.backgroundColor,ne.style.color=ht.color,ne.style.borderColor=ht.borderColor;let a=ne.querySelector("svg");a&&a.setAttribute("stroke",ht.color||"currentColor"),ht=null}ne.setAttribute("aria-label","Start voice recognition")}}},Qp=()=>{if(!ne||ht)return;let r=o.voiceRecognition??{};ht={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:r.iconName??"mic",iconSize:parseFloat(r.iconSize??"")||pn}},Xp=(r,a)=>{if(!ne)return;let p=ne.querySelector("svg");p&&p.remove();let f=ht?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||pn),y=ge(r,f,a,1.5);y&&ne.appendChild(y)},ec=()=>{ne&&ne.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Gs=()=>{if(!ne)return;Qp();let r=o.voiceRecognition??{},a=r.recordingBackgroundColor,p=r.recordingIconColor,f=r.recordingBorderColor;if(ec(),ne.classList.add("persona-voice-recording"),ss("recording"),ne.style.backgroundColor=a??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=p??"var(--persona-voice-recording-indicator, #ffffff)",p){let y=ne.querySelector("svg");y&&y.setAttribute("stroke",p)}f&&(ne.style.borderColor=f),ne.setAttribute("aria-label","Stop voice recognition")},YS=()=>{if(!ne)return;Qp();let r=o.voiceRecognition??{},a=E.getVoiceInterruptionMode(),p=r.processingIconName??"loader",f=r.processingIconColor??ht?.color??"",y=r.processingBackgroundColor??ht?.backgroundColor??"",v=r.processingBorderColor??ht?.borderColor??"";ec(),ne.classList.add("persona-voice-processing"),ss("processing"),ne.style.backgroundColor=y,ne.style.borderColor=v;let B=f||"currentColor";ne.style.color=B,Xp(p,B),ne.setAttribute("aria-label","Processing voice input"),a==="none"&&(ne.style.cursor="default")},JS=()=>{if(!ne)return;Qp();let r=o.voiceRecognition??{},a=E.getVoiceInterruptionMode(),p=a==="cancel"?"square":a==="barge-in"?"mic":"volume-2",f=r.speakingIconName??p,y=r.speakingIconColor??(a==="barge-in"?r.recordingIconColor??ht?.color??"":ht?.color??""),v=r.speakingBackgroundColor??(a==="barge-in"?r.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":ht?.backgroundColor??""),B=r.speakingBorderColor??(a==="barge-in"?r.recordingBorderColor??"":ht?.borderColor??"");ec(),ne.classList.add("persona-voice-speaking"),ss("speaking"),ne.style.backgroundColor=v,ne.style.borderColor=B;let $=y||"currentColor";ne.style.color=$,Xp(f,$);let F=a==="cancel"?"Stop playback and re-record":a==="barge-in"?"Speak to interrupt":"Agent is speaking";ne.setAttribute("aria-label",F),a==="none"&&(ne.style.cursor="default"),a==="barge-in"&&ne.classList.add("persona-voice-recording")},Vo=()=>{ne&&(ec(),ss("idle"),ht&&(ne.style.backgroundColor=ht.backgroundColor??"",ne.style.color=ht.color??"",ne.style.borderColor=ht.borderColor??"",Xp(ht.iconName,ht.color||"currentColor"),ht=null),ne.style.cursor="",ne.setAttribute("aria-label","Start voice recognition"))},Yp=()=>{if(!bo()){if(Tn(o.voiceRecognition?.provider)){let r=E.getVoiceStatus(),a=E.getVoiceInterruptionMode();if(a==="none"&&(r==="processing"||r==="speaking"))return;if(a==="cancel"&&(r==="processing"||r==="speaking")){E.stopVoicePlayback();return}if(E.isBargeInActive()){E.stopVoicePlayback(),E.deactivateBargeIn().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,oo(),Oo("user"),Vo()});return}E.toggleVoice().then(()=>{ze.active=E.isVoiceActive(),ze.manuallyDeactivated=!E.isVoiceActive(),oo(),Oo("user"),E.isVoiceActive()?Gs():Vo()});return}if(wo){let r=le.value.trim();ze.manuallyDeactivated=!0,oo(),br("user"),r&&!zp()&&na()}else ze.manuallyDeactivated=!1,oo(),Zl("user")}};Id=Yp,ne&&fe.push(()=>{Tn(o.voiceRecognition?.provider)?(E.isVoiceActive()&&E.toggleVoice(),Vo()):br("system")});let ZS=w.on("assistant:complete",()=>{be.getState().pendingSubmission&&setTimeout(()=>{E.isStreaming()||OS()},0)});fe.push(ZS);let ex=w.on("assistant:complete",()=>{Nf&&(ze.active||ze.manuallyDeactivated||Nf==="assistant"&&!ze.lastUserMessageWasVoice||setTimeout(()=>{!ze.active&&!ze.manuallyDeactivated&&(Tn(o.voiceRecognition?.provider)?E.toggleVoice().then(()=>{ze.active=E.isVoiceActive(),Oo("auto"),E.isVoiceActive()&&Gs()}):Zl("auto"))},600))});fe.push(ex);let tx=w.on("action:resubmit",()=>{setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)});fe.push(tx);let Zm=()=>{pt(!ve,"user")},St=null,dn=null;if(ce&&!Le()){let{instance:r,element:a}=dg({config:o,plugins:l,onToggle:Zm});St=r,r||(dn=a)}St?t.appendChild(St.element):dn&&t.appendChild(dn),Ui(),Ts(),Al(),ap(),$i(E.isStreaming()),Qd()||(Hn()==="follow"?gr(!0):yl()),Cw(),ye&&(!ce||Le()?setTimeout(()=>Xr(),0):ve&&setTimeout(()=>Xr(),200));let is=null,eh=()=>{is&&(is.disconnect(),is.observe(Ie),is.observe(de))},ra=()=>{if(Le()){Hr(),Ui();return}let r=Lt(o),a=o.launcher?.sidebarMode??!1,p=t.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640,v=p.innerWidth<=y,B=f&&v&&ce;try{if(B){Wr(),Li=ll();return}let $=!1;qt&&(qt=!1,Wr(),$=!0);let F=ll();if(!$&&F!==Li&&(Wr(),$=!0),Li=F,$&&rl(),!ce&&!r){we.style.height="",we.style.width="";return}if(!a&&!r){let X=o?.launcher?.width??o?.launcherWidth??Jo;we.style.width=X,we.style.maxWidth=X}al(),xf()}finally{if(Hr(),Ja(),Ui(),ve&&ce){let F=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),q=o.launcher?.sidebarMode??!1,X=o.launcher?.mobileFullscreen??!0,oe=Lt(o)&&X&&F,pe=q||X&&F&&ce||oe;if(pe&&!yo){let Xe=t.getRootNode(),ct=Xe instanceof ShadowRoot?Xe.host:t.closest(".persona-host");ct&&!ho&&(ho=Vu(ct,o.launcher?.zIndex??an)),yo=Ku(t.ownerDocument)}else pe||(ho?.(),ho=null,yo?.(),yo=null)}}};ra();let tc=t.ownerDocument.defaultView??window;if(tc.addEventListener("resize",ra),fe.push(()=>tc.removeEventListener("resize",ra)),typeof ResizeObserver<"u"){is=new ResizeObserver(()=>{Ja()}),eh(),fe.push(()=>{is?.disconnect(),is=null});let r=new ResizeObserver(()=>{Fl()});r.observe(de),fe.push(()=>r.disconnect())}tc.addEventListener("resize",Fl),fe.push(()=>tc.removeEventListener("resize",Fl)),Bn=te.scrollTop;let th=Qo(te),nh=()=>{let r=te.scrollTop,a=Qo(te),p=a<th;if(th=a,!sr()){Bn=r,Ut();return}let{action:f,nextLastScrollTop:y}=Gh({following:Wn.isFollowing(),currentScrollTop:r,lastScrollTop:Bn,nearBottom:cs(te,Bo),userScrollThreshold:hw,isAutoScrolling:Cn||dl||p,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Bn=y,f==="resume"){bl()||wn();return}f==="pause"&&Di()};if(te.addEventListener("scroll",nh,{passive:!0}),fe.push(()=>te.removeEventListener("scroll",nh)),typeof ResizeObserver<"u"){let r=new ResizeObserver(()=>{Tw(),su(ke)});r.observe(ke),r.observe(te),fe.push(()=>r.disconnect())}let oh=()=>{sr()&&Wn.isFollowing()&&bl()&&Di()},rh=te.ownerDocument;rh.addEventListener("selectionchange",oh),fe.push(()=>{rh.removeEventListener("selectionchange",oh)});let nx=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),sh=r=>{nx.has(r.key)&&(Vr(),qg()&&sr()&&Wn.isFollowing()&&Di())},ih=r=>{r.target?.closest("a, button, [tabindex], input, textarea, select")&&(Vr(),qg()&&sr()&&Wn.isFollowing()&&Di())};te.addEventListener("keydown",sh),te.addEventListener("focusin",ih),fe.push(()=>{te.removeEventListener("keydown",sh),te.removeEventListener("focusin",ih)});let ah=r=>{if(r.deltaY!==0&&Vr(),!sr())return;let a=Qh({following:Wn.isFollowing(),deltaY:r.deltaY,nearBottom:cs(te,Bo),resumeWhenNearBottom:!0});a==="pause"?Di():a==="resume"&&!bl()&&wn()};te.addEventListener("wheel",ah,{passive:!0}),te.addEventListener("touchmove",Vr,{passive:!0}),te.addEventListener("pointerdown",Vr,{passive:!0}),fe.push(()=>{te.removeEventListener("touchmove",Vr),te.removeEventListener("pointerdown",Vr)}),fe.push(()=>te.removeEventListener("wheel",ah)),Rt.addEventListener("click",()=>{ro(),te.scrollTop=te.scrollHeight,Bn=te.scrollTop,wn(),gr(!0),Ut()}),fe.push(()=>Rt.remove()),fe.push(()=>{zf(),ro()});let lh=()=>{_e&&(_r&&(_e.removeEventListener("click",_r),_r=null),Fe()?(_e.style.display="",_r=()=>{pt(!1,"user")},_e.addEventListener("click",_r)):_e.style.display="none")};lh(),(()=>{let{clearChatButton:r}=Be;r&&r.addEventListener("click",()=>{if(Co()){Op({focusComposer:!0}).catch(p=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",p)});return}E.clearMessages(),Wt.clear(),wn(),si(Be.composerOverlay);try{localStorage.removeItem(Ci),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ci}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ci)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),K?.clear&&fl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),Z={},he.syncFromMetadata(),Ye?.clearAttachments(),hl(),ws(void 0),go(void 0),$r(),Re?.clear(),ot?.reset(),gt?.update()})})();let ch=[["keydown",KS],["input",jS],["input",uo],["input",Rr],["keyup",Rr],["paste",GS],["focus",rw]],dh=r=>{if(r)for(let[a,p]of ch)et?.addListener(r,a,p)},ox=r=>{if(r)for(let[a,p]of ch)et?.removeListener(r,a,p)},ph=()=>{et&&(et.addListener(et.form,"submit",US),et.addListener(et.footer,"click",Rr),dh(le),ne&&et.addListener(ne,"click",Yp))};ph();let uh=()=>{Pt?.onComposerSwap((r,a)=>{ox(a),le=r,et&&(et.input=r),dh(r),Hd(),ep(),uo()})};uh();let Jp=!1;function gh(){if(!Jp){Jp=!0;try{let r=le?.value??"",a=Ie.ownerDocument??document,p=le?a.activeElement===le:!1;Gp(),et?.destroy(),et=null,Pt?.destroy(),Pt=null;let f=null,y=()=>(f=Le()?ed({config:o}):_a({config:o}),f.footer),v=Zg(y)??y();Pn.replaceComposer(v),Ie=Pn.composer.footer;let B=f!==null&&v===f.footer;xs=!B,$g=B?f.setSendButtonMode:()=>{},Jg(Ie),tf(Ie),nf(),of(),rf(),uh(),sf(),Rd(),af(),ph();let $=Or.indexOf(Wo);Wo.destroy(),Wo=Da(or),$>=0&&(Or[$]=Wo),le&&(le.value=r),uo(),Rr(),Al(),Ts(),$i(E.isStreaming()),ze.active&&ss("recording"),Wr(),eh(),Hr(),eo(),Sl(),p&&le?.focus()}finally{Jp=!1}}}let sa=t.ownerDocument??document;sa.addEventListener("keydown",Qm,!0);let fh=()=>{jd()},mh=()=>{sa.visibilityState==="hidden"&&jd()};typeof window<"u"&&(window.addEventListener("pagehide",fh),sa.addEventListener("visibilitychange",mh),fe.push(()=>{window.removeEventListener("pagehide",fh),sa.removeEventListener("visibilitychange",mh)}));let hh="persona-attachment-drop-active",ia=0,Zp=()=>{ia=0,de.classList.remove(hh)},Qs=()=>o.attachments?.enabled===!0&&Ye!==null&&!bo(),yh=r=>{!hd(r.dataTransfer)||!Qs()||(ia++,ia===1&&de.classList.add(hh))},bh=r=>{!hd(r.dataTransfer)||!Qs()||(ia--,ia<=0&&Zp())},vh=r=>{!hd(r.dataTransfer)||!Qs()||(r.preventDefault(),r.dataTransfer.dropEffect="copy")},Ch=r=>{if(!hd(r.dataTransfer)||!Qs())return;r.preventDefault(),r.stopPropagation(),Zp();let a=Array.from(r.dataTransfer.files??[]);a.length!==0&&Ye.handleFiles(a)},vr=!0;de.addEventListener("dragenter",yh,vr),de.addEventListener("dragleave",bh,vr),t.addEventListener("dragover",vh,vr),t.addEventListener("drop",Ch,vr);let nc=t.ownerDocument,wh=r=>{Qs()&&r.preventDefault()},Sh=r=>{Qs()&&r.preventDefault()};nc.addEventListener("dragover",wh),nc.addEventListener("drop",Sh),fe.push(()=>{et?.destroy(),et=null,Gp(),fo?.destroy(),fo=null,Ho?.destroy(),Ho=null,ar?.destroy(),ar=null,lr?.destroy(),lr=null,ir=null,kd=null,jd(),Bi.destroy(),js&&clearTimeout(js),$r(),rs?.abort(),rs=null,Ye?.destroy(),Ye=null,be.destroy(),sa.removeEventListener("keydown",Qm,!0),Pt?.destroy()}),fe.push(()=>{de.removeEventListener("dragenter",yh,vr),de.removeEventListener("dragleave",bh,vr),t.removeEventListener("dragover",vh,vr),t.removeEventListener("drop",Ch,vr),nc.removeEventListener("dragover",wh),nc.removeEventListener("drop",Sh),Zp()}),fe.push(()=>{E.cancel()}),St?fe.push(()=>{St?.destroy()}):dn&&fe.push(()=>{dn?.remove()});let xt={update(r){let a=o.toolCall,p=o.messageActions,f=o.layout?.messages,y=o.colorScheme,v=o.loadingIndicator,B=o.iterationDisplay,$=o.features?.showReasoning,F=o.features?.showToolCalls,q=o.features?.toolCallDisplay,X=o.features?.reasoningDisplay,oe=o.features?.streamAnimation?.type,pe=o.features?.history?.enabled===!0,Xe=o.features?.history?.provider,ct=o.getIdentityProof,ut=o.clientToken,Vt=o.contextMentions;o=cC({...o,features:i},r),i=o.features,o=wg(o),s(),Nd(),Ia(t,o),Ua(t,o),$a(t,o),Io(),no(),o.colorScheme!==y&&Af();let Dt=Ag.getForInstance(o.plugins);l.length=0,l.push(...Dt),xm(),ce=o.launcher?.enabled??!0,at=o.launcher?.autoExpand??!1,Po=o.features?.showReasoning??!0,j=o.features?.showToolCalls??!0,_=o.features?.scrollToBottom??{};let At=Hn();V=o.features?.scrollBehavior??{},At!==Hn()&&(ro(),wn()),_f(),Vg(),Ut();let nn=C;if(C=o.features?.showEventStreamToggle??!1,C&&!nn){if(Re||(ja(),E.setSSEEventCallback((Y,je)=>{o.onSSEEvent?.(Y,je),bd(Y,je)})),!Ze&&Ae){let Y=o.features?.eventStream?.classNames,je="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"+(Y?.toggleButton?" "+Y.toggleButton:"");Ze=k("button",je),Ze.style.width="28px",Ze.style.height="28px",Ze.style.color=gn.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let Ge=en(MC,"18px","currentColor",1.5);Ge&&Ze.appendChild(Ge);let tt=Be.clearChatButtonWrapper,yt=Be.closeButtonWrapper,Zt=tt||yt;Zt&&Zt.parentNode===Ae?Ae.insertBefore(Ze,Zt):Ae.appendChild(Ze),Ze.addEventListener("click",()=>{zt?Ss():Ld()})}}else!C&&nn&&(Ss(),Ze&&(Ze.remove(),Ze=null),Re?.clear(),Me?.destroy(),Re=null,Me=null,ot?.reset(),ot=null,Ve=null);if(o.launcher?.enabled===!1&&St&&(St.destroy(),St=null),o.launcher?.enabled===!1&&dn&&(dn.remove(),dn=null),o.launcher?.enabled!==!1&&!St&&!dn){let{instance:Y,element:je}=dg({config:o,plugins:l,onToggle:Zm});St=Y,Y||(dn=je),t.appendChild(je)}St&&St.update(o),ta(),Ir&&o.launcher?.subtitle!==void 0&&(Ir.textContent=o.launcher.subtitle);let Je=o.layout?.header;if(Je?.layout!==Ue&&Ae){let Y=Je?Zc(o,Je,{showClose:Fe(),onClose:()=>pt(!1,"user")}):fs({config:o,showClose:Fe(),onClose:()=>pt(!1,"user")});Pn.replaceHeader(Y),Ae=Pn.header.element,wt=Pn.header.iconHolder,rr=Pn.header.headerTitle,Ir=Pn.header.headerSubtitle,_e=Pn.header.closeButton,Ue=Je?.layout,ta()}else if(Je){if(wt&&(wt.style.display=Je.showIcon===!1?"none":""),rr&&(rr.style.display=Je.showTitle===!1?"none":""),Ir&&(Ir.style.display=Je.showSubtitle===!1?"none":""),_e){let Y=Fe()&&Je.showCloseButton!==!1;_e.style.display=Y?"":"none"}if(Be.clearChatButtonWrapper){let Y=Je.showClearChat;if(Y!==void 0){Be.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:je}=Be;je&&!je.classList.contains("persona-absolute")&&(Y?je.classList.remove("persona-ml-auto"):je.classList.add("persona-ml-auto"))}}}let So=o.layout?.showHeader!==!1;Ae&&(Ae.style.display=So?"":"none");let Ko=o.layout?.showFooter!==!1;Ie&&(Ie.style.display=Ko?"":"none"),Hr(),Ut(),ce!==Te?ce?pt(at,"auto"):(ve=!0,Ui()):at!==N&&pt(at,"auto"),N=at,Te=ce,ra(),lh();let as=JSON.stringify(o.toolCall)!==JSON.stringify(a),io=JSON.stringify(o.messageActions)!==JSON.stringify(p),Yt=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),ao=o.loadingIndicator?.render!==v?.render||o.loadingIndicator?.renderIdle!==v?.renderIdle||o.loadingIndicator?.showBubble!==v?.showBubble,Xs=o.iterationDisplay!==B,P=(o.features?.showReasoning??!0)!==($??!0)||(o.features?.showToolCalls??!0)!==(F??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(q)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(X);(as||io||Yt||ao||Xs||P)&&E&&(qr++,qn(ke,E.getMessages(),vt));let Se=o.features?.streamAnimation?.type;if(Se!==oe&&Se&&Se!=="none"){let Y=Ud(Se,o.features?.streamAnimation?.plugins);Y&&ma(Y,t)}let se=o.launcher??{},Mt=se.headerIconHidden??!1,Ot=o.layout?.header?.showIcon,Jt=Mt||Ot===!1,_t=se.headerIconName,$t=se.headerIconSize??"48px";if(wt){let Y=Ae,je=Y?.querySelector(".persona-flex-col");if(Jt)wt.style.display="none",Y&&je&&!Y.contains(je)&&Y.insertBefore(je,Y.firstChild);else{if(wt.style.display="",wt.style.height=$t,wt.style.width=$t,Y&&je&&(Y.contains(wt)?wt.nextSibling!==je&&(wt.remove(),Y.insertBefore(wt,je)):Y.insertBefore(wt,je)),_t){let tt=parseFloat($t)||24,yt=ge(_t,tt*.6,"currentColor",1);yt?wt.replaceChildren(yt):wt.textContent=se.agentIconText??"\u{1F4AC}"}else if(se.iconUrl){let tt=wt.querySelector("img");if(tt)tt.src=se.iconUrl,tt.style.height=$t,tt.style.width=$t;else{let yt=document.createElement("img");yt.src=se.iconUrl,yt.alt="",yt.className="persona-rounded-xl persona-object-cover",yt.style.height=$t,yt.style.width=$t,wt.replaceChildren(yt)}}else{let tt=wt.querySelector("svg"),yt=wt.querySelector("img");(tt||yt)&&wt.replaceChildren(),wt.textContent=se.agentIconText??"\u{1F4AC}"}let Ge=wt.querySelector("img");Ge&&(Ge.style.height=$t,Ge.style.width=$t)}}let Et=o.layout?.header?.showTitle,rn=o.layout?.header?.showSubtitle;if(rr&&(rr.style.display=Et===!1?"none":""),Ir&&(Ir.style.display=rn===!1?"none":""),_e){let Y=Fe()&&o.layout?.header?.showCloseButton!==!1;if(_e.style.display=Y?"":"none",!Le()){let Kt=se.closeButtonSize??"";_e.style.height=Kt,_e.style.width=Kt,_e.style.minWidth=Kt,_e.style.minHeight=Kt}let je=se.closeButtonPlacement??"inline",{closeButtonWrapper:Ge}=Be,tt=je==="top-right",yt=Ge?.classList.contains("persona-absolute");if(Ge&&tt!==yt)if(Ge.remove(),tt){Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Kt=Ki??de;Kt.style.position="relative",Kt.appendChild(Ge)}else{let Kt=se.clearChat?.placement??"inline",Gt=se.clearChat?.enabled??!0;Ge.className=Gt&&Kt==="inline"?"":"persona-ml-auto",Ae&&Ae.appendChild(Ge)}if(_e.style.color=se.closeButtonColor||gn.actionIconColor,se.closeButtonBackgroundColor?(_e.style.backgroundColor=se.closeButtonBackgroundColor,_e.classList.remove("hover:persona-bg-gray-100")):(_e.style.backgroundColor="",_e.classList.add("hover:persona-bg-gray-100")),se.closeButtonBorderWidth||se.closeButtonBorderColor){let Kt=se.closeButtonBorderWidth||"0px",Gt=se.closeButtonBorderColor||"transparent";_e.style.border=`${Kt} solid ${Gt}`,_e.classList.remove("persona-border-none")}else _e.style.border="",_e.classList.add("persona-border-none");se.closeButtonBorderRadius?(_e.style.borderRadius=se.closeButtonBorderRadius,_e.classList.remove("persona-rounded-full")):(_e.style.borderRadius="",_e.classList.add("persona-rounded-full")),se.closeButtonPaddingX?(_e.style.paddingLeft=se.closeButtonPaddingX,_e.style.paddingRight=se.closeButtonPaddingX):(_e.style.paddingLeft="",_e.style.paddingRight=""),se.closeButtonPaddingY?(_e.style.paddingTop=se.closeButtonPaddingY,_e.style.paddingBottom=se.closeButtonPaddingY):(_e.style.paddingTop="",_e.style.paddingBottom=""),Jc(_e,se.closeButtonIconName??"x",{iconSize:Le()?ig:void 0,iconText:se.closeButtonIconText??"\xD7"});let Zt=se.closeButtonTooltipText??"Close chat",lo=se.closeButtonShowTooltip??!0;_e.setAttribute("aria-label",Zt),Ge&&Qt({anchor:_e,trigger:Ge,text:()=>_e?.getAttribute("aria-label")??Zt,enabled:lo})}let{clearChatButton:He,clearChatButtonWrapper:De}=Be;if(He){let Y=se.clearChat??{},je=Y.enabled??!0,Ge=o.layout?.header?.showClearChat,tt=Ge!==void 0?Ge:je,yt=Y.placement??"inline";if(De){De.style.display=tt?"":"none";let{closeButtonWrapper:Zt}=Be;!Le()&&Zt&&!Zt.classList.contains("persona-absolute")&&(tt?Zt.classList.remove("persona-ml-auto"):Zt.classList.add("persona-ml-auto"));let lo=yt==="top-right",Kt=De.classList.contains("persona-absolute");if(!Le()&&lo!==Kt&&tt){if(De.remove(),lo){De.className="persona-absolute persona-top-4 persona-z-50",De.style.right="48px";let xo=Ki??de;xo.style.position="relative",xo.appendChild(De)}else{De.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",De.style.right="";let xo=Be.closeButtonWrapper;Ae&&xo&&xo.parentElement===Ae?Ae.insertBefore(De,xo):Ae&&Ae.appendChild(De)}let Gt=Be.closeButtonWrapper;Gt&&!Gt.classList.contains("persona-absolute")&&(lo?Gt.classList.add("persona-ml-auto"):Gt.classList.remove("persona-ml-auto"))}}if(tt){if(!Le()){let Gt=Y.size??"";He.style.height=Gt,He.style.width=Gt,He.style.minWidth=Gt,He.style.minHeight=Gt}let Zt=Y.iconColor??"";if(He.style.color=Zt||gn.actionIconColor,Jc(He,Y.iconName??"refresh-cw",{iconSize:Le()?ag:void 0}),Y.backgroundColor?(He.style.backgroundColor=Y.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let Gt=Y.borderWidth||"0px",xo=Y.borderColor||"transparent";He.style.border=`${Gt} solid ${xo}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");Y.borderRadius?(He.style.borderRadius=Y.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),Y.paddingX?(He.style.paddingLeft=Y.paddingX,He.style.paddingRight=Y.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),Y.paddingY?(He.style.paddingTop=Y.paddingY,He.style.paddingBottom=Y.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let lo=Y.tooltipText??"Clear chat",Kt=Y.showTooltip??!0;He.setAttribute("aria-label",lo),De&&Qt({anchor:He,trigger:De,text:()=>He?.getAttribute("aria-label")??lo,enabled:Kt})}}let Ce=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Eg],sn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[qa.message,qa.messageAndClick];he=Tg({parsers:Ce,handlers:sn,getSessionMetadata:ae,updateSessionMetadata:re,emit:w.emit,documentRef:typeof document<"u"?document:null}),vt=PC(o,he,ko),jw(),E.updateConfig(o),(o.features?.history?.enabled===!0!==pe||o.features?.history?.provider!==Xe||o.getIdentityProof!==ct||o.clientToken!==ut)&&(xn({restoreFocus:!1}),mm()),yr(),Fl(),qn(ke,E.getMessages(),vt),Ts(),Al(),qw(),$i(E.isStreaming()),Vt!==o.contextMentions&&gh();let Cr=o.voiceRecognition?.enabled===!0,An=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Mn=Tn(o.voiceRecognition?.provider);if(Cr&&(An||Mn))if(!ne||!Ln){let Y=li(o);if(Y){ne=Y.button,Ln=Y.wrapper;let je=po&&po.parentElement===Ka?po:null;Ka?Ka.insertBefore(Ln,je):Zn?.appendChild(Ln),et&&(et.micButton=ne),et?.addListener(ne,"click",Yp),ne.disabled=bo()||E.isStreaming()&&!Jd()}}else{let Y=o.voiceRecognition??{},je=o.sendButton??{},Ge=Y.iconName??"mic",tt=Y.iconSize,yt=parseFloat(tt??"")||pn;ne.classList.add(Nn),ne.classList.toggle(co,!tt),ne.style.width=tt??"",ne.style.height=tt??"",ne.style.minWidth=tt??"",ne.style.minHeight=tt??"";let Zt=Y.iconColor??je.textColor;ne.innerHTML="";let lo=ge(Ge,yt,Zt||"currentColor",1.5);lo?ne.appendChild(lo):ne.textContent="\u{1F3A4}";let Kt=Y.backgroundColor??je.backgroundColor;Kt?ne.style.backgroundColor=Kt:ne.style.backgroundColor="",Zt?ne.style.color=Zt:ne.style.color="var(--persona-text, #111827)",Y.borderWidth?(ne.style.borderWidth=Y.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),Y.borderColor?ne.style.borderColor=Y.borderColor:ne.style.borderColor="",Y.paddingX?(ne.style.paddingLeft=Y.paddingX,ne.style.paddingRight=Y.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),Y.paddingY?(ne.style.paddingTop=Y.paddingY,ne.style.paddingBottom=Y.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let Gt=Y.tooltipText??"Start voice recognition",xo=Y.showTooltip??!1;ne.setAttribute("aria-label",Gt),Ln&&Qt({anchor:ne,trigger:Ln,text:()=>ne?.getAttribute("aria-label")??Gt,enabled:xo}),Ln.style.display="",ne.disabled=bo()||E.isStreaming()&&!Jd()}else ne&&Ln&&(Ln.style.display="none",Tn(o.voiceRecognition?.provider)?E.isVoiceActive()&&E.toggleVoice():wo&&br());if(o.attachments?.enabled===!0){if(!bn||!bt){let Y=o.attachments??{};vn||(vn=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),vn.style.display="none",(le.parentElement??Zn).insertBefore(vn,le)),ft||(ft=document.createElement("input"),ft.type="file",ft.accept=(Y.allowedTypes??Yo).join(","),ft.multiple=(Y.maxFiles??4)>1,ft.style.display="none",ft.setAttribute("aria-label","Attach files"),(le.parentElement??Zn).insertBefore(ft,le)),bn=k("div","persona-send-button-wrapper"),bt=k("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Nn} ${co}`),bt.type="button",bt.setAttribute("aria-label",Y.buttonTooltipText??"Attach file");let je=Y.buttonIconName??"paperclip";bt.style.fontSize="18px",bt.style.lineHeight="1";let Ge=ge(je,pn,"currentColor",1.5);Ge?bt.appendChild(Ge):bt.textContent="\u{1F4CE}",bt.addEventListener("click",yt=>{yt.preventDefault(),ft?.click()}),bn.appendChild(bt);let tt=Y.buttonTooltipText??"Attach file";Qt({anchor:bt,trigger:bn,text:()=>bt?.getAttribute("aria-label")??tt}),Sd?Sd.append(bn):Zn.appendChild(bn),et&&(et.attachmentButton=bt,et.attachmentInput=ft??void 0,et.attachmentPreviews=vn??void 0),!Ye&&ft&&vn&&(Ye=Ma.fromConfig(Y,Kg),Ye.setPreviewsContainer(vn),et?.addListener(ft,"change",async()=>{Ye&&ft?.files&&(await Ye.handleFileSelect(ft.files),ft.value="")}))}else{bn.style.display="";let Y=o.attachments??{};ft&&(ft.accept=(Y.allowedTypes??Yo).join(","),ft.multiple=(Y.maxFiles??4)>1),Ye&&Ye.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles,adapter:Y.adapter})}if(de.querySelector(".persona-attachment-drop-overlay")?.remove(),de.appendChild(IC(o.attachments?.dropOverlay)),bt){let Y=o.attachments??{},je=Y.buttonTooltipText??"Attach file";bt.setAttribute("aria-label",je),bt.textContent="";let Ge=ge(Y.buttonIconName??"paperclip",pn,"currentColor",1.5);Ge?bt.appendChild(Ge):bt.textContent="\u{1F4CE}",bn&&Qt({anchor:bt,trigger:bn,text:()=>bt?.getAttribute("aria-label")??je})}}else bn&&(bn.style.display="none"),Ye&&Ye.clearAttachments(),de.querySelector(".persona-attachment-drop-overlay")?.remove();let We=o.sendButton??{},Go=We.useIcon??!1,It=We.iconText??"\u2191",En=We.iconName,la=We.tooltipText??"Send message",ix=We.showTooltip??!1,ca=We.size,ax=parseFloat(ca??"")||Hu,oc=We.backgroundColor,da=We.textColor;if(Go){if(xe.style.width=ca??"",xe.style.height=ca??"",xe.style.minWidth=ca??"",xe.style.minHeight=ca??"",xe.style.fontSize="18px",xe.style.lineHeight="1",da?xe.style.color=da:xe.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!E.isStreaming())if(xe.innerHTML="",En){let Y=parseFloat(We.iconSize??"")||Math.round(ax*.5),je=da?.trim()||"currentColor",Ge=We.iconStrokeWidth??2,tt=ge(En,Y,je,Ge),yt=ge(We.stopIconName??"square",Y,je,Ge);tt&&yt?xe.appendChild(Ru(tt,yt)):tt?xe.appendChild(tt):xe.textContent=It}else xe.textContent=It;xe.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Nn}`,oc?(xe.style.backgroundColor=oc,xe.classList.remove("persona-bg-persona-primary")):(xe.style.backgroundColor="",xe.classList.add("persona-bg-persona-primary"))}else xe.textContent=o.copy?.sendButtonLabel??"Send",xe.style.width="",xe.style.height="",xe.style.minWidth="",xe.style.minHeight="",xe.style.fontSize="",xe.style.lineHeight="",xe.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?(xe.style.backgroundColor=oc,xe.classList.remove("persona-bg-persona-accent")):xe.classList.add("persona-bg-persona-accent"),da?xe.style.color=da:xe.classList.add("persona-text-white");We.borderWidth?(xe.style.borderWidth=We.borderWidth,xe.style.borderStyle="solid"):(xe.style.borderWidth="",xe.style.borderStyle=""),We.borderColor?xe.style.borderColor=We.borderColor:xe.style.borderColor="",We.paddingX?(xe.style.paddingLeft=We.paddingX,xe.style.paddingRight=We.paddingX):(xe.style.paddingLeft="",xe.style.paddingRight=""),We.paddingY?(xe.style.paddingTop=We.paddingY,xe.style.paddingBottom=We.paddingY):(xe.style.paddingTop="",xe.style.paddingBottom=""),E.isStreaming()||xe.setAttribute("aria-label",la),Sl(),po&&Qt({anchor:xe,trigger:po,text:()=>xe.getAttribute("aria-label")??la,enabled:ix}),cf();let xh=qc(be.getState().activeModeIds,o.composer?.modes);be.setActiveModeIds(xh),vs().length>0!==!!Ho&&Rd(),Ho?.render(xh,vs());for(let Y of[...Cs.keys()])$c(Y,o.composer?.modeGroups)||Cs.delete(Y);Cs.forEach(Y=>Y.repaint()),ir?.repaint(),fo?.resolve();let rc=kr(o,Le());if(Fd(),rc){ke.style.maxWidth=rc,ke.style.marginLeft="auto",ke.style.marginRight="auto",ke.style.width="100%",In.style.maxWidth=rc,In.style.marginLeft="auto",In.style.marginRight="auto",In.style.width="100%";for(let Y of[Zn,or,vn,rt])Y&&(Y.style.maxWidth=rc,Y.style.marginLeft="auto",Y.style.marginRight="auto",Y.style.width="100%")}else{ke.style.maxWidth="",ke.style.marginLeft="",ke.style.marginRight="",ke.style.width="",In.style.maxWidth="",In.style.marginLeft="",In.style.marginRight="",In.style.width="";for(let Y of[Zn,or,vn,rt])Y&&(Y.style.maxWidth="",Y.style.marginLeft="",Y.style.marginRight="",Y.style.width="")}let wr=o.statusIndicator??{},lx=wr.visible??!0;if(rt.style.display=lx?"":"none",E){let Y=E.getStatus();Va(rt,(Ge=>Ge==="idle"?wr.idleText??Nt.idle:Ge==="connecting"?wr.connectingText??Nt.connecting:Ge==="connected"?wr.connectedText??Nt.connected:Ge==="error"?wr.errorText??Nt.error:Nt[Ge])(Y),wr,Y)}rt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let cx=wr.align==="left"?"persona-text-left":wr.align==="center"?"persona-text-center":"persona-text-right";rt.classList.add(cx),Hd(),ep(),eo(),vd()},open(){Fe()&&pt(!0,"api")},close(){Fe()&&pt(!1,"api")},toggle(){Fe()&&pt(!ve,"api")},reconnect(){E.reconnectNow()},clearChat(){Ro=!1,E.clearMessages(),Wt.clear(),wn();try{localStorage.removeItem(Ci),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ci}`)}catch(a){console.error("[AgentWidget] Failed to clear default localStorage:",a)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ci)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(a){console.error("[AgentWidget] Failed to clear custom localStorage:",a)}let r=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(r),K?.clear&&fl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),Z={},he.syncFromMetadata(),Ye?.clearAttachments(),hl(),ws(void 0),go(void 0),$r(),Re?.clear(),ot?.reset(),gt?.update()},setMessage(r){return!le||E.isStreaming()||bo()?!1:(!ve&&Fe()&&pt(!0,"system"),le.value=r,le.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(r){if(E.isStreaming()||Qr())return!1;let a=r?.trim()||le.value.trim();return a?(!ve&&Fe()&&pt(!0,"system"),le.value="",le.style.height="auto",uo(),Yl(a,{consumeDraft:!1}),!0):!1},getComposerState(){return be.getState()},setQuote(r){let a=r?.text?.trim();a&&go({...r,text:a})},clearQuote(){go(void 0)},startVoiceRecognition(){return E.isStreaming()?!1:Tn(o.voiceRecognition?.provider)?(E.isVoiceActive()||E.isBargeInActive()||(!ve&&Fe()&&pt(!0,"system"),ze.manuallyDeactivated=!1,oo(),E.toggleVoice().then(()=>{ze.active=E.isVoiceActive(),Oo("user"),E.isVoiceActive()&&Gs()})),!0):wo?!0:Jm()?(!ve&&Fe()&&pt(!0,"system"),ze.manuallyDeactivated=!1,oo(),Zl("user"),!0):!1},stopVoiceRecognition(){return Tn(o.voiceRecognition?.provider)?!E.isVoiceActive()&&!E.isBargeInActive()?!1:((E.isBargeInActive()?E.deactivateBargeIn():E.toggleVoice()).then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,oo(),Oo("user"),Vo()}),!0):wo?(ze.manuallyDeactivated=!0,oo(),br("user"),!0):!1},injectMessage(r){return!ve&&Fe()&&pt(!0,"system"),E.injectMessage(r)},injectAssistantMessage(r){!ve&&Fe()&&pt(!0,"system");let a=E.injectAssistantMessage(r);return ln&&(ln=!1,Jn&&(clearTimeout(Jn),Jn=null),setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)),a},injectUserMessage(r){return!ve&&Fe()&&pt(!0,"system"),E.injectUserMessage(r)},injectSystemMessage(r){return!ve&&Fe()&&pt(!0,"system"),E.injectSystemMessage(r)},injectMessageBatch(r){return!ve&&Fe()&&pt(!0,"system"),E.injectMessageBatch(r)},injectComponentDirective(r){return!ve&&Fe()&&pt(!0,"system"),E.injectComponentDirective(r)},injectTestMessage(r){!ve&&Fe()&&pt(!0,"system"),E.injectTestEvent(r)},async connectStream(r,a){return E.connectStream(r,a)},__pushEventStreamEvent(r){C&&(ja(),bd(r.type,r.payload))},showEventStream(){C&&Ld()},hideEventStream(){zt&&Ss()},isEventStreamVisible(){return zt},listConversations(r){return E.listConversations(r)},getActiveConversationId(){return E.getActiveConversationId()},openConversation(r,a){return Dp(r,{focusComposer:a?.focus===!0})},startNewConversation(r){return Op({focusComposer:r?.focus===!0})},deleteConversation(r){return Um(r)},renameConversation(r,a){return _p(r,{title:a})},setConversationStarred(r,a){return _p(r,{starred:a})},clearConversationHistory(r){return $m(r)},resetHistoryIdentity(){return qm()},getHistoryIdentityStatus(){return Dn?Dn.getIdentityStatus():vp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(r){return ea({...r?.returnSurface?{returnSurface:r.returnSurface}:{},...r?.focus!==void 0?{focus:r.focus}:{}})},hideHistory(r){xn(r?.restoreFocus!==void 0?{restoreFocus:r.restoreFocus}:void 0)},isHistoryVisible(){return Ct},showArtifacts(){mn(o)&&(Ro=!1,As=!0,no(),qe?.setMobileOpen(!0))},hideArtifacts(){mn(o)&&(Ro=!0,no())},upsertArtifact(r){return mn(o)?(Sr(o.features?.artifacts,{artifactType:r.artifactType,...r.artifactType==="markdown"&&r.file?{file:r.file}:{},...r.presentation?{presentation:r.presentation}:{}})==="panel"&&(Ro=!1,As=!0),E.upsertArtifact(r)):null},selectArtifact(r){mn(o)&&E.selectArtifact(r)},clearArtifacts(){mn(o)&&E.clearArtifacts()},getArtifacts(){return E?.getArtifacts()??[]},getSelectedArtifactId(){return E?.getSelectedArtifactId()??null},focusInput(){return ce&&!ve&&!Le()||!le?!1:(le.focus(),!0)},async resolveApproval(r,a,p){let y=E.getMessages().find(v=>v.variant==="approval"&&v.approval?.id===r);if(!y?.approval)throw new Error(`Approval not found: ${r}`);if(y.approval.toolType==="webmcp"){E.resolveWebMcpApproval(y.id,a);return}return E.resolveApproval(y.approval,a,p)},setFollowUpSuggestions(r){fw(r)},clearFollowUpSuggestions(){Of()},getMessages(){return E.getMessages()},getStatus(){return E.getStatus()},getPersistentMetadata(){return{...Z}},updatePersistentMetadata(r){re(r)},on(r,a){return w.on(r,a)},off(r,a){w.off(r,a)},isOpen(){return Fe()&&ve},isVoiceActive(){return ze.active},toggleReadAloud(r){E.toggleReadAloud(r)},stopReadAloud(){E.stopSpeaking()},getReadAloudState(r){return E.getReadAloudState(r)},onReadAloudChange(r){return E.onReadAloudChange(r)},getState(){return{open:Fe()&&ve,launcherEnabled:ce,voiceActive:ze.active,streaming:E.isStreaming()}},showCSATFeedback(r){!ve&&Fe()&&pt(!0,"system");let a=ke.querySelector(".persona-feedback-container");a&&a.remove();let p=xC({onSubmit:async(f,y)=>{E.isClientTokenMode()&&await E.submitCSATFeedback(f,y),r?.onSubmit?.(f,y)},onDismiss:r?.onDismiss,...r});ke.appendChild(p),p.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(r){!ve&&Fe()&&pt(!0,"system");let a=ke.querySelector(".persona-feedback-container");a&&a.remove();let p=AC({onSubmit:async(f,y)=>{E.isClientTokenMode()&&await E.submitNPSFeedback(f,y),r?.onSubmit?.(f,y)},onDismiss:r?.onDismiss,...r});ke.appendChild(p),p.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(r,a){return E.submitCSATFeedback(r,a)},async submitNPSFeedback(r,a){return E.submitNPSFeedback(r,a)},destroy(){up(),Jr!=null&&(clearInterval(Jr),Jr=null),fe.forEach(r=>r()),Ke.remove(),jt?.remove(),St?.destroy(),dn?.remove(),_r&&_e.removeEventListener("click",_r)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let r=window.AgentWidgetBrowser,a={controller:xt,getMessages:xt.getMessages,getStatus:xt.getStatus,getMetadata:xt.getPersistentMetadata,updateMetadata:xt.updatePersistentMetadata,clearHistory:()=>xt.clearChat(),setVoiceActive:p=>p?xt.startVoiceRecognition():xt.stopVoiceRecognition()};window.AgentWidgetBrowser=a,fe.push(()=>{window.AgentWidgetBrowser===a&&(window.AgentWidgetBrowser=r)})}if(typeof window<"u"){let r=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),a=q=>{let X=q.detail;(!X?.instanceId||X.instanceId===r)&&xt.focusInput()};if(window.addEventListener("persona:focusInput",a),fe.push(()=>{window.removeEventListener("persona:focusInput",a)}),C){let q=oe=>{let pe=oe.detail;(!pe?.instanceId||pe.instanceId===r)&&xt.showEventStream()},X=oe=>{let pe=oe.detail;(!pe?.instanceId||pe.instanceId===r)&&xt.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",X),fe.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",X)})}let p=q=>{let X=q.detail;(!X?.instanceId||X.instanceId===r)&&xt.showHistory()},f=q=>{let X=q.detail;(!X?.instanceId||X.instanceId===r)&&xt.hideHistory()};window.addEventListener("persona:showHistory",p),window.addEventListener("persona:hideHistory",f),fe.push(()=>{window.removeEventListener("persona:showHistory",p),window.removeEventListener("persona:hideHistory",f)});let y=q=>{let X=q.detail;(!X?.instanceId||X.instanceId===r)&&xt.showArtifacts()},v=q=>{let X=q.detail;(!X?.instanceId||X.instanceId===r)&&xt.hideArtifacts()},B=q=>{let X=q.detail;X?.instanceId&&X.instanceId!==r||X?.artifact&&xt.upsertArtifact(X.artifact)},$=q=>{let X=q.detail;X?.instanceId&&X.instanceId!==r||typeof X?.id=="string"&&xt.selectArtifact(X.id)},F=q=>{let X=q.detail;(!X?.instanceId||X.instanceId===r)&&xt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",B),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",F),fe.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",B),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",F)})}let Gn=AT(o.persistState);if(Gn&&Fe()){let r=MT(Gn.storage),a=`${Gn.keyPrefix}widget-open`,p=`${Gn.keyPrefix}widget-voice`,f=`${Gn.keyPrefix}widget-voice-mode`;if(r){let y=Gn.persist?.openState&&r.getItem(a)==="true",v=Gn.persist?.voiceState&&r.getItem(p)==="true",B=Gn.persist?.voiceState&&r.getItem(f)==="true";if(y&&(St?.setPanelOpen(!0,"auto"),setTimeout(()=>{xt.open(),setTimeout(()=>{if(v||B)xt.startVoiceRecognition();else if(Gn.persist?.focusInput){let $=t.querySelector("textarea");$&&$.focus()}},100)},0)),Gn.persist?.openState&&(w.on("widget:opened",()=>{r.setItem(a,"true")}),w.on("widget:closed",()=>{r.setItem(a,"false")})),Gn.persist?.voiceState&&(w.on("voice:state",$=>{r.setItem(p,$.active?"true":"false")}),w.on("user:message",$=>{r.setItem(f,$.viaVoice?"true":"false")})),Gn.clearOnChatClear){let $=()=>{r.removeItem(a),r.removeItem(p),r.removeItem(f)},F=()=>$();window.addEventListener("persona:clear-chat",F),fe.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}if(J&&Fe()&&(St?.setPanelOpen(!0,"auto"),setTimeout(()=>{xt.open()},0)),Ws(),!mw){let r=sc(()=>{E&&(qr++,Wt.clear(),qn(ke,E.getMessages(),vt))});fe.push(r)}T=()=>{E&&(qr++,Wt.clear(),qn(ke,E.getMessages(),vt))},E.getMessages().length>0&&wl(),A=()=>{E&&(qr++,Wt.clear(),qn(ke,E.getMessages(),vt))};let rx=Fh(()=>{E&&(qr++,Wt.clear(),qn(ke,E.getMessages(),vt))});fe.push(rx);let sx=yg(()=>{E&&(qr++,Wt.clear(),qn(ke,E.getMessages(),vt),er()?.updateInlineArtifactBlocks(ke,$n.artifacts,{suppressTransition:!0}),no())});return fe.push(sx),xt};var HC=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,e*parseFloat(s[1])/100):420},kT=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},PT=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},IT=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let s=o.offsetHeight>0;o.style.height="100%";let i=o.offsetHeight>0;o.remove(),!(!s||i)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.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 ${e.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.")},RC=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},Dg=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},WC=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Dg(t)},Rg=t=>{t.style.transition=""},Wg=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Bg=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},yd=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},LT=(t,e,n,o,s)=>{s?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},HT=(t,e,n,o,s,i)=>{let l=i?e:t;s==="left"?l.firstElementChild!==o&&l.replaceChildren(o,n):l.lastElementChild!==o&&l.replaceChildren(n,o)},RT=t=>{let e=di(t),n=e.components?.panel,o=(s,i)=>s==null||s===""?i:un(e,s)??s;return{inset:o(n?.inset,zc),canvasBackground:o(n?.canvasBackground,jc)}},BC=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},WT=(t,e,n,o,s,i,l,c)=>{let d=Yn(i),u=d.reveal==="push",g=c!=null,m=c?.inset??"",b=c?.canvasBackground??"";LT(t,e,n,o,u),HT(t,e,n,o,d.side,u),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=d.side,t.dataset.personaDockOpen=l?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.minWidth="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let h=t.ownerDocument.defaultView,x=i?.launcher?.mobileFullscreen??!0,T=i?.launcher?.mobileBreakpoint??640,M=h!=null?h.innerWidth<=T:!1;if(x&&M&&l){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Wg(e),Rg(o),WC(o),Bg(n),yd(s,o),BC(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(i?.launcher?.zIndex??an),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",u&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),WC(o),kT(o,d.maxHeight),BC(o,g&&l,m,b),d.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Wg(e),Rg(o),Bg(n),yd(s,o);let I=d.animate?"transform 180ms ease":"none",z=d.side==="right"?"translateX(100%)":"translateX(-100%)",A=l?"translateX(0)":z;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=I,o.style.transform=A,o.style.pointerEvents=l?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Rg(o),Dg(o),yd(s,o);let I=HC(d.width,t.clientWidth),z=Math.max(0,t.clientWidth),A=d.animate?"margin-left 180ms ease":"none",H=d.side==="right"?l?-I:0:l?0:-I;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${z+I}px`,e.style.transition=A,e.style.marginLeft=`${H}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${z}px`,n.style.maxWidth=`${z}px`,n.style.minWidth=`${z}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=l?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",Wg(e),Dg(o),Bg(n),yd(s,o);let I=d.reveal==="emerge";I?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let z=l?d.width:"0px",A=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${g?", padding 180ms ease":""}`:"none",H=!l;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${z}`,o.style.width=z,o.style.maxWidth=z,o.style.minWidth=z,o.style.minHeight="0",PT(o,d.maxHeight),o.style.overflow=I||H?"hidden":"visible",o.style.transition=A,I){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let w=g?`calc(${HC(d.width,t.clientWidth)}px - (2 * ${m}))`:d.width;s.style.width=w,s.style.minWidth=w,s.style.maxWidth=w,s.style.boxSizing="border-box"}}},BT=(t,e)=>{let n=t.ownerDocument.createElement("div");return RC(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){RC(n,o)},destroy(){n.remove()}}},DT=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let s=t.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let i=t.nextSibling,l=n.createElement("div"),c=n.createElement("div"),d=n.createElement("div"),u=n.createElement("aside"),g=n.createElement("div"),m=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;c.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",u.appendChild(g),o.insertBefore(l,t),d.appendChild(t);let b=null,h=()=>{b?.disconnect(),b=null},x=null,T=()=>{x=e?.launcher?.detachedPanel===!0?RT(e):null};T();let M=()=>{WT(l,c,d,u,g,e,m,x)},O=null,I=()=>{O?.(),O=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(O=Vc(()=>{T(),M()}))},z=()=>{h(),Yn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{M()}),b.observe(l)))},A=!1,H=()=>{M(),z(),m&&!A&&l.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,IT(l,Yn(e)))},w=l.ownerDocument.defaultView,D=()=>{H()};return w?.addEventListener("resize",D),Yn(e).reveal==="push"?(c.appendChild(d),c.appendChild(u),l.appendChild(c)):(l.appendChild(d),l.appendChild(u)),H(),I(),{mode:"docked",host:g,shell:l,syncWidgetState(K){let ie=K.launcherEnabled?K.open:!0;m!==ie&&(m=ie,H())},updateConfig(K){e=K,(e?.launcher?.enabled??!0)===!1&&(m=!0),T(),H(),I()},destroy(){w?.removeEventListener("resize",D),O?.(),O=null,h(),o.isConnected&&(i&&i.parentNode===o?o.insertBefore(t,i):o.appendChild(t)),l.remove()}}},DC=(t,e)=>Lt(e)?DT(t,e):BT(t,e);var za={desktop:{w:1280,h:800},mobile:{w:390,h:844}},OC=.15,_C=1.5,Og="persona-preview-shell-theme",OT={load:()=>null,save:()=>{},clear:()=>{}},_T=["How do I get started?","Pricing & plans","Talk to support"];function _g(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function NT(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function NC(t){let e=NT(t);return`* { box-sizing: border-box; }
|
|
128
|
+
`)}if(!f&&!r){let De="max-height: -moz-available !important; max-height: stretch !important;",Ce=a?"":"padding-top: 1.25em !important;",sn=a?"":`z-index: ${o.launcher?.zIndex??an} !important;`;Ke.style.cssText+=De+Ce+sn}Ed(),Et()},Fd=()=>{t.style.setProperty("--persona-content-max-width",kr(o,Le()))},wf=!1,Sf=()=>{let r=qu(o,Le());Le()&&o.composer?.placement&&o.debug===!0&&!wf&&(wf=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let a=Zo(o);t.setAttribute("data-persona-composer-placement",r),t.setAttribute("data-persona-conversation-state",Xa),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",a.composerGap??Kc),Ja()},xf=()=>{if(Le())return;let r=Lt(o),a=o.launcher?.sidebarMode??!1;if(r||a||(o.launcher?.fullHeight??!1)||!ce)return;let f=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640;if(y&&f.innerWidth<=b)return;let D=f.innerHeight,q=64,U=o.launcher?.heightOffset??0,z=Math.max(200,D-q),X=Math.min(640,z);we.style.height=`${Math.max(200,X-U)}px`};Nd(),Ia(t,o),Ua(t,o),$a(t,o),Fd(),Sf(),Wr=()=>{Nd(),xf(),Ia(t,o),Ua(t,o),$a(t,o),Fd(),Sf(),tl?t.style.setProperty("--persona-artifact-welded-outer-radius",tl):t.style.removeProperty("--persona-artifact-welded-outer-radius"),Lo(),vd()};let fe=[];fe.push(()=>{mf=!0}),fe.push(()=>{d.forEach(r=>r()),c.destroy()}),fe.push(()=>{document.removeEventListener("keydown",bf)}),fe.push(()=>{Ti!==null&&clearTimeout(Ti)});let yo=null,bo=null;fe.push(()=>{yo?.(),yo=null,bo?.(),bo=null}),Ii&&fe.push(()=>{Ii?.disconnect(),Ii=null}),fe.push(()=>{Ri?.(),Ri=null,_d(),mt&&(mt.remove(),mt=null),qe?.element.style.removeProperty("width"),qe?.element.style.removeProperty("maxWidth"),qe?.destroy()}),C&&fe.push(()=>{$e=!0,Ve=null,kt!==null&&(cancelAnimationFrame(kt),kt=null),gt?.destroy(),gt=null,Re?.destroy(),Re=null,Me=null});let Dr=null,Af=()=>{Dr&&(Dr(),Dr=null),o.colorScheme==="auto"&&(Dr=Vc(()=>{Ia(t,o)}))};Af(),fe.push(()=>{Dr&&(Dr(),Dr=null)}),fe.push(()=>{T=!0,h?.()}),fe.push(()=>{P=!0});let Mf=!1;fe.push(()=>{Mf=!0});let Ud=(r,a)=>{let p=ua(r,a);return p||!Jh.includes(r)?p:(hv().then(f=>{if(Mf)return;ou(f.wipe),ou(f.glyphCycle);let y=ua(r,a);y&&ma(y,t)}).catch(()=>{}),null)},cl=o.features?.streamAnimation;if(cl?.type&&cl.type!=="none"){let r=Ud(cl.type,cl.plugins);r&&ma(r,t),fe.push(()=>Zh(t))}let Bo=Da(or),Ef=Da(wd),Tf=Da(xi),Or=[Bo,Ef,Tf];fe.push(()=>{Or.forEach(r=>r.destroy())});let _r=null,A,Nr=null,kf=!1,Pf=0,If=null,Lf=r=>r.reduce((a,p)=>p.role==="user"?a+1:a,0),Hf=r=>{for(let a=r.length-1;a>=0;a--)if(va(r[a]))return r[a].id??null;return null},Rf=!1,gw=()=>{Rf||o.debug!==!0||(Rf=!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".'))},Wf=!1,Bf=!1,Df=(r,a)=>{Wf||o.debug!==!0||!a.enabled||a.expose||kf||Bf&&(A.isStreaming()||r.some(va)||(Wf=!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.")))},Ts=r=>{if(!A)return;let a=r??A.getMessages(),p=z=>{z.render([],A,le,a)},f=z=>{Or.forEach(X=>{X!==z&&p(X)})};Nr&&(Lf(a)>Pf||Hf(a)!==If)&&(Nr=null);let y=Er(o);Df(a,y);let b=y.enabled?Ly(a):null,D=Nr??b,q=Nr?"host":"agent";if(D){let z=o.suggestions?.followUps,X=z?.placement??(z?"auto":"composer"),pe=(X==="auto"?Le()?"composer":"after-message":X)==="after-message"?Tf:Bo;f(pe),pe.render(D,A,le,a,o.suggestionChipsConfig,{source:q,surface:"followUp",variant:z?.variant??"chip",behavior:z?.behavior??"send",overflow:z?.overflow??"wrap",maxItems:z?.maxItems??4,config:o,plugins:l,submitPrompt:Xl});return}if(a.some(z=>z.role==="user")){Or.forEach(p);return}let U=o.suggestions?.starters;if(U){let z=fi(Zo(o),a),X=U.placement??"auto",oe=X==="auto"?z?"welcome":"composer":X;if(oe==="welcome"&&!z){gw(),Or.forEach(p);return}let pe=oe==="welcome"?Ef:Bo;f(pe),pe.render(U.items??o.suggestionChips,A,le,a,o.suggestionChipsConfig,{surface:"starter",variant:U.variant??"card",behavior:U.behavior??"send",overflow:U.overflow??"wrap",maxItems:U.maxItems??4,config:o,plugins:l,submitPrompt:Xl});return}f(Bo),Bo.render(o.suggestionChips,A,le,a,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:l,submitPrompt:Xl})},Of=()=>{Nr&&(Nr=null,Ts())},fw=r=>{let a=Array.isArray(r)?[...r]:[];if(!a.length){Of();return}let p=A?A.getMessages():[];Nr=a,kf=!0,Pf=Lf(p),If=Hf(p),Ts(p)},Rn=!1,Wt=uv(),ks=new Map,Fr=new Map,cr=new Map,Ur=null,dr=null;function $r(){if(!Ur)return;let r=Ur;Ur=null,dr?.destroy(),dr=null,Wt.delete(r),de.querySelector(`#wrapper-${r}`)?.removeAttribute("data-preserve-runtime"),A&&qn(ke,A.getMessages(),vt)}let qr=0,mw=Ys()!==null,Wn=Kh(),Bn=0,pr=null,Cn=!1,dl=!1,ur=0,Ft=null,zr=null,$d=!1,Ps=!1,jr=null,Wi=!0,pl=!1,Is=null,ul=!1,Vr=()=>{ul=!0,vw()},qd=null,hw=4,Do=24,yw=80,bw=1e3,Oo=null,_f=()=>{t.setAttribute("data-persona-scrollbar",xd()),xd()!=="on-scroll"&&(Oo!==null&&clearTimeout(Oo),Oo=null,te.removeAttribute("data-persona-scrollbar-visible"))},vw=()=>{xd()==="on-scroll"&&(te.setAttribute("data-persona-scrollbar-visible",""),Oo!==null&&clearTimeout(Oo),Oo=setTimeout(()=>{Oo=null,cs(te,Do)&&te.removeAttribute("data-persona-scrollbar-visible")},bw))};_f(),fe.push(()=>{Oo!==null&&clearTimeout(Oo)});let zd=new Map,ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};lf=()=>ze.active,to();let Nf=o.voiceRecognition?.autoResume??!1,_o=r=>{w.emit("voice:state",{active:ze.active,source:r,timestamp:Date.now()})},ro=()=>{re(r=>({...r,voiceState:{active:ze.active,timestamp:Date.now(),manuallyDeactivated:ze.manuallyDeactivated}}))},Cw=()=>{if(o.voiceRecognition?.enabled===!1)return;let r=Hg(Z.voiceState),a=!!r.active,p=Number(r.timestamp??0);ze.manuallyDeactivated=!!r.manuallyDeactivated,a&&Date.now()-p<CT&&setTimeout(()=>{ze.active||(ze.manuallyDeactivated=!1,Tn(o.voiceRecognition?.provider)?A.toggleVoice().then(()=>{ze.active=A.isVoiceActive(),_o("restore"),A.isVoiceActive()&&Gs()}):Zl("restore"))},1e3)},ww=()=>A?kC(A.getMessages()).filter(r=>!r.__skipPersist):[],gl=null,Ff=(r,a)=>{typeof console<"u"&&console.error(r,a)},fl=(r,a)=>{let p=()=>{try{let D=r();return!D||typeof D.then!="function"?null:Promise.resolve(D).catch(q=>{Ff(a,q)})}catch(D){return Ff(a,D),null}},f=gl,y=f?f.then(()=>p()??void 0):p();if(!y)return;let b=y.finally(()=>{gl===b&&(gl=null)});gl=b};function Ls(r){if(!K?.save)return;let a=r?kC(r):A?ww():[],p=ie&&A?.getResumableHandle();p&&(Z={...Z,durableResume:{executionId:p.executionId,after:p.lastEventId}});let f={messages:a,metadata:Z,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId,...Kr?{draft:Kr}:{}};fl(()=>K.save(f),"[AgentWidget] Failed to persist state:")}let Kr,ml=()=>!K?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Bi=qb({write:()=>{if(!ml())return;let r=be.getState(),a=Ub({text:r.text,mentionRefs:r.mentionRefs,contentSegments:Fp(),selectedModelId:r.selectedModelId,activeModeIds:r.activeModeIds,quote:r.quote});JSON.stringify(a)!==JSON.stringify(Kr)&&(Kr=a,Ls())}});function Uf(){ml()&&Bi.schedule()}function jd(){Bi.flush()}function $f(r){if(!ml())return;let a=$b(r,{mentionSourceIds:(o.contextMentions?.sources??[]).map(p=>p.id),modelIds:(o.composer?.models??[]).map(p=>p.id),modes:o.composer?.modes??[]});a&&(Kr=r,le&&!le.value&&(le.value=a.text,le.dispatchEvent(new Event("input",{bubbles:!0})),go()),a.selectedModelId&&(be.setSelectedModelId(a.selectedModelId),ir?.repaint()),Za(a.activeModeIds??[]),a.quote&&fo(a.quote),Bi.cancel())}function hl(){Bi.cancel(),Kr&&(Kr=void 0,ml()&&Ls())}let Hs=null,qf=()=>Ke.querySelector("#persona-scroll-container")||te,Rs=()=>{Hs!==null&&(cancelAnimationFrame(Hs),Hs=null),Cn=!1},zf=()=>{pr!==null&&(cancelAnimationFrame(pr),pr=null),dl=!1,Rs()},Sw=()=>Rn&&Kd()&&(Hn()!=="anchor-top"||zg()),Vd=()=>{let r=Ai()||"Jump to latest",a=Sw();Rt.toggleAttribute("data-persona-scroll-to-bottom-streaming",a),ur>0?(Lr.textContent=String(ur),Lr.style.display="",Rt.setAttribute("aria-label",`${r} (${ur} new)`)):(Lr.textContent="",Lr.style.display="none",Rt.setAttribute("aria-label",a?`${r} (response streaming below)`:r))},jf=()=>{ur!==0&&(ur=0,Vd())},xw=()=>{let r=Ft?.spacerHeight??0;return r<=0?cs(te,Do):Cl(r)-te.scrollTop-te.clientHeight<=Do},Kd=()=>sr()?!Wn.isFollowing():!xw(),Gd=()=>!!A&&A.getMessages().length>0,Ut=()=>{if(!YC()||qC()){Rt.parentNode&&Rt.remove(),Rt.style.display="none";return}Rt.parentNode!==de&&de.appendChild(Rt),Hr();let a=Qo(te)>0&&Kd()&&Gd();a?Vd():jf(),Rt.style.display=a?"":"none"},Di=()=>{Wn.pause()&&(zf(),Ut())},wn=()=>{Wn.resume(),jf(),Ut()},gr=(r=!1)=>{sr()&&Gd()&&Wn.isFollowing()&&(!r&&!Rn||(pr!==null&&(cancelAnimationFrame(pr),pr=null),dl=!0,pr=requestAnimationFrame(()=>{pr=null,dl=!1,Wn.isFollowing()&&Aw(qf(),r?220:140)})))},Vf=(r,a,p,f=()=>!0)=>{let y=r.scrollTop,b=a(),D=b-y;if(Rs(),Math.abs(D)<1){Cn=!0,r.scrollTop=b,Bn=r.scrollTop,Cn=!1;return}let q=performance.now();Cn=!0;let U=X=>1-Math.pow(1-X,3),z=X=>{if(!f()){Rs();return}let oe=a();oe!==b&&(b=oe,D=b-y);let pe=X-q,Xe=Math.min(pe/p,1),ct=U(Xe),ut=y+D*ct;r.scrollTop=ut,Bn=r.scrollTop,Xe<1?Hs=requestAnimationFrame(z):(r.scrollTop=b,Bn=r.scrollTop,Hs=null,Cn=!1)};Hs=requestAnimationFrame(z)},Aw=(r,a=500)=>{let p=Qo(r)-r.scrollTop;if(Math.abs(p)<1){Bn=r.scrollTop;return}if(Math.abs(p)>=yw){Rs(),Cn=!0,r.scrollTop=Qo(r),Bn=r.scrollTop,Cn=!1;return}Vf(r,()=>Qo(r),a,()=>Wn.isFollowing())},yl=()=>{if(!Gd()){Ut();return}let r=qf();Cn=!0,r.scrollTop=Qo(r),Bn=r.scrollTop,Cn=!1,Ut()},Gr=r=>{let a=0,p=r;for(;p&&p!==te;)a+=p.offsetTop,p=p.offsetParent;return a},Mw=()=>{let r=te.getRootNode();return(typeof r.getSelection=="function"?r.getSelection():null)??te.ownerDocument.getSelection()},bl=()=>Xh(Mw(),te),Qd=()=>{if(JC()!=="last-user-turn")return!1;let r=A?.getMessages()??[];if(r.length<2)return!1;let a=[...r].reverse().find(b=>b.role==="user");if(!a)return!1;let p=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a.id):a.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=te.querySelector(`[data-message-id="${p}"]`);if(!f)return!1;let y=Math.min(Math.max(0,Gr(f)-Mi()),Qo(te));return Cn=!0,te.scrollTop=y,Bn=te.scrollTop,Cn=!1,Hn()==="follow"&&!cs(te,Do)&&Wn.pause(),Ut(),!0},vl=r=>{let a=Math.max(0,Math.round(r));Un.style.height=`${a}px`,Un.style.display=a>0?"":"none",Ft&&(Ft.spacerHeight=Math.max(0,r))},Cl=r=>{let a=parseFloat(getComputedStyle(te).paddingBottom)||0,p=0;for(let y of Array.from(te.children)){if(y===Un||y.offsetHeight===0)continue;let b=Gr(y)+y.offsetHeight;b>p&&(p=b)}let f=te.scrollHeight-r;return p>0?Math.min(p+a,f):f},Ew=()=>{if(!Ft||Ft.spacerHeight<=0)return;let r=Cl(Ft.spacerHeight),a=Math.max(0,Math.round(te.scrollTop)+te.clientHeight-r+Do);a<Ft.spacerHeight&&(vl(a),Ut())},so=()=>{zr!==null&&(cancelAnimationFrame(zr),zr=null),Rs(),Ft=null,Un.style.height="0px",Un.style.display="none"},Kf=r=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Xd=r=>te.querySelector(`[data-message-id="${Kf(r)}"]`),Gf=r=>{zr!==null&&cancelAnimationFrame(zr),zr=requestAnimationFrame(()=>{zr=null;let a=Kf(r),p=te.querySelector(`[data-message-id="${a}"]`);if(!p)return;let f=Gr(p),y=Ft?.spacerHeight??0,b=Cl(y),{targetScrollTop:D,spacerHeight:q}=nu({anchorOffsetTop:f,topOffset:Mi(),viewportHeight:te.clientHeight,contentHeight:b,slack:Do});Ft={initialSpacerHeight:q,contentHeightAtAnchor:b,spacerHeight:q},vl(q),Vf(te,()=>p.isConnected?Math.max(0,Gr(p)-Mi()):D,220)})},Sn=()=>{if(Hn()!=="anchor-top"||!Ft||!Is)return;let r=Xd(Is);if(!r)return;Rs();let a=Ft.spacerHeight,p=Cl(a),{targetScrollTop:f,spacerHeight:y}=nu({anchorOffsetTop:Gr(r),topOffset:Mi(),viewportHeight:te.clientHeight,contentHeight:p,slack:Do});Ft={initialSpacerHeight:y,contentHeightAtAnchor:p,spacerHeight:y},vl(y),Cn=!0,te.scrollTop=f,Bn=te.scrollTop,Cn=!1,Ut()},Tw=()=>{if(sr()){if(!Wn.isFollowing()||cs(te,1))return;gr(!Rn);return}if(Ft&&Ft.initialSpacerHeight>0){let r=te.scrollHeight-Ft.spacerHeight,a=Yh({initialSpacerHeight:Ft.initialSpacerHeight,contentHeightAtAnchor:Ft.contentHeightAtAnchor,currentContentHeight:r});a!==Ft.spacerHeight&&vl(a)}Ut()},kw=r=>{let a=Hn();a==="follow"?(wn(),gr(!0)):a==="anchor-top"&&(Wi=!1,pl=!0,ul=!1,Is=r,Gf(r))},Pw=()=>{if(Hn()==="anchor-top"){if(pl){Wi=!1;return}Wi=!0,so(),wn(),gr(!0)}},Iw=96,Lw=r=>{if(jr===null)return!0;let a=Xd(jr),p=Xd(r);if(!a||!p)return!0;let f=Gr(p)-Gr(a);return Mi()+f>te.clientHeight-Iw},Hw=r=>{if(Hn()!=="anchor-top"||!pl||ul||bl())return;let a=jr===null;for(let p of r){if(!a){p.id===jr&&(a=!0);continue}if(Vh(p)){if(p.id===Is||!Lw(p.id))return;Is=p.id,Gf(p.id);return}}},Rw=r=>{let a=new Map;r.forEach(p=>{let f=zd.get(p.id);a.set(p.id,{streaming:p.streaming,role:p.role}),!f&&p.role==="assistant"&&(w.emit("assistant:message",p),!Ps&&(Hn()!=="anchor-top"||zg())&&Kd()&&(ur+=1,Vd(),Ut(),Qa(ur===1?"1 new message below.":`${ur} new messages below.`))),p.role==="assistant"&&f?.streaming&&p.streaming===!1&&w.emit("assistant:complete",p),p.variant==="approval"&&p.approval&&(f?p.approval.status!=="pending"&&w.emit("approval:resolved",{approval:p.approval,decision:p.approval.status}):w.emit("approval:requested",{approval:p.approval,message:p}))}),zd.clear(),a.forEach((p,f)=>{zd.set(f,p)})},Oi=(r,a)=>{let p=a==="user"?"user":"assistant",f=o.layout?.messages?.[p],y=f?.width??"content",b=f?.maxWidth??(y==="full"?"100%":void 0);r.classList.add("persona-message-row"),r.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),r.classList.add(`persona-message-row-${a}`,`persona-message-width-${y}`),r.classList.toggle("persona-justify-end",a==="user"),r.setAttribute("data-message-role",a),r.setAttribute("data-message-width",y),b?r.style.setProperty("--persona-message-row-max-width",b):r.style.removeProperty("--persona-message-row-max-width")},No=(r,a)=>{let p=document.createElement("div");return p.className="persona-flex",p.id=`wrapper-${r}`,p.setAttribute("data-wrapper-id",r),Oi(p,a),p},Ww=(r,a,p)=>{let f=document.createElement("div"),b=(()=>{let L=l.find(Ne=>Ne.renderLoadingIndicator);if(L?.renderLoadingIndicator)return L.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),D=(L,Ne)=>Ne==null?!1:typeof Ne=="string"?(L.textContent=Ne,!0):(L.appendChild(Ne),!0),q=new Set,U=new Map,z=new Set,X=l.some(L=>L.renderAskUserQuestion),oe=[],pe=[],Xe=o.enableComponentStreaming!==!1,ct=o.approval!==!1,ut=[],Vt=o.messageActions,Dt=Vt?.showRegenerate===!0&&Vt.enabled!==!1&<.current?.isStreaming()!==!0?Zy(a):null,At=Vt?.showEdit===!0&&Vt.enabled!==!1,nn=Vt?.showQuote===!0&&Vt.enabled!==!1,Je=null,on=o.features?.reasoningDisplay?.completedVisibility,xo=L=>on==="removed"?!0:on==="removed-when-short"?Lh(L,o.features?.reasoningDisplay?.shortThinkThreshold):!1,Ko=o.features?.toolCallDisplay?.completedVisibility==="removed",io=L=>L.variant==="reasoning"&&L.reasoning?.status==="complete"?xo(L.reasoning):Ko&&L.variant==="tool"&&L.toolCall?.status==="complete";if(a.forEach(L=>{if(io(L))return;if(q.add(L.id),U.set(L.id,L.role),Ur===L.id&&dr){let Ce=No(L.id,L.role);Ce.setAttribute("data-persona-message-edit-stub","true"),Ce.setAttribute("data-preserve-runtime","true"),f.appendChild(Ce),Je={messageId:L.id,element:dr.element};return}let Ne=X&&ds(L),Se=ct&&L.variant==="approval"&&!!L.approval,se=!Ne&&L.role==="assistant"&&!L.variant&&Xe&&Lg(L);!Se&&cr.has(L.id)&&(r.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),cr.delete(L.id)),!se&&Fr.has(L.id)&&(r.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),Fr.delete(L.id));let Mt=ds(L)?`:${L.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${L.agentMetadata?.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot={canRegenerate:Dt===L.id,canEdit:At&&yu(L),canQuote:nn&&!L.variant&&(L.content?.trim().length??0)>0},Jt=`${Ot.canRegenerate?"r":""}${Ot.canEdit?"e":""}${Ot.canQuote?"q":""}`,_t=pv(L,qr)+Mt+`:${Jt}`,$t=Ne||Se||se?null:gv(Wt,L.id,_t);if($t){f.appendChild($t.cloneNode(!0)),ds(L)&&L.toolCall?.id&&L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(z.add(L.toolCall.id),Cc(L,o,Be.composerOverlay));return}let Et=null,rn=l.find(Ce=>!!(L.variant==="reasoning"&&Ce.renderReasoning||L.variant==="tool"&&Ce.renderToolCall||!L.variant&&Ce.renderMessage)),He=o.layout?.messages;if(ds(L)&&L.agentMetadata?.askUserQuestionAnswered===!0){ks.delete(L.id),r.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime");return}if(va(L)&&Er(o).enabled)return;if(ds(L)&&o.features?.askUserQuestion?.enabled!==!1){let Ce=l.find(sn=>typeof sn.renderAskUserQuestion=="function");if(Ce&<.current){let sn=ks.get(L.id),Cr=sn!==_t,An=null;if(Cr){let{payload:dt,complete:We}=oi(L),Go=L.id,It=()=>lt.current?.getMessages().find(En=>En.id===Go);An=Ce.renderAskUserQuestion({message:L,payload:dt,complete:We,resolve:En=>{let la=It();la&<.current?.resolveAskUserQuestion(la,En)},dismiss:()=>{let En=It();En?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(En),lt.current?.resolveAskUserQuestion(En,"(dismissed)"))},config:o})}let Mn=sn!=null;if(Cr&&An===null&&!Mn){L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(z.add(L.toolCall.id),Cc(L,o,Be.composerOverlay));return}let it=No(L.id,L.role);it.setAttribute("data-ask-plugin-stub","true"),it.setAttribute("data-preserve-runtime","true"),f.appendChild(it),oe.push({messageId:L.id,fingerprint:_t,bubble:An});return}else{L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(z.add(L.toolCall.id),Cc(L,o,Be.composerOverlay));return}}else if(Se){let Ce=I();if(!Ce){f.appendChild(No(L.id,L.role));return}let sn=l.find(it=>typeof it.renderApproval=="function")??v,An=cr.get(L.id)!==_t,Mn=null;if(An&&sn?.renderApproval){let it=L.id,dt=(We,Go)=>{let It=lt.current?.getMessages().find(En=>En.id===it);It?.approval&&(It.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(It.id,We):lt.current?.resolveApproval(It.approval,We,Go))};Mn=sn.renderApproval({message:L,defaultRenderer:()=>Ce.createApprovalBubble(L,o),config:o,approve:We=>dt("approved",We),deny:We=>dt("denied",We)})}if(An&&Mn===null)r.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),cr.delete(L.id),Et=Ce.createApprovalBubble(L,o);else{let it=No(L.id,L.role);it.setAttribute("data-approval-plugin-stub","true"),it.setAttribute("data-preserve-runtime","true"),f.appendChild(it),ut.push({messageId:L.id,fingerprint:_t,bubble:Mn});return}}else if(rn)if(L.variant==="reasoning"&&L.reasoning&&rn.renderReasoning){if(!Io)return;Et=rn.renderReasoning({message:L,defaultRenderer:()=>ug(L,o),config:o})}else if(L.variant==="tool"&&L.toolCall&&rn.renderToolCall){if(!j)return;Et=rn.renderToolCall({message:L,defaultRenderer:()=>fg(L,o),config:o})}else rn.renderMessage&&(Et=rn.renderMessage({message:L,defaultRenderer:()=>{let Ce=tg(L,p,He,o.messageActions,ys,{loadingIndicatorRenderer:b,widgetConfig:o,actionEligibility:Ot});return L.role!=="user"&&R(Ce,L,o,A),Ce},config:o}));if(!Et&&se){let Ce=SC(L);if(Ce){let sn=Fr.get(L.id),Cr=sn!==_t,An=o.wrapComponentDirectiveInBubble!==!1&&Xo.getOptions(Ce.component)?.bubbleChrome!==!1,Mn=null;if(Cr){let it=CC(Ce,{config:o,message:L,transform:p});if(it&&Ce.component==="PersonaArtifactInline"){let dt=it.hasAttribute("data-artifact-inline")?it:it.querySelector("[data-artifact-inline]"),We=dt?.getAttribute("data-artifact-inline")??"",Go=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(We):We,It=We?r.querySelector(`#wrapper-${L.id}`)?.querySelector(`[data-artifact-inline="${Go}"]`)??null:null;dt&&It&&It!==dt&&er()?.hasLiveInlineArtifactBlock(It)&&(dt===it?it=It:dt.replaceWith(It))}if(it)if(An){let dt=document.createElement("div");if(dt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),dt.id=`bubble-${L.id}`,dt.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let We=document.createElement("div");We.className="persona-mb-3 persona-text-sm persona-leading-relaxed",We.innerHTML=p({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),dt.appendChild(We)}dt.appendChild(it),Mn=dt}else{let dt=document.createElement("div");if(dt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",dt.id=`bubble-${L.id}`,dt.setAttribute("data-message-id",L.id),dt.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let We=document.createElement("div");We.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",We.innerHTML=p({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),dt.appendChild(We)}dt.appendChild(it),Mn=dt}}if(Mn||sn!=null){let it=No(L.id,L.role);it.setAttribute("data-component-directive-stub","true"),it.setAttribute("data-preserve-runtime","true"),f.appendChild(it),pe.push({messageId:L.id,fingerprint:_t,bubble:Mn});return}}}if(!Et)if(L.variant==="reasoning"&&L.reasoning){if(!Io)return;Et=ug(L,o)}else if(L.variant==="tool"&&L.toolCall){if(!j)return;Et=fg(L,o)}else if(L.variant==="approval"&&L.approval){if(o.approval===!1)return;let Ce=I();if(!Ce)return;Et=Ce.createApprovalBubble(L,o)}else{let Ce=o.layout?.messages;Ce?.renderUserMessage&&L.role==="user"?Et=Ce.renderUserMessage({message:L,config:o,streaming:!!L.streaming}):Ce?.renderAssistantMessage&&L.role==="assistant"?Et=Ce.renderAssistantMessage({message:L,config:o,streaming:!!L.streaming}):Et=tg(L,p,Ce,o.messageActions,ys,{loadingIndicatorRenderer:b,widgetConfig:o,actionEligibility:Ot}),L.role!=="user"&&Et&&R(Et,L,o,A)}let De=No(L.id,L.role);De.appendChild(Et),fv(Wt,L.id,_t,De),f.appendChild(De)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Se=Ne.getAttribute("data-persona-ask-sheet-for");Se&&!z.has(Se)&&si(Be.composerOverlay,Se)}),o.features?.toolCallDisplay?.grouped){let L=[],Ne=[],Se=o.features.toolCallDisplay.groupedMode==="summary";a.forEach(se=>{if(se.variant==="tool"&&se.toolCall&&j){if(Ko&&se.toolCall.status==="complete")return;Ne.push(se);return}se.variant==="reasoning"&&(!Io||se.reasoning?.status==="complete"&&xo(se.reasoning))||((Ne.length>1||Se&&Ne.length>0)&&L.push(Ne),Ne=[])}),(Ne.length>1||Se&&Ne.length>0)&&L.push(Ne),L.forEach(se=>{let Mt=se.map(He=>Array.from(f.children).find(De=>De instanceof HTMLElement&&De.getAttribute("data-wrapper-id")===He.id)).filter(He=>!!He);if(Mt.length<(Se?1:2))return;let Ot=No(`tool-group-${se[0].id}`,"assistant");Ot.setAttribute("data-persona-tool-group-row","true");let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let _t=document.createElement("div");_t.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",_t.id=`tool-group-summary-${se[0].id}`;let $t=`Called ${se.length} ${se.length===1?"tool":"tools"}`,Et=o.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(He=>He.toolCall).filter(He=>!!He),defaultSummary:$t,config:o});D(_t,Et)||(_t.textContent=$t);let rn=document.createElement("div");rn.className="persona-tool-group-stack persona-flex persona-flex-col",rn.id=`tool-group-stack-${se[0].id}`,rn.setAttribute("data-persona-tool-group-stack","true"),Jt.appendChild(_t),Se||Jt.appendChild(rn),Ot.appendChild(Jt),Mt[0].before(Ot),Mt.forEach((He,De)=>{if(Se){He.remove();return}He.style.setProperty("--persona-message-row-max-width","100%");let Ce=document.createElement("div");Ce.className="persona-tool-group-item persona-relative",Ce.setAttribute("data-persona-tool-group-item","true"),De<Mt.length-1&&Ce.setAttribute("data-persona-tool-group-connector","true"),Ce.appendChild(He),rn.appendChild(Ce)})})}mv(Wt,q);let aa=L=>L.variant==="tool"&&!j||L.variant==="reasoning"&&!Io||io(L),as=a.some(L=>L.role==="assistant"&&L.streaming&&!aa(L)),ao=a.length-1;for(;ao>=0&&aa(a[ao]);)ao--;let Yt=ao>=0?a[ao]:void 0,lo=ao<a.length-1,Xs=Yt?.role==="assistant"&&!Yt.streaming&&Yt.variant!=="approval"&&!lo;if(Rn&&a.some(L=>L.role==="user")&&!as&&!Xs){let L={config:o,streaming:!0,location:"standalone",defaultRenderer:Na},Ne=l.find(se=>se.renderLoadingIndicator),Se=null;if(Ne?.renderLoadingIndicator&&(Se=Ne.renderLoadingIndicator(L)),Se===null&&o.loadingIndicator?.render&&(Se=o.loadingIndicator.render(L)),Se===null&&(Se=Na()),Se){let se=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1,Ot=o.layout?.messages?.layout??"bubble";se.className=Mt?Fa("assistant",Ot).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),se.setAttribute("data-typing-indicator","true"),Mt&&(se.style.color="var(--persona-message-assistant-text, var(--persona-text))",Ot!=="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 Jt=No("typing-indicator","assistant");Jt.appendChild(se),f.appendChild(Jt)}}if(!Rn&&a.length>0){let L=a[a.length-1],Ne={config:o,lastMessage:L,messageCount:a.length},Se=l.find(Mt=>Mt.renderIdleIndicator),se=null;if(Se?.renderIdleIndicator&&(se=Se.renderIdleIndicator(Ne)),se===null&&o.loadingIndicator?.renderIdle&&(se=o.loadingIndicator.renderIdle(Ne)),se){let Mt=document.createElement("div"),Ot=o.loadingIndicator?.showBubble!==!1;Mt.className=Ot?["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(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild(se);let Jt=No("idle-indicator","assistant");Jt.appendChild(Mt),f.appendChild(Jt)}}if(uy(f),Yc(r,f),su(r),Je){let{messageId:L,element:Ne}=Je,Se=r.querySelector(`#wrapper-${L}`);Se&&Ne.parentElement!==Se&&(Oi(Se,U.get(L)??"user"),Se.replaceChildren(Ne))}if(oe.length>0)for(let{messageId:L,fingerprint:Ne,bubble:Se}of oe){let se=r.querySelector(`#wrapper-${L}`);se&&(Oi(se,U.get(L)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Ne),ks.set(L,Ne)))}if(ks.size>0)for(let L of ks.keys())q.has(L)||ks.delete(L);if(pe.length>0)for(let{messageId:L,fingerprint:Ne,bubble:Se}of pe){let se=r.querySelector(`#wrapper-${L}`);se&&(Oi(se,U.get(L)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Ne),Fr.set(L,Ne)))}if(Fr.size>0)for(let L of Fr.keys())q.has(L)||Fr.delete(L);if(ut.length>0)for(let{messageId:L,fingerprint:Ne,bubble:Se}of ut){let se=r.querySelector(`#wrapper-${L}`);se&&(Oi(se,U.get(L)??"assistant"),Se!==null&&(se.replaceChildren(Se),se.setAttribute("data-bubble-fp",Ne),cr.set(L,Ne)))}if(cr.size>0)for(let L of cr.keys())q.has(L)||cr.delete(L)},Yd=!1,wl=()=>{Yd||(Yd=!0,Ah().catch(()=>{Yd=!1}))},qn=(r,a,p)=>{a.length>0&&wl(),Ww(r,a,p),ff()},_i=null,Bw=()=>{if(_i)return;let r=p=>{let f=p.composedPath();f.includes(Ke)||jt&&f.includes(jt)||pt(!1,"user")};_i=r,(t.ownerDocument??document).addEventListener("pointerdown",r,!0)},Qf=()=>{if(!_i)return;(t.ownerDocument??document).removeEventListener("pointerdown",_i,!0),_i=null};fe.push(()=>Qf());let Ni=null,Dw=()=>{if(Ni)return;let r=p=>{p.key==="Escape"&&(p.isComposing||pt(!1,"user"))};Ni=r,(t.ownerDocument??document).addEventListener("keydown",r,!0)},Xf=()=>{if(!Ni)return;(t.ownerDocument??document).removeEventListener("keydown",Ni,!0),Ni=null};fe.push(()=>Xf());let Fi=!1,Yf=new Set,Ow=()=>{let r=o.launcher?.composerBar?.peek?.streamAnimation;return r||o.features?.streamAnimation},Ws=()=>{if(!Le())return;let r=Be.peekBanner,a=Be.peekTextNode;if(!r||!a)return;if(ve){r.classList.remove("persona-pill-peek--visible");return}let p=A?.getMessages()??[],f;for(let Dt=p.length-1;Dt>=0;Dt--){let At=p[Dt];if(At.role==="assistant"&&At.content){f=At;break}}if(!f){r.classList.remove("persona-pill-peek--visible");return}let y=f.content,b=!!f.streaming,D=Ow(),q=mc(D),U=q.type!=="none"?Ud(q.type,D?.plugins):null,z=U?.isAnimating?.(f)===!0,X=U!==null&&(b||z);X&&U&&!Yf.has(U.name)&&(ma(U,t),Yf.add(U.name));let oe=X&&U?.containerClass?U.containerClass:null,pe=a.dataset.personaPeekStreamClass??null;pe&&pe!==oe&&(a.classList.remove(pe),delete a.dataset.personaPeekStreamClass),oe&&pe!==oe&&(a.classList.add(oe),a.dataset.personaPeekStreamClass=oe),X?(a.style.setProperty("--persona-stream-step",`${q.speed}ms`),a.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(a.style.removeProperty("--persona-stream-step"),a.style.removeProperty("--persona-stream-duration"));let Xe=X?hc(y,q.buffer,U,f,b):y;if(X&&q.placeholder==="skeleton"&&b&&(!Xe||!Xe.trim())){let Dt=document.createElement("div"),At=fa();At.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(At),Yc(a,Dt)}else{let Dt=Math.max(0,Xe.length-100),At=Xe.length>100?Xe.slice(-100):Xe,nn=ic(At);if(!X||!U){let Je=Xe.length>100?`\u2026${At}`:At;a.textContent!==Je&&(a.textContent=Je)}else{let Je=nn;(U.wrap==="char"||U.wrap==="word")&&(Je=ga(nn,U.wrap,`peek-${f.id}`,{skipTags:U.skipTags,startIndex:Dt}));let on=document.createElement("div");if(on.innerHTML=Je,U.useCaret&&At.length>0){let xo=yc(),Ko=on.querySelectorAll(".persona-stream-char, .persona-stream-word"),io=Ko[Ko.length-1];io?.parentNode?io.parentNode.insertBefore(xo,io.nextSibling):on.appendChild(xo)}Yc(a,on),U.onAfterRender?.({container:a,bubble:r,messageId:f.id,message:f,speed:q.speed,duration:q.duration})}}let Vt=Rn||Fi;r.classList.toggle("persona-pill-peek--visible",Vt)};if(Le()){let r=Be.peekBanner;if(r){let f=y=>{y.preventDefault(),y.stopPropagation(),pt(!0,"user")};r.addEventListener("pointerdown",f),fe.push(()=>{r.removeEventListener("pointerdown",f)})}let a=()=>{Fi||(Fi=!0,Ws())},p=()=>{Fi&&(Fi=!1,Ws())};we.addEventListener("pointerenter",a),we.addEventListener("pointerleave",p),fe.push(()=>{we.removeEventListener("pointerenter",a),we.removeEventListener("pointerleave",p)}),jt&&(jt.addEventListener("pointerenter",a),jt.addEventListener("pointerleave",p),fe.push(()=>{jt.removeEventListener("pointerenter",a),jt.removeEventListener("pointerleave",p)}))}let _w=r=>{let a=o.launcher?.composerBar??{},p=a.expandedSize??"anchored",f=a.bottomOffset??"16px",y=a.collapsedMaxWidth,b=a.expandedMaxWidth??"880px",D=a.expandedTopOffset??"5vh",q=a.modalMaxWidth??"880px",U=a.modalMaxHeight??"min(90vh, 800px)",z="calc(100vw - 32px)",X="var(--persona-pill-area-height, 80px)",oe=Ke.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",jt){let pe=jt.style;pe.bottom=f,pe.width=y??""}if(r&&p!=="fullscreen"){if(p==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=q,oe.maxWidth=z,oe.maxHeight=U,oe.height=U;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${f} + ${X})`,oe.top=D,oe.width=b,oe.maxWidth=z}},Ui=()=>{if(ve&&wl(),!Fe())return;if(Le()){let z=(o.launcher?.composerBar??{}).expandedSize??"anchored",X=ve?"expanded":"collapsed";Ke.dataset.state=X,Ke.dataset.expandedSize=z,jt&&(jt.dataset.state=X,jt.dataset.expandedSize=z),Ke.style.removeProperty("display"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),_w(ve),de.style.display=ve?"flex":"none",Wr(),ve?(Bw(),Dw()):(Qf(),Xf()),Ws();return}let r=Lt(o),a=t.ownerDocument.defaultView??window,p=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,y=a.innerWidth<=p,b=f&&y&&ce,D=Jn(o).reveal;ve?(Ke.style.removeProperty("display"),Ke.style.display=r?"flex":"",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0"),we.classList.add("persona-scale-100","persona-opacity-100"),St?(St.setPanelOpen(!0),St.element.style.display="none"):dn&&(dn.style.display="none")):(r?r&&(D==="overlay"||D==="push")&&!b?(Ke.style.removeProperty("display"),Ke.style.display="flex",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ke.style.setProperty("display","none","important"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ke.style.display="",Ke.classList.add("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100"),we.classList.add("persona-scale-95","persona-opacity-0")),St?(St.setPanelOpen(!1),St.element.style.display=r?"none":""):dn&&(dn.style.display=r?"none":""))},pt=(r,a="user")=>{if(!Fe()||ve===r)return;let p=ve;ve=r,Ui();let f=(()=>{let b=o.launcher?.sidebarMode??!1,D=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,U=o.launcher?.mobileBreakpoint??640,z=D.innerWidth<=U,X=Lt(o)&&q&&z,oe=Le()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return b||q&&z&&ce||X||oe})();if(ve&&f){if(!yo){let b=t.getRootNode(),D=b instanceof ShadowRoot?b.host:t.closest(".persona-host");D&&(yo=Vu(D,o.launcher?.zIndex??an))}bo||(bo=Ku(t.ownerDocument))}else ve||(yo?.(),yo=null,bo?.(),bo=null);ve&&(ra(),Qd()||(Hn()==="follow"?gr(!0):yl()));let y={open:ve,source:a,timestamp:Date.now()};ve&&!p?w.emit("widget:opened",y):!ve&&p&&w.emit("widget:closed",y),w.emit("widget:state",{open:ve,launcherEnabled:ce,voiceActive:ze.active,streaming:A.isStreaming()})},fr={inputDisabled:!1,sendDisabled:!1},vo=()=>fr.inputDisabled,Jd=()=>Tn(o.voiceRecognition?.provider)&&!!A&&(A.isBargeInActive()||["listening","processing","speaking"].includes(A.getVoiceStatus())),Qr=()=>fr.inputDisabled||fr.sendDisabled,Nw=()=>(fr.inputDisabled?fr.inputReason:void 0)??(fr.sendDisabled?fr.sendReason:void 0);function Zd(){if(!xe)return;if(be.getState().phase==="streaming"){xe.disabled=!1;return}let r=Ye?!Ye.isReady():!1;xe.disabled=Qr()||r}function Sl(){if(!uo)return;let r=be.getState(),a=o.sendButton?.visibility==="when-text"&&r.phase!=="streaming"&&r.text.trim().length===0&&r.attachments.length===0;uo.toggleAttribute("data-persona-send-hidden",a)}function Fw(){let r=Nw();if(Le()){let a=eo??Ie;r?a.setAttribute("title",r):a.removeAttribute("title"),Ie.toggleAttribute(wi,!!r);return}if(r){rt.setAttribute("role","status"),rt.setAttribute("aria-live","polite"),rt.setAttribute(wi,""),rt.textContent=r;return}if(rt.hasAttribute(wi)&&(rt.removeAttribute("role"),rt.removeAttribute("aria-live"),rt.removeAttribute(wi),u)){let a=A.getStatus();Va(rt,Ug(a),o.statusIndicator??{},a)}}function ep(){let r=Iu(o.composer?.inputDisabled),a=Iu(o.composer?.sendDisabled);fr={inputDisabled:r.disabled,inputReason:r.reason,sendDisabled:a.disabled,sendReason:a.reason},be.setInputDisabled(r.disabled),be.setSendDisabled(a.disabled);let p=be.getState().phase==="streaming",f=r.disabled,y=p||f;le&&(le instanceof HTMLTextAreaElement?le.disabled=f:le.setAttribute("contenteditable",f?"false":"true"),le.setAttribute("aria-disabled",f?"true":"false")),bt&&(bt.disabled=f),ft&&(ft.disabled=f);for(let b of Pt?.affordanceButtons??[])b.querySelectorAll("button").forEach(D=>{D.disabled=f});ne&&(ne.disabled=f||p&&!Jd()),Or.forEach(b=>{b.elements.forEach(D=>{D.toggleAttribute("data-disabled",y),D instanceof HTMLButtonElement||D.setAttribute("aria-disabled",y?"true":"false")}),b.buttons.forEach(D=>{D.disabled=y})}),sp.forEach(b=>{b.toggleAttribute("data-disabled",y),b instanceof HTMLButtonElement?b.disabled=y:b.setAttribute("aria-disabled",y?"true":"false"),b.querySelectorAll("button").forEach(D=>{D.disabled=y})}),Ie.dataset.personaComposerStreaming=p?"true":"false",Ie.dataset.personaComposerInputDisabled=f?"true":"false",Ie.dataset.personaComposerSendDisabled=Qr()?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(b=>{(b instanceof HTMLButtonElement||b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement||b instanceof HTMLSelectElement)&&(b.disabled=p)}),Zd(),Fw()}let $i=r=>{be.setStreaming(r),$g(r?"stop":"send"),ep()},Xr=()=>{ze.active||le&&le.focus()};w.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Xr(),200)});let Yr=null,qi=!1,tp=!yn.hidden,mr=null,np=!S,xl=null;fe.push(()=>{xl?.cancel(),xl=null});let Uw=r=>{let a=Wv(r);if(a===Xa)return;Xa=a,t.setAttribute("data-persona-conversation-state",a);let p=Md();Ja(),np&&(xl?.cancel(),xl=Hv(Ie,a==="active"?p:Md(),a==="active"?"drop":"rise")),Sn()},Jf=null,Zf,em=null,Bs=null,op=!1,zi=r=>{let a=Zo(o),p=`${a.variant}|${a.dismiss}|${a.anchor??"bottom"}|${a.align??""}|${a.iconPlacement}|${a.kicker??""}|${a.title}|${a.subtitle}`;(p!==Jf||a.icon!==Zf)&&(Jf=p,Zf=a.icon,od({host:yn,iconHolder:zC,kicker:jC,title:VC,subtitle:KC,starterSuggestions:wd},a));let f=a.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${a.message}`;f!==em&&(em=f,rd(In,a.message,o));let y=r??(A?A.getMessages():o.initialMessages);Uw(y);let b=qi,D=!b&&fi(a,y),q=D!==tp;if(tp=D,Bs){mr?.cancel(),mr=null,b!==op&&(op=b,b?rg(te,yn,null):og(te,yn,Bs)),gi(te,yn,!b);return}if(q&&!D&&!b&&a.dismiss==="on-first-message"&&np){mr=Lv(yn,z=>{mr===z&&(mr=null),!tp&&!Bs&&(gi(te,yn,!1),Sn()),z?.cancel()});return}if(mr){if(!D&&!b)return;mr.cancel(),mr=null}let U=!yn.hidden;gi(te,yn,D),!D&&U&&Sn()},rp=[],sp=[],ip=!1,tm=null,nm,om=()=>{sp.length=0;let r=rp.splice(0,rp.length);for(let a of r)try{a()}catch(p){console.warn("[persona] renderWelcome cleanup threw",p)}};fe.push(om);let $w=(r,a)=>{let p=Qu(r,a);if(!p)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),k("span");let f=o.suggestions?.starters,y=Xu({item:{...p,behavior:p.behavior??f?.behavior??"send"},index:a,surface:"starter",source:"config",variant:f?.variant??"card",streaming:u?A.isStreaming():!1,config:o,plugins:l,chipsConfig:o.suggestionChipsConfig,session:A,getTextarea:()=>le,eventTarget:yn,submitPrompt:Xl});return sp.push(y),y},ap=()=>{if(ip)return;ip=!0;let r=Zo(o);tm=`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`,nm=r.icon;try{om(),rg(te,yn,Bs),Bs=null,op=!1;let a=A?A.getMessages():o.initialMessages,p=fi(r,a),f=0,y=null;for(let b of l)if(b.renderWelcome&&(y=b.renderWelcome({config:r,variant:r.variant,visible:p,defaultRenderer:()=>yn,sendMessage:D=>{if(!A||A.isStreaming())return;let q=D.trim();q&&A.sendMessage(q)},requestRender:()=>ap(),renderStarter:D=>$w(D,f++),storage:g(b.id),onCleanup:D=>{rp.push(D)}}),y))break;y&&y!==yn&&(Bs=y,og(te,yn,y))}finally{ip=!1}zi()},qw=()=>{let r=Zo(o);`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`===tm&&r.icon===nm||ap()},Al=()=>{zi(),xs||(le.placeholder=Db(be.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!A?.isStreaming()&&(xe.textContent=o.copy?.sendButtonLabel??"Send")),le.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',le.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},zw=!!o.setStoredConversationId,Ds=r=>re(a=>{let p={...a};return delete p[r],p}),Ml=r=>{let a=Z[r];return typeof a=="string"?a:null},rm=()=>{let r=Z.durableResume;if(!r||typeof r!="object")return null;let a=r;return typeof a.executionId=="string"&&a.executionId.length>0&&typeof a.after=="string"&&a.after.length>0?{executionId:a.executionId,after:a.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Ml("sessionId"),setStoredSessionId:r=>{re(a=>({...a,sessionId:r}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Ds("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ml("conversationId")),setStoredConversationId:o.setStoredConversationId??(r=>{re(a=>({...a,conversationId:r}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Ds("conversationId"))});let sm=()=>o.clientToken??null,im=r=>fC(r,Q(),o.persistState===!1),am=sm(),zn=am?im(am):null,Fo={...zn?{visitorStore:zn}:{},historyBootstrapReady:W,getStoredMessageCursor:()=>Ml("historyMessageCursor"),setStoredMessageCursor:r=>{if(r===null){Ds("historyMessageCursor");return}re(a=>({...a,historyMessageCursor:r}))},getPendingDisplayProjections:()=>{let r=Z.pendingDisplayProjections;if(!r||typeof r!="object")return null;let a=r;return typeof a.conversationId!="string"||!Array.isArray(a.messageIds)?null:{conversationId:a.conversationId,messageIds:a.messageIds.filter(p=>typeof p=="string")}},setPendingDisplayProjections:r=>{if(!r){Ds("pendingDisplayProjections");return}re(a=>({...a,pendingDisplayProjections:r}))},getStoredResumableHandle:rm,setStoredResumableHandle:r=>{if(!r){Ds("durableResume");return}re(a=>({...a,durableResume:r}))},shouldResumeDurableConversation:()=>ie&&rm()!==null,...zw?{}:{getStoredConversationRevision:()=>Ml("conversationRevision"),setStoredConversationRevision:r=>{if(r===null){Ds("conversationRevision");return}re(a=>({...a,conversationRevision:r}))}}};if(ie){let r=o.onExecutionState,a=t.ownerDocument.defaultView,p=!1,f=()=>p=!0,y=()=>p=!1;a?.addEventListener("pagehide",f),a?.addEventListener("pageshow",y),fe.push(()=>{a?.removeEventListener("pagehide",f),a?.removeEventListener("pageshow",y)}),o={...o,reconnectStream:o.reconnectStream??(b=>A.getClient().reconnectClientTokenStream(b)),onExecutionState:b=>{(b||!p)&&Fo.setStoredResumableHandle?.(b?{executionId:b.executionId,after:b.lastEventId}:null),r?.(b)}}}let jw=()=>{let r=sm();if(r&&zn?.matches(r,Q(),o.persistState===!1)||!r&&!zn)return;zn?.destroy(),zn=r?im(r):null;let a={...Fo};zn?a.visitorStore=zn:delete a.visitorStore,Fo=a,A.setHistoryInternals(Fo)},Jr=null,Vw=()=>{Jr==null&&(Jr=setInterval(()=>{let r=ke.querySelectorAll("[data-tool-elapsed]");if(r.length===0){clearInterval(Jr),Jr=null;return}let a=Date.now();r.forEach(p=>{let f=Number(p.getAttribute("data-tool-elapsed"));f&&(p.textContent=Rh(a-f))})},100))},lp=(r,a)=>{if(Object.is(r,a))return!0;if(r===null||a===null||typeof r!="object"||typeof a!="object")return!1;if(Array.isArray(r)||Array.isArray(a))return!Array.isArray(r)||!Array.isArray(a)||r.length!==a.length?!1:r.every((D,q)=>lp(D,a[q]));let p=r,f=a,y=Object.keys(p),b=Object.keys(f);return y.length===b.length&&y.every(D=>Object.prototype.hasOwnProperty.call(f,D)&&lp(p[D],f[D]))},lm=r=>{let{content:a,rawContent:p,llmContent:f,...y}=r;return y},cp=r=>r.role==="assistant"&&r.streaming===!0&&!r.variant&&!r.toolCall&&!r.tools&&!r.approval&&!r.reasoning&&!r.contentParts&&!r.stopReason&&!Lg(r),Kw=(r,a,p)=>{if(r.length!==a.length)return!1;let f=r[p.index],y=a[p.index];return!f||!y||f.id!==p.id||y.id!==p.id?!1:(!Object.is(f.content,y.content)||!Object.is(f.rawContent,y.rawContent)||!Object.is(f.llmContent,y.llmContent))&&cp(f)&&cp(y)&&lp(lm(f),lm(y))},dp=null,Os=null,Zr=null,Uo=null,pp=null,Gw=r=>{if(!ie)return Ls(r);pp=r,queueMicrotask(()=>{pp===r&&(pp=null,Ls(r))})},El=r=>{dp=r;let a,p;Os=null;for(let y=r.length-1;y>=0;y-=1){let b=r[y];if(!a&&b.role==="user"&&(a=b),!p&&b.role==="assistant"&&(p=b),!Os&&cp(b)&&(Os={index:y,id:b.id}),a&&p&&Os)break}qn(ke,r,vt),er()?.updateInlineArtifactBlocks(ke,$n.artifacts,{suppressTransition:Rn}),Vw(),zi(r),Ts(r),gr(!Rn),Rw(r),r.length===0&&(so(),Wi=!0,pl=!1,Is=null,ul=!1),!$d||Ps?($d=!0,jr=a?.id??null,qd=p?.id??null):a&&a.id!==jr?(jr=a.id,kw(a.id)):p&&p.id!==qd&&Pw(),p&&(qd=p.id),Hw(r);let f=ze.lastUserMessageId;a&&a.id!==f&&(ze.lastUserMessageId=a.id,w.emit("user:message",a)),ze.lastUserMessageWasVoice=!!a?.viaVoice,Gw(r),Ws()},up=()=>{Uo!==null&&(cancelAnimationFrame(Uo),Uo=null);let r=Zr;Zr=null,r&&El(r)},cm=()=>{Uo!==null&&cancelAnimationFrame(Uo),Uo=null,Zr=null},Qw=r=>{let a=Zr??dp;if(Rn&&a&&Os&&Kw(a,r,Os)){Zr=r,Uo===null&&(Uo=requestAnimationFrame(()=>{Uo=null;let p=Zr;Zr=null,p&&El(p)}));return}if(r.length===0){cm(),El(r);return}up(),El(r)};A=new kc(o,{onMessagesChanged(r){Qw(r)},onStatusChanged(r){let a=o.statusIndicator??{};Va(rt,(f=>f==="idle"?a.idleText??Nt.idle:f==="connecting"?a.connectingText??Nt.connecting:f==="connected"?a.connectedText??Nt.connected:f==="error"?a.errorText??Nt.error:f==="paused"?a.pausedText??Nt.paused:f==="resuming"?a.resumingText??Nt.resuming:Nt[f])(r),a,r),Cd()},onStreamingChanged(r){r||(A?.getMessages().length===0?cm():up()),Rn=r,$i(r),Cd(),A&&qn(ke,A.getMessages(),vt),r||(gr(!0),Ew(),Bf=!0,A&&Df(A.getMessages(),Er(o))),Ut(),Qa(r?"Responding\u2026":"Response complete."),Ws()},onVoiceStatusChanged(r){if(w.emit("voice:status",{status:r,timestamp:Date.now()}),!(r!=="disconnected"&&!Tn(o.voiceRecognition?.provider)))switch(r){case"listening":Vo(),Gs();break;case"processing":Vo(),YS();break;case"speaking":Vo(),JS();break;default:r==="idle"&&A.isBargeInActive()?(Vo(),Gs(),ne?.setAttribute("aria-label","End voice session")):(ze.active=!1,Vo(),_o("system"),ro());break}},onArtifactsState(r){$n=r,r.artifacts.length===0&&(As=!1),er()?.updateInlineArtifactBlocks(ke,r.artifacts,{suppressTransition:Rn}),oo(),Ls()},onHistoryStateChanged(r){Ng(r)},onHistoryNotice(r){Fg(r)},onReconnect(r){let{executionId:a,lastEventId:p}=r.handle;r.phase==="paused"?w.emit("stream:paused",{executionId:a,after:p}):r.phase==="resuming"?w.emit("stream:resuming",{executionId:a,after:p,attempt:r.attempt??1}):w.emit("stream:resumed",{executionId:a,after:p})}},Fo),lt.current=A,fe.push(()=>A.cancel()),fe.push(()=>{A.destroy(),zn?.destroy(),zn=null});let gp=null;if(A.onReadAloudChange((r,a)=>{uf=r,gf=a,ff();let p=r??gp;r&&(gp=r);let f=p?A.getMessages().find(y=>y.id===p)??null:null;w.emit("message:read-aloud",{messageId:p,message:f,state:a,timestamp:Date.now()}),a==="idle"&&(gp=null)}),u=!0,$d=!0,o.voiceRecognition?.enabled===!0&&Tn(o.voiceRecognition.provider))try{A.setupVoice()}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",r)}let Xw=720,Yw=250,Qe=ru(o.features?.history?.copy),Dn=null,fp=!1,st=null,Tl=null,kl="conversation",mp=null,cn=null,Co=null,Pl=A.getHistoryState(),hp=null,ji=0,yp=null,Il=null,Ll=null,bp=`persona-history-${Math.random().toString(36).slice(2,8)}`,vp=()=>o.features?.history?.enabled===!0,wo=()=>vp()&&!!Dn&&!fp,dm=()=>{let r=A.getStatus();return Rn||r==="paused"||r==="resuming"},Cp=()=>{let r=o.features?.history?.scope;if(r)return r;let a=o.getIdentityProof?"verified-user":"browser",p=Dn?.capabilities.scopes;return!p||p.includes(a)?a:p[0]??a},_s=()=>Tl?.scope??Cp(),pm=()=>A.getClientSession()?.targetId??null,um=r=>`${r.state}:${"reason"in r?r.reason:""}`,Jw=r=>{let a=um(r);a!==hp&&(hp=a,w.emit("history:identityStatusChanged",{status:r,timestamp:Date.now()}))},Hl=r=>{r&&(Ho.textContent="",Ho.textContent=r)},gm=null,fm=null,Zw=()=>{if(!vp())return null;let r=bC();if(r)return r();let a=o.features?.history?.provider;return a?typeof a!="function"?a:(gm!==a&&(gm=a,fm=a()),fm):A.isClientTokenMode()?vC({client:A.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:p=>A.bindActivatedSession(p),getClient:()=>A.getClient()}):null},mm=()=>{Il?.(),Il=null,Ll?.(),Ll=null,fp=!1,Dn=Zw();let r={...Fo};Dn?r.historyProvider=Dn:delete r.historyProvider,Fo=r,A.setHistoryInternals(Fo),Dn&&(Il=Dn.subscribeAvailability?.(a=>{fp=!a,a||xn({restoreFocus:!1}),yr()})??null,Ll=Dn.subscribeIdentityStatus(a=>Jw(a)),hp=um(Dn.getIdentityStatus()))},wp=()=>{let r=o.features?.history?.presentation??"panel";if(r==="panel"||r==="auto"&&!(!ce||Lt(o)))return"panel";let a=ho??de;return(a.getBoundingClientRect().width||a.clientWidth)>=Xw?"rail":"panel"},jn=(r,a)=>{a?(r.setAttribute("aria-hidden","true"),r.setAttribute("inert","")):(r.removeAttribute("aria-hidden"),r.removeAttribute("inert"))},Rl="data-persona-history-suppressed",On=null,hr=null,es=null,Vi=null,Sp=null,hm="",ym=()=>Ae===Sp?hm:o.layout?.showHeader===!1?"none":"",eS=()=>Ht==="panel"&&!!es&&Vi===es.element&&o.layout?.showHeader!==!1&&ym()!=="none",tS=()=>{for(let r of Array.from(Ae.children))r!==On&&r.setAttribute(Rl,"")},nS=()=>{for(let r of Array.from(de.querySelectorAll(`[${Rl}]`)))r.removeAttribute(Rl)},oS=()=>{let r=es;if(!r)return;if(Array.from(Ae.children).some(f=>f!==On&&!f.hasAttribute(Rl))){hr&&hr!==Ae&&(hr.style.removeProperty("min-height"),hr=null);let f=Ae.offsetHeight;f>0&&(Ae.style.minHeight=`${f}px`,hr=Ae)}On||(On=k("div","persona-history-header-host")),r.setHeaderPlacement("external");let p=r.getHeaderElement();p.parentNode!==On&&On.replaceChildren(p),On.parentNode!==Ae&&Ae.appendChild(On),tS()},bm=()=>{hr&&(hr.style.removeProperty("min-height"),hr=null),On&&(es?.setHeaderPlacement("inline"),On.remove(),On=null,nS())},Wl=null,xp=()=>{if(Wl){if(te.style.display="none",jn(te,!0),Ie.hidden=!0,jn(Ie,!0),eS()){oS(),Ae.style.display=ym(),jn(Ae,!1);return}bm(),Ae.style.display="none",jn(Ae,!0)}};vd=xp;let rS=r=>{let a=te.style.display,p=Ie.hidden,f=Ie,y=Ae,b=Ae.style.display;Sp=y,hm=b,Wl=()=>{Wl=null,bm(),Sp=null,te.style.display=a,jn(te,!1),f.hidden=p,jn(f,!1),Ie!==f&&(Ie.hidden=!1,jn(Ie,!1)),y.style.display=b,jn(y,!1),Ae!==y&&(Ae.style.display=o.layout?.showHeader===!1?"none":"",jn(Ae,!1))},Ie.parentNode?.insertBefore(r,Ie),xp()},Ns=null,ts=null,Ki=null,Fs=null,vm=()=>[Ae,Be.closeButtonWrapper,Be.clearChatButtonWrapper,te,Ie],sS=52,Bl=()=>o.features?.history?.rail?.collapsible!==!1,Us=()=>o.features?.history?.rail?.side==="right"?"right":"left",Ap=200,Mp=400,Ep=r=>Math.min(Mp,Math.max(Ap,Math.round(r))),iS=()=>o.features?.history?.rail?.resizable===!0,Gi,aS=()=>{if(Gi===void 0&&(Gi=null,o.persistState!==!1))try{let r=Number(window.localStorage.getItem(`${Q()}rail-width`));r&&(Gi=r)}catch{}return Gi},Qi=()=>Ep(aS()??o.features?.history?.rail?.width??260),lS=r=>{if(Gi=r,o.persistState!==!1)try{window.localStorage.setItem(`${Q()}rail-width`,String(r))}catch{}},Dl=()=>Bl()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Bt=!1,Cm=r=>{let a=k("img");return a.src=r,a.alt="",a.setAttribute("aria-hidden","true"),a},cS=()=>{let r=o.features?.history?.rail?.brand;if(!r)return;let a=!1,p;return f=>{if(r.render)try{return r.render({collapsed:f})??null}catch(y){return a||(a=!0,console.warn("[persona] history rail brand threw",y)),null}return p===void 0&&(r.iconUrl?p=Cm(r.iconUrl):p=r.icon?ge(r.icon,20):null),p?p.cloneNode(!0):null}},dS=()=>o.features?.history?.rail?.sections?.map(r=>{let a=!1,p=f=>{a||(a=!0,console.warn("[persona] history rail section threw",r.id,f))};return{id:r.id,title:r.title,placement:r.placement??"above-conversations",items:r.items.map(f=>{let y;return{id:f.id,label:f.label,badge:f.badge,iconNode:()=>{if(y!==void 0)return y;try{f.renderIcon?y=f.renderIcon()??null:f.iconUrl?y=Cm(f.iconUrl):y=f.icon?ge(f.icon,20):null}catch(b){p(b),y=null}return y},onSelect:()=>{try{f.onSelect()}catch(b){p(b)}}}})}})??[],pS=r=>{let a=dS();for(let p of r)a.some(f=>f.id===p.id)?console.warn("[persona] duplicate history rail section id",p.id):a.push(p);return a.length?a:void 0},Xi=null,wm=()=>`${Q()}rail-collapsed`,Tp=()=>{if(Xi===null&&(Xi=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let r=window.localStorage.getItem(wm());r&&(Xi=r==="1")}catch{}return Xi},kp=r=>{if(Xi=r,o.persistState!==!1)try{window.localStorage.setItem(wm(),r?"1":"0")}catch{}},Yi=()=>Ht==="rail"&&Bl()&&!Dl()&&Tp(),Pp=()=>{},Sm=()=>{if(Dl()){Pp();return}kp(!Tp()),st?.view.setCollapsed(Yi()),Lo(),Sn()},Ip=()=>{let r=o.features?.history?.rail?.collapseShortcut;return!r||!Qc(r)?null:{combo:r,hint:Xc(r),aria:Ha(r)}},xm=()=>{d.forEach(a=>a()),d=[];let r=Ip();r&&d.push(c.register({id:"history-rail-collapse",combo:r.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Ct&&Ht==="rail"&&Bl()||qs(),run:()=>Dl()?Pp():Sm()}));for(let a of o.layout?.header?.trailingActions??[])a.shortcut&&d.push(c.register({id:`header-action-${a.id}`,combo:a.shortcut,run:()=>{let p=t.querySelector(`[data-persona-header-action="${a.id}"]`);p?p.click():o.layout?.header?.onAction?.(a.id)}}));for(let a of l)for(let p of a.shortcuts??[])d.push(c.register({...p,id:`${a.id}:${p.id}`}))};xm();let uS=300,Ol="var(--persona-history-overlay-margin,8px)",Vn=null,$o=null,_l=0,qo=null,$s=null,ns=!1,Lp=0,Am=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,qs=()=>wo()&&Dl()&&(Ht??wp())==="rail",gS=()=>Ct&&!Bt,Ji=()=>{$s!==null&&clearTimeout($s),$s=null},fS=()=>{kg().catch(()=>{})},Mm=()=>{Ji(),Bt&&($s=setTimeout(()=>{$s=null,!(ns||!Bt)&&(qo?.contains(document.activeElement)||xn({restoreFocus:!1}))},uS))},mS=(r,a)=>{let p=qo?.getBoundingClientRect();if(!p)return!1;let f=Vn?.getBoundingClientRect(),y=f?Math.min(f.top,p.top):p.top;return r>=p.left&&r<=p.right&&a>=y&&a<=p.bottom||!!f&&r>=f.left&&r<=f.right&&a>=f.top&&a<=f.bottom},Hp=r=>{Bt&&(ns=mS(r.clientX,r.clientY),ns?Ji():$s===null&&Mm())},Em=r=>{Ct||!qs()||(Bt=!0,ea({invoker:Vn,keyboard:r?.keyboard===!0}).then(()=>{Ct?!ns&&document.activeElement!==Vn&&xn():Bt=!1}))},Tm=()=>{let r=Vi?.querySelector('[data-persona-history-focus="collapse"]');r&&(r.setAttribute("aria-label",Bt?Qe.expandLabel:Qe.collapseLabel),r.setAttribute("aria-expanded",Bt?"false":"true"))},km=()=>{kp(!1);let r=st;if(!Bt||!r){ea({invoker:Vn});return}let a=document.activeElement===Vn;Bt=!1,Nl(),r.element.remove(),Wp(r.element),Tm(),a&&Ul(),Sn(),yr()},hS=()=>{kp(!0),xn()};Pp=()=>{!Ct||Bt?km():hS()};let yS=()=>{let r=Ip(),a=gs({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":bp,...r?{"aria-keyshortcuts":r.aria}:{}}}),p=a.button;p.addEventListener("mouseenter",()=>{ns=!0,Ji(),!(Am()||Date.now()<Lp)&&Em()}),p.addEventListener("mouseleave",()=>{ns=!1,Lp=0,Mm()}),p.addEventListener("focus",()=>{Ct||fS()}),p.addEventListener("click",f=>{wo()&&(f.detail!==0&&Am()&&!Ct?Em():km())}),Vn=p,$o=a.wrapper},Zi=()=>{if($o&&!$o.isConnected&&($o=null,Vn=null),!qs()){$o?.remove(),$o=null,Vn=null;return}Vn||yS();let r=$o,a=Vn;if(!r||!a)return;let p=Us()!=="right"?Ae.firstChild:null;(p??Ae.lastChild)!==r&&Ae.insertBefore(r,p),r.style.display=gS()||_l>0?"none":"",a.setAttribute("aria-label",Qe.expandLabel),a.setAttribute("aria-expanded",Ct?"true":"false"),qo&&Lo()},Pm=r=>{if(!Bt)return;let a=r.target;a instanceof Node&&(qo?.contains(a)||$o?.contains(a)||a instanceof Element&&a.closest('.persona-dropdown-menu,[role="alertdialog"]')||xn({restoreFocus:!1}))};document.addEventListener("pointerdown",Pm,!0),fe.push(()=>{document.removeEventListener("pointerdown",Pm,!0),document.removeEventListener("pointermove",Hp),zs?.(),Ji()});let Rp=null,zs=null,Im=16,Lm=r=>{lS(Ep(r)),Lo(),Sn()},bS=()=>{let r=k("div","persona-rail-resizer");return r.tabIndex=0,r.setAttribute("role","separator"),r.setAttribute("aria-orientation","vertical"),r.setAttribute("aria-valuemin",String(Ap)),r.setAttribute("aria-valuemax",String(Mp)),r.addEventListener("pointerdown",a=>{let p=ts;if(!p||a.button!==0)return;a.preventDefault(),zs?.();let f=a.clientX,y=p.getBoundingClientRect().width||Qi(),b=Us()==="right"?-1:1,D=y,q=t.ownerDocument;p.style.transition="none";let U=X=>{D=Ep(y+b*(X.clientX-f)),p.style.flex=`0 0 ${D}px`,r.setAttribute("aria-valuenow",String(D))},z=()=>{zs=null,q.removeEventListener("pointermove",U),q.removeEventListener("pointerup",z),q.removeEventListener("pointercancel",z),p.style.removeProperty("transition");try{r.releasePointerCapture(a.pointerId)}catch{}Lm(D)};zs=z,q.addEventListener("pointermove",U),q.addEventListener("pointerup",z),q.addEventListener("pointercancel",z);try{r.setPointerCapture(a.pointerId)}catch{}}),r.addEventListener("keydown",a=>{let p=Us()==="right"?-Im:Im,f=Qi(),y=a.key==="ArrowRight"?f+p:a.key==="ArrowLeft"?f-p:a.key==="Home"?Ap:a.key==="End"?Mp:null;y!==null&&(a.preventDefault(),Lm(y))}),r},vS=(r,a)=>{if(!iS()||Yi()){zs?.(),Rp?.remove();return}let p=Rp??bS();Rp=p,p.setAttribute("aria-label",Qe.resizeLabel),p.setAttribute("aria-valuenow",String(Qi())),p.nextElementSibling!==a&&r.insertBefore(p,a)};Lo=()=>{st?.view.setRailSide(Us());let r=Us()==="right",a=qo;if(a){let q=Vn?Vn.getBoundingClientRect().bottom-de.getBoundingClientRect().top:0;a.style.top=`calc(${Math.max(0,Math.round(q))}px + ${Ol})`,a.style.width=`${Qi()}px`,a.style.left=r?"":Ol,a.style.right=r?Ol:""}let p=ts,f=Ns,y=Ki;if(!p||!f||!y)return;p.style.flex=`0 0 ${Yi()?sS:Qi()}px`;let b="1px solid var(--persona-divider,#e5e7eb)";p.style.borderRight=r?"":b,p.style.borderLeft=r?b:"";let D=r?y:p;f.firstElementChild!==D&&f.append(D,r?p:y),vS(f,r?p:y)};let Hm=r=>{if(Fs&&ts){Fs.replaceWith(r),Fs=null,Lo();return}let a=k("div","persona-history-rail-shell");a.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let p=k("div","persona-history-rail-conversation");p.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let f=k("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",de.insertBefore(a,Ae.parentNode===de?Ae:te);for(let y of vm())y?.parentNode===de&&p.appendChild(y);a.append(f,p),f.appendChild(r),Ns=a,ts=f,Ki=p,Lo()},CS=()=>{if(Ns)return;let r=k("div","persona-history-rail-placeholder");r.style.cssText="flex:1 1 auto;min-height:0",Fs=r,Hm(r),Sn()},Rm=()=>{Fs&&(Nl(),Sn())},wS=r=>{let a=k("div","persona-history-rail-overlay");a.style.cssText=`position:absolute;bottom:${Ol};display:flex;overflow:hidden;z-index:${uc-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(a),a.appendChild(r),document.addEventListener("pointermove",Hp),qo=a,Lo(),Tm()},Nl=()=>{Wl?.(),qo&&(ns&&(Lp=Date.now()+150),document.removeEventListener("pointermove",Hp),qo.remove(),qo=null);let r=Ns;if(r){zs?.();for(let a of vm())a&&r.contains(a)&&de.insertBefore(a,r);r.remove(),Ns=null,ts=null,Ki=null,Fs=null}},Wm=r=>{Vi=r,r.id=bp,r.style.flex="1 1 auto",r.style.minHeight="0"},Wp=r=>{Wm(r),(Ht!=="rail"||Bt)&&Rm(),Ht!=="rail"?rS(r):Bt?wS(r):Hm(r)},Fl=()=>{if(Zi(),jm(),!Ct||!st)return;let r=wp();if(r===Ht)return;let a=document.activeElement,p=a instanceof HTMLElement&&(st.element.contains(a)||On?.contains(a)===!0)?a:null;Nl(),st.element.remove(),st.view.setHeaderPlacement("inline"),Ht=r,st.view.setPresentation(r),st.view.setCollapsed(Yi()),st.requestRender(),st.element.isConnected||Wp(st.element),p?.isConnected?p.focus():Ul(),Ut(),Sn(),yr()},Bm=(r,a)=>On?.querySelector(a)??r.querySelector(a),Ul=()=>{let r=st?.element??Vi;if(!r)return;let a=Bm(r,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(a){a.focus();return}let p=Bm(r,".persona-history-title")??r;p.tabIndex=-1,p.focus()},ea=async r=>{if(!wo()||Ct)return;let a=Dn;if(!a)return;if(!Bt&&qs()&&Tp()){Zi();return}$l();let p=++ji;kl=r?.returnSurface??"conversation",mp=r?.invoker??cn;let f=qs()&&!Bt;f&&(_l+=1,Zi(),CS());let y;try{y=await kg()}catch{Hl(Qe.openHistoryLabel),f&&(_l-=1,p===ji&&(Rm(),Zi()));return}if(f&&(_l-=1),p!==ji||Ct)return;Tl={scope:Cp()},Ht=wp(),Ct=!0;let b=Ht==="panel"&&o.layout?.showHeader!==!1&&Ae.style.display!=="none"?"external":"inline",D=o.features?.history?.rowAvatar,q=Ip(),U=q?{hint:q.hint,aria:q.aria}:null,z={provider:a,context:Tl,targetId:pm(),presentation:Ht,collapsible:Bl(),collapsed:Yi(),railSide:Us(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:cS(),onToggleCollapse:Sm,...U?{collapseShortcut:U}:{},headerPlacement:b,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:D===!1?!1:typeof D=="string"?D:o.launcher?.iconUrl,activeConversationId:A.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:X=>Dp(X,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:X=>os(X),attachTooltip:Qt,onStartNew:()=>Op({focusComposer:!0}),onClose:()=>xn(),onRequestDeleteConversation:X=>zm(X),onRequestClearHistory:()=>TS(),...a.resetDevice?{onRequestResetIdentity:()=>kS()}:{}};st=yC({plugins:l,config:o,getPresentation:()=>Ht??"panel",getReturnSurface:()=>kl,close:()=>xn(),createView:({slots:X,renderDom:oe,onModelChange:pe,railSections:Xe})=>(es=y.createHistoryView({...z,railSections:pS(Xe),slots:X,renderDom:oe,onModelChange:pe,onAnnounce:Hl}),es),onElementChanged:(X,oe)=>{if(!oe?.isConnected)return Wp(X);Wm(X),oe.replaceWith(X),xp()}}),st.view.setNewConversationRequired(Pl.recovery==="new_conversation_required"),r?.focus!==!1&&(Ht!=="rail"||r?.keyboard===!0)&&Ul(),Ut(),Sn(),yr(),w.emit("history:opened",{presentation:Ht,returnSurface:kl,timestamp:Date.now()})},$l=()=>{},xn=r=>{if(!Ct)return;ji+=1;let a=kl,p=mp,f=st,y=r?.restoreFocus!==!1;Ct=!1;let b=!1,D=null,q=()=>{if(!b){if(b=!0,$l=()=>{},D!==null&&clearTimeout(D),Bt=!1,Ji(),Nl(),f?.dispose(),f?.view.destroy(),f?.element.remove(),st===f&&(st=null,es=null,Vi=null,Ht=null,Tl=null,mp=null),Ut(),Sn(),yr(),y){let z=p??cn;z?.isConnected?z.focus():Xr()}w.emit("history:closed",{returnSurface:a,timestamp:Date.now()})}},U=f&&f.element===f.view.element?f.view.playExit():null;if(!U){q();return}$l=q,D=setTimeout(q,Yw),U.then(q)},Dm=r=>{if(!(r.key!=="Escape"||!Ct||!st)){if(Ht==="rail"){let a=r.target;if(!(a instanceof Node)||!(st.element.contains(a)||Bt&&$o?.contains(a)===!0))return}r.preventDefault(),r.stopPropagation(),xn()}};de.addEventListener("keydown",Dm),fe.push(()=>de.removeEventListener("keydown",Dm));let ql=null,Om=!1,ta=()=>{if(!rr)return;let r=o.layout?.header?.titleSource==="conversation",a=r&&ql?.trim()||null;rr.textContent=a??o.launcher?.title??"Chat Assistant";let p=rr.closest(".persona-combo-btn");if(!p)return;let f=!r||A.getActiveConversationId()!==null;p.setAttribute("data-persona-menu-locked",f?"false":"true"),p.setAttribute("aria-haspopup",f?"true":"false"),f||p.setAttribute("aria-expanded","false"),p.style.cursor=f?"pointer":"default";let y=p.querySelector("svg");y&&(y.style.display=f?"":"none")},SS=r=>{r!==ql&&(ql=r,ta())},os=r=>{Om=r?.starred===!0,SS(r&&r.title.trim()||null),ta()};ta(),de.addEventListener("persona:title-menu-builtin",r=>{let a=r.detail?.actionId,p=A.getActiveConversationId();p&&(a==="delete"?zm(p):a==="star"&&A.canUpdateConversations()&&_p(p,{starred:!Om}).catch(()=>{}))});let zl=0,xS=250,jl=null,Vl=()=>{jl&&clearTimeout(jl),jl=null};fe.push(Vl);let _m=()=>{Vl();let r=Yr;r&&(qi=!0,r.hidden=!1,ke.style.display="none",zi())},Kl=()=>{zl+=1,Vl(),Yr&&(Yr.remove(),Yr=null,qi=!1,ke.style.removeProperty("display"),jn(Ie,!1),zi())},AS=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;ke.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Bp=(r,a)=>G("div",{className:_n("persona-conversation-loading-bubble",a&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:r}}),Nm=()=>G("div",{className:"persona-conversation-loading-body"},Bp("58%",!1),Bp("72%",!0),Bp("44%",!1)),Fm=r=>{Yr?.remove(),Yr=r,r.hidden=!qi,te.insertBefore(r,ke),Vl(),qi||(jl=setTimeout(_m,xS)),jn(Ie,!0)},MS=()=>{let r={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Nm},a=null,p=l.find(f=>f.renderLoadingIndicator);p?.renderLoadingIndicator&&(a=p.renderLoadingIndicator(r)),a===null&&o.loadingIndicator?.render&&(a=o.loadingIndicator.render(r)),Fm(G("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},a??Nm()))},ES=r=>{let a=()=>{Dp(r,{focusComposer:!0}).catch(()=>{})},p=wo()?()=>{Kl(),ea()}:void 0,f=(q,U)=>{let z=G("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:q});return z.addEventListener("click",U),z},y=()=>G("div",{className:"persona-conversation-loading-error-body"},G("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),G("div",{className:"persona-conversation-loading-error-actions"},f(Qe.openConversationRetryLabel,a),p?f(Qe.openConversationBackLabel,p):null)),b=Object.freeze({conversationId:r,config:o,copy:Object.freeze({title:Qe.openConversationErrorTitle,retryLabel:Qe.openConversationRetryLabel,backLabel:Qe.openConversationBackLabel}),retry:a,...p?{back:p}:{},defaultRenderer:y}),D=null;for(let q of l)if(q.renderHistoryOpenError){try{D=q.renderHistoryOpenError(b)}catch(U){console.warn("[persona] renderHistoryOpenError threw",U),D=null}if(D)break}Fm(G("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},D??y())),_m()};w.on("history:closed",()=>{Yr&&jn(Ie,!0)});let Dp=async(r,{focusComposer:a=!1}={})=>{let p=_s(),f=!!st;st?.view.setActiveConversationId(r),Kl();let y=zl;MS(),Ct&&(Ht==="panel"||Bt)&&xn({restoreFocus:!1}),Ps=!0;try{await A.openConversation(r,{scope:p})}catch(b){throw y===zl&&ES(r),b}finally{Ps=!1}y===zl&&(Kl(),Wt.clear(),so(),wn(),Qd()||yl(),AS(),zo(),f||os(null),w.emit("history:conversationOpened",{conversationId:r,title:ql,scope:p,timestamp:Date.now()}),a&&Xr())},Op=async({focusComposer:r=!1}={})=>{Kl(),await A.startNewConversation({scope:_s()}),os(null),Wt.clear(),so(),wn(),yl(),zo();let a=A.getActiveConversationId();st?.view.setActiveConversationId(a),w.emit("history:conversationStarted",{conversationId:a,timestamp:Date.now()}),Ct&&(Ht==="panel"||Bt)&&xn({restoreFocus:!1}),r&&Xr()},_p=async(r,a)=>{let p=await A.updateConversation(r,{...a,...a.title!==void 0?{title:a.title.trim()}:{}});return st?.view.applyConversationSummary(p),!st&&r===A.getActiveConversationId()&&os(p),p},Um=async r=>{let a=_s(),p=A.getActiveConversationId()===r;await A.deleteConversation(r,{scope:a}),st?.view.removeConversationSummary(r),p&&(os(null),Wt.clear(),so(),wn(),zo()),w.emit("history:conversationDeleted",{conversationId:r,scope:a,wasActive:p,timestamp:Date.now()})},$m=async r=>{let a=r?.scope??_s(),p=r?.allTargets?null:r?.targetId??pm(),f=await A.clearConversationHistory({...p?{targetId:p}:{},scope:a});return os(null),Wt.clear(),so(),wn(),zo(),w.emit("history:cleared",{deleted:f.deleted,scope:a,targetId:p,timestamp:Date.now()}),f},qm=async()=>{if(!Dn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let r=!1;try{r=(await A.resetHistoryDevice()).remoteRevocationConfirmed}finally{os(null),A.clearArtifacts(),Wt.clear(),dp=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),Z={},he.syncFromMetadata(),K?.clear&&fl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),so(),wn(),zo(),xn({restoreFocus:!1}),Xr(),ve||St?.launcher.element.focus()}return Hl(r?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),w.emit("history:identityReset",{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},Np=()=>ho?we:de,zm=async r=>await md({host:Np(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Um(r),"deleted"):"cancelled",TS=async()=>{let r=_s()==="verified-user";return await md({host:Np(),title:Qe.clearHistoryConfirmTitle,description:r?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await $m(),"cleared"):"cancelled"},kS=async()=>{if(!await md({host:Np(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:a}=await qm();return{outcome:"reset",remoteRevocationConfirmed:a}},Kn=k("button","persona-history-earlier");Kn.type="button",Kn.textContent=Qe.showEarlierMessagesLabel,Kn.setAttribute("data-persona-history-earlier",""),Object.assign(Kn.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 zo=()=>{if(!(wo()&&!!Pl.nextMessageCursor&&!!A.getActiveConversationId())){Kn.remove();return}Kn.textContent=Qe.showEarlierMessagesLabel,Kn.parentNode!==te&&te.insertBefore(Kn,te.firstChild)};Kn.addEventListener("click",()=>{let r=A.getActiveConversationId(),a=Pl.nextMessageCursor;if(!r||!a||Kn.disabled)return;Kn.disabled=!0;let p=te.scrollHeight,f=te.scrollTop;A.loadOlderMessages(r,a,{scope:_s()}).then(()=>{te.scrollTop=f+(te.scrollHeight-p),Sn()}).catch(()=>{}).finally(()=>{Kn.disabled=!1,zo()})});let PS=()=>{let r=gs({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 r.button.addEventListener("click",a=>{if(!(!wo()||dm())){if(Ct){xn();return}ea({invoker:r.button,keyboard:a.detail===0})}}),r},jm=()=>{if(!wo()){Co?.remove(),cn=null,Co=null;return}if(Co&&!Co.isConnected&&(cn=null,Co=null),!cn&&Ae){let f=PS();cn=f.button,Co=f.wrapper;let y=Be.clearChatButtonWrapper||Be.closeButtonWrapper;y?.parentNode&&Ae.contains(y)?y.parentNode.insertBefore(Co,y):Ae.appendChild(Co)}if(!cn||!Co)return;let r=qs()||Ct&&Ht==="rail";if(Co.style.display=r?"none":"",r){document.activeElement===cn&&Ul();return}let a=dm();cn.disabled=a,cn.setAttribute("aria-disabled",a?"true":"false");let p=a?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;cn.setAttribute("aria-label",p),(o.features?.history?.presentation??"panel")==="panel"?(cn.removeAttribute("aria-expanded"),cn.removeAttribute("aria-controls")):(cn.setAttribute("aria-expanded",Ct?"true":"false"),cn.setAttribute("aria-controls",bp))},Gl=!1,IS=()=>{let r=Be.clearChatButton;if(r){if(wo()){Gl||(yp=r.getAttribute("aria-label")??"",Gl=!0),r.setAttribute("aria-label",Qe.newConversationLabel),r.removeAttribute("title");return}Gl&&(Gl=!1,yp&&r.setAttribute("aria-label",yp))}},yr=()=>{Qe=ru(o.features?.history?.copy),jm(),Zi(),IS(),zo()};Cd=yr,Ng=r=>{Pl=r,st?.view.setNewConversationRequired(r.recovery==="new_conversation_required"),$i(r.sendBlocked||Rn),zo()},Fg=r=>{(r.code==="history_continuity_reset"||r.code==="conversation_deleted_recovered")&&(Wt.clear(),so(),wn()),Hl(r.message),st?.view.refresh()},mm(),yr(),fe.push(()=>{Il?.(),Ll?.(),ji+=1,$l(),st?.dispose(),st?.view.destroy(),st=null}),o.clientToken&&A.initClientSession().then(()=>{if(wo())return A.reconcileBootConversation({scope:Cp()})}).then(()=>{zo()}).catch(r=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",r)}),(C||o.onSSEEvent)&&A.setSSEEventCallback((r,a)=>{o.onSSEEvent?.(r,a),bd(r,a)});let Vm=()=>{let r=o.resume??(ie?Fo.getStoredResumableHandle?.():null);r&&typeof o.reconnectStream=="function"&&A.resumeFromHandle(r)};S?S.then(r=>{if(r){if(r.metadata&&(Z=Hg(r.metadata),he.syncFromMetadata()),r.messages?.length){Ps=!0;try{A.hydrateMessages(r.messages)}finally{Ps=!1}wl()}r.artifacts?.length&&A.hydrateArtifacts(r.artifacts,r.selectedArtifactId??null),$f(r.draft)}}).catch(r=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",r)}).finally(()=>{np=!0,B(),Vm()}):($f(H),Vm());let LS=()=>{!Le()||ve||!(o.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},HS=(r,a)=>r?a?{refs:[...r.refs,...a.refs],finalize:async()=>{let[p,f]=await Promise.allSettled([r.finalize(),a.finalize()]),y=[];return p.status==="fulfilled"?y.push(p.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",p.reason),f.status==="fulfilled"?y.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),TT(y)}}:r:a,Fp=()=>{let a=le.getInlineMessageFields?.();return a&&a.contentSegments.some(f=>f.kind==="mention")?a.contentSegments:void 0},jo=!1,rs=null,Ql=()=>{le.value="",le.style.height="auto",go(),oa()},Up="data-persona-composer-notice",js=null;function RS(r){Qa(r),!(Le()||!rt)&&(rt.hasAttribute(wi)||(rt.setAttribute(Up,""),rt.setAttribute("role","status"),rt.setAttribute("aria-live","polite"),rt.textContent=r,js&&clearTimeout(js),js=setTimeout(()=>{if(js=null,!!rt?.hasAttribute(Up)&&(rt.removeAttribute(Up),rt.removeAttribute("role"),rt.removeAttribute("aria-live"),u)){let a=A.getStatus();Va(rt,Ug(a),o.statusIndicator??{},a)}},4e3)))}function WS(){let r=be.getState().pendingSubmission;r&&(ws(void 0),le&&(le.value=r.text,le.dispatchEvent(new Event("input",{bubbles:!0})),go()),r.options.selectedModelId&&(be.setSelectedModelId(r.options.selectedModelId),ir?.repaint()),r.options.activeModeIds?.length&&Za(r.options.activeModeIds),r.options.quote&&fo(r.options.quote),le?.focus())}let BS=r=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",r)},Km=(r={})=>{let a=(r.overrideText??le?.value??"").trim();return r.resolveInlineCommand&&a?(Pt?.takeInlineCommand(a)??Promise.resolve(null)).then(p=>Gm(r,a,p)):Gm(r,a,null)},Gm=(r,a,p)=>{if(p?.kind==="action"){Ql(),Pt?.clear(),Rr();return}let f=p?.kind==="server"?p.mentions:null,y=p?.kind==="prompt"?p.sendText:a,b=r.pending?.contentParts,D=(Ye?.hasAttachments()??!1)||(b?.length??0)>0;if(!Gb({text:y,hasAttachments:D,attachmentsReady:Ye?.isReady()??!0,hasMentions:Pt?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:vo(),sendDisabled:Qr()}))return;let q=A.isStreaming()?Pd():"block";if(q==="defer-one"&&!r.pending){if(be.getState().pendingSubmission){RS("One message is already queued. Edit or remove it first.");return}DS({intent:r,sendText:y,serverMentions:f});return}let U={text:y,mentionRefs:[...Pt?.getMentionRefs()??[],...f?.refs??[]],contentSegments:p?.kind==="prompt"?void 0:Fp(),options:{...be.getState().selectedModelId&&{selectedModelId:be.getState().selectedModelId},...be.getState().activeModeIds.length>0&&{activeModeIds:[...be.getState().activeModeIds]},...be.getState().quote&&{quote:{...be.getState().quote}}},viaVoice:r.viaVoice};r.pending&&(U.options={...r.pending.options},U.contentSegments=r.pending.contentSegments,U.mentionRefs=[...r.pending.mentionRefs],U.viaVoice=r.pending.viaVoice);let z=()=>{if(b?.length)return[...b];if(!Ye?.hasAttachments())return;let ut=[...Ye.getContentParts()];return U.text&&ut.push(Mo(U.text)),ut};U.contentParts=z();let X=()=>{$r(),LS();let ut=Pt?.collectForSubmit()??null,Vt=HS(ut,f),Dt=z();r.consumeDraft!==!1&&Ql();let At={selectedModelId:U.options.selectedModelId,activeModeIds:U.options.activeModeIds},nn=q==="interrupt";nn&&A.cancel(),A.sendMessage(U.text,{contentParts:Dt,mentions:Vt??void 0,contentSegments:U.contentSegments,viaVoice:U.viaVoice,composerOptions:At,...U.options.quote&&{quote:U.options.quote},...nn&&{interrupt:!0}}),Ye?.hasAttachments()&&Ye.clearAttachments(),ut&&Pt?.clear(),Rr();let Je=be.getState().activeModeIds,on=Bb(Je,o.composer?.modes);on.length!==Je.length&&Za(on),be.getState().quote&&fo(void 0),hl(),Wd.release(),to()},oe=o.composer?.onBeforeSend;if(!oe){X();return}let pe=new AbortController;rs=pe;let Xe=ut=>{if(rs=null,ut.status==="error"){BS(ut.error);return}ut.status==="proceed"&&X()},ct=Qb(oe,U,pe.signal);if(!(ct instanceof Promise)){Xe(ct);return}return be.setPreparing(!0),ct.then(Xe).finally(()=>be.setPreparing(!1))};function DS(r){let a=be.getState(),p=Ye?.hasAttachments()??!1,f=p?[...Ye.getContentParts()]:[];p&&r.sendText&&f.push(Mo(r.sendText));let y=Nu({text:r.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Pt?.getMentionRefs()??[],...r.serverMentions?.refs??[]],contentSegments:Fp(),options:{...a.selectedModelId&&{selectedModelId:a.selectedModelId},...a.activeModeIds.length>0&&{activeModeIds:[...a.activeModeIds]},...a.quote&&{quote:{...a.quote}}},viaVoice:r.intent.viaVoice});ws(y),r.intent.consumeDraft!==!1&&Ql(),p&&Ye.clearAttachments(),Pt?.clear(),Rr(),a.quote&&fo(void 0),hl(),Wd.release(),to(),Qa("Message queued. It sends when the response finishes.")}function OS(){let r=be.getState().pendingSubmission;r&&(ws(void 0),Yl(r.text,{consumeDraft:!1,pending:r}))}function _S(r){if(o.messageActions?.showEdit!==!0)return;let a=A.getMessages().find(p=>p.id===r);!a||!yu(a)||Ur!==r&&($r(),Ur=r,dr=Fb({messageId:r,initialText:a.content,onSave:p=>NS(r,p),onCancel:()=>$r()}),Wt.delete(r),qn(ke,A.getMessages(),vt),dr.focus())}function NS(r,a){let p=dr;if(Ur=null,dr=null,p?.destroy(),Wt.delete(r),!A.resubmitFrom(r,{reason:"edit",replacement:{text:a,mentionRefs:[],options:{}}})){qn(ke,A.getMessages(),vt);return}Sn()}function FS(r){if(A.isStreaming())return;let a=hu(A.getMessages(),r);a&&($r(),A.resubmitFrom(a,{reason:"retry"})&&Sn())}el={regenerate:FS,edit:_S,quote:r=>{let p=A.getMessages().find(f=>f.id===r)?.content?.trim();p&&(fo({text:p,messageId:r}),le?.focus())}};let na=async r=>{if(!jo){jo=!0;try{await Km({resolveInlineCommand:!0,...r})}finally{jo=!1}}};function Xl(r){Qr()||(Ql(),Yl(r,{consumeDraft:!1}))}let Yl=(r,a)=>{if(jo)return;jo=!0;let p=()=>{jo=!1};try{let f=Km({...a,overrideText:r});f instanceof Promise?f.finally(p):p()}catch(f){throw p(),f}},US=r=>{if(r.preventDefault(),A.isStreaming()){A.cancel(),ot?.reset(),gt?.update();return}jo||na()},$S=()=>o.features?.composerHistory!==!1,$p={...ju},qp=!1,oa=()=>{$p={...ju}},qS=()=>A.getMessages().filter(r=>r.role==="user").map(r=>r.content??"").filter(r=>r.length>0),zS=r=>{if(!le)return;qp=!0,le.value=r,le.dispatchEvent(new Event("input",{bubbles:!0})),qp=!1;let a=le.value.length;le.setSelectionRange(a,a)},jS=r=>{qp||(r.isComposing||Pt?.handleInput(r.inputType??void 0),oa())},VS=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ka(le)}),KS=r=>{if(le&&!vo()&&!(!r.isComposing&&Pt?.handleKeydown(r))){if($S()&&(r.key==="ArrowUp"||r.key==="ArrowDown")&&!r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.isComposing){let a=le.selectionStart===0&&le.selectionEnd===0,p=dv({direction:r.key==="ArrowUp"?"up":"down",history:qS(),currentValue:le.value,atStart:a,state:$p});if($p=p.state,p.handled){r.preventDefault(),p.value!==void 0&&zS(p.value);return}}if(vb(r,VS())){if(A.isStreaming()){if(r.preventDefault(),Pd()==="block"||jo||Qr())return;oa(),na();return}if(jo){r.preventDefault();return}if(Qr()){r.preventDefault();return}oa(),r.preventDefault(),xe.click()}}},Qm=r=>{if(!(r.key!=="Escape"||r.isComposing)&&r.composedPath().includes(de)){if(rs){rs.abort(),rs=null,r.preventDefault(),r.stopImmediatePropagation();return}A.isStreaming()&&(A.cancel(),ot?.reset(),gt?.update(),oa(),r.preventDefault(),r.stopImmediatePropagation())}},GS=async r=>{if(o.attachments?.enabled!==!0||!Ye||vo())return;let a=xT(r.clipboardData);a.length!==0&&(r.preventDefault(),await Ye.handleFiles(a))},Gn=null,So=!1,Vs=null,ht=null,zp=()=>o.voiceRecognition?.completionBehavior==="review";function ss(r){ne?.setAttribute("data-state",r),r==="recording"?XS():Gp()}let Xm="--persona-voice-level",jp=.5,Ks=null,Vp=-1,Jl=0,Ym=()=>{let r=[],a=Ln??ne?.parentElement??null;return a&&r.push(a),Ie&&r.push(Ie),r},Kp=r=>{let a=Math.round(Math.max(0,Math.min(1,r))*100)/100;if(a!==Vp){Vp=a;for(let p of Ym())p.style.setProperty(Xm,String(a))}},QS=()=>{Vp=-1,Jl=0;for(let r of Ym())r.style.removeProperty(Xm)};function XS(){if(Ks!==null)return;if(typeof requestAnimationFrame!="function"){Kp(u?A.getVoiceLevel()??jp:jp);return}let r=()=>{Ks=requestAnimationFrame(r);let a=u?A.getVoiceLevel():null;if(a===null){Kp(jp);return}Jl+=(a-Jl)*.3,Kp(Jl)};Ks=requestAnimationFrame(r)}function Gp(){Ks!==null&&(cancelAnimationFrame(Ks),Ks=null),QS()}let Jm=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Zl=(r="user")=>{if(So||A.isStreaming())return;let a=Jm();if(!a)return;Gn=new a;let p=o.voiceRecognition??{},f=p.pauseDuration??2e3;Gn.continuous=p.provider?.browser?.continuous??!0,Gn.interimResults=!0,Gn.lang=p.provider?.browser?.language??"en-US";let y=le.value;Gn.onresult=b=>{let D="",q="";for(let z=0;z<b.results.length;z++){let X=b.results[z],oe=X[0].transcript;X.isFinal?D+=oe+" ":q=oe}let U=y+D+q;le.value=U,go(),Vs&&clearTimeout(Vs),(D||q)&&(Vs=window.setTimeout(()=>{if(le.value.trim()&&Gn&&So){if(br(),zp())return;na({viaVoice:!0})}},f))},Gn.onerror=b=>{b.error!=="no-speech"&&br()},Gn.onend=()=>{if(So){let b=le.value.trim();!zp()&&b&&b!==y.trim()&&na({viaVoice:!0}),br()}};try{if(Gn.start(),So=!0,ze.active=!0,r!=="system"&&(ze.manuallyDeactivated=!1),_o(r),ro(),to(),ne){let b=o.voiceRecognition??{};ht={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:b.iconName??"mic",iconSize:parseFloat(b.iconSize??"")||pn};let D=b.recordingBackgroundColor,q=b.recordingIconColor,U=b.recordingBorderColor;if(ne.classList.add("persona-voice-recording"),ss("recording"),ne.style.backgroundColor=D??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=q??"var(--persona-voice-recording-indicator, #ffffff)",q){let z=ne.querySelector("svg");z&&z.setAttribute("stroke",q)}U&&(ne.style.borderColor=U),ne.setAttribute("aria-label","Stop voice recognition")}}catch{br("system")}},br=(r="user")=>{if(So){if(So=!1,Vs&&(clearTimeout(Vs),Vs=null),Gn){try{Gn.stop()}catch{}Gn=null}if(ze.active=!1,_o(r),ro(),to(),ne){if(ne.classList.remove("persona-voice-recording"),ss("idle"),ht){ne.style.backgroundColor=ht.backgroundColor,ne.style.color=ht.color,ne.style.borderColor=ht.borderColor;let a=ne.querySelector("svg");a&&a.setAttribute("stroke",ht.color||"currentColor"),ht=null}ne.setAttribute("aria-label","Start voice recognition")}}},Qp=()=>{if(!ne||ht)return;let r=o.voiceRecognition??{};ht={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:r.iconName??"mic",iconSize:parseFloat(r.iconSize??"")||pn}},Xp=(r,a)=>{if(!ne)return;let p=ne.querySelector("svg");p&&p.remove();let f=ht?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||pn),y=ge(r,f,a,1.5);y&&ne.appendChild(y)},ec=()=>{ne&&ne.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Gs=()=>{if(!ne)return;Qp();let r=o.voiceRecognition??{},a=r.recordingBackgroundColor,p=r.recordingIconColor,f=r.recordingBorderColor;if(ec(),ne.classList.add("persona-voice-recording"),ss("recording"),ne.style.backgroundColor=a??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=p??"var(--persona-voice-recording-indicator, #ffffff)",p){let y=ne.querySelector("svg");y&&y.setAttribute("stroke",p)}f&&(ne.style.borderColor=f),ne.setAttribute("aria-label","Stop voice recognition")},YS=()=>{if(!ne)return;Qp();let r=o.voiceRecognition??{},a=A.getVoiceInterruptionMode(),p=r.processingIconName??"loader",f=r.processingIconColor??ht?.color??"",y=r.processingBackgroundColor??ht?.backgroundColor??"",b=r.processingBorderColor??ht?.borderColor??"";ec(),ne.classList.add("persona-voice-processing"),ss("processing"),ne.style.backgroundColor=y,ne.style.borderColor=b;let D=f||"currentColor";ne.style.color=D,Xp(p,D),ne.setAttribute("aria-label","Processing voice input"),a==="none"&&(ne.style.cursor="default")},JS=()=>{if(!ne)return;Qp();let r=o.voiceRecognition??{},a=A.getVoiceInterruptionMode(),p=a==="cancel"?"square":a==="barge-in"?"mic":"volume-2",f=r.speakingIconName??p,y=r.speakingIconColor??(a==="barge-in"?r.recordingIconColor??ht?.color??"":ht?.color??""),b=r.speakingBackgroundColor??(a==="barge-in"?r.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":ht?.backgroundColor??""),D=r.speakingBorderColor??(a==="barge-in"?r.recordingBorderColor??"":ht?.borderColor??"");ec(),ne.classList.add("persona-voice-speaking"),ss("speaking"),ne.style.backgroundColor=b,ne.style.borderColor=D;let q=y||"currentColor";ne.style.color=q,Xp(f,q);let U=a==="cancel"?"Stop playback and re-record":a==="barge-in"?"Speak to interrupt":"Agent is speaking";ne.setAttribute("aria-label",U),a==="none"&&(ne.style.cursor="default"),a==="barge-in"&&ne.classList.add("persona-voice-recording")},Vo=()=>{ne&&(ec(),ss("idle"),ht&&(ne.style.backgroundColor=ht.backgroundColor??"",ne.style.color=ht.color??"",ne.style.borderColor=ht.borderColor??"",Xp(ht.iconName,ht.color||"currentColor"),ht=null),ne.style.cursor="",ne.setAttribute("aria-label","Start voice recognition"))},Yp=()=>{if(!vo()){if(Tn(o.voiceRecognition?.provider)){let r=A.getVoiceStatus(),a=A.getVoiceInterruptionMode();if(a==="none"&&(r==="processing"||r==="speaking"))return;if(a==="cancel"&&(r==="processing"||r==="speaking")){A.stopVoicePlayback();return}if(A.isBargeInActive()){A.stopVoicePlayback(),A.deactivateBargeIn().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,ro(),_o("user"),Vo()});return}A.toggleVoice().then(()=>{ze.active=A.isVoiceActive(),ze.manuallyDeactivated=!A.isVoiceActive(),ro(),_o("user"),A.isVoiceActive()?Gs():Vo()});return}if(So){let r=le.value.trim();ze.manuallyDeactivated=!0,ro(),br("user"),r&&!zp()&&na()}else ze.manuallyDeactivated=!1,ro(),Zl("user")}};Id=Yp,ne&&fe.push(()=>{Tn(o.voiceRecognition?.provider)?(A.isVoiceActive()&&A.toggleVoice(),Vo()):br("system")});let ZS=w.on("assistant:complete",()=>{be.getState().pendingSubmission&&setTimeout(()=>{A.isStreaming()||OS()},0)});fe.push(ZS);let ex=w.on("assistant:complete",()=>{Nf&&(ze.active||ze.manuallyDeactivated||Nf==="assistant"&&!ze.lastUserMessageWasVoice||setTimeout(()=>{!ze.active&&!ze.manuallyDeactivated&&(Tn(o.voiceRecognition?.provider)?A.toggleVoice().then(()=>{ze.active=A.isVoiceActive(),_o("auto"),A.isVoiceActive()&&Gs()}):Zl("auto"))},600))});fe.push(ex);let tx=w.on("action:resubmit",()=>{setTimeout(()=>{A&&!A.isStreaming()&&A.continueConversation()},100)});fe.push(tx);let Zm=()=>{pt(!ve,"user")},St=null,dn=null;if(ce&&!Le()){let{instance:r,element:a}=dg({config:o,plugins:l,onToggle:Zm});St=r,r||(dn=a)}St?t.appendChild(St.element):dn&&t.appendChild(dn),Ui(),Ts(),Al(),ap(),$i(A.isStreaming()),Qd()||(Hn()==="follow"?gr(!0):yl()),Cw(),ye&&(!ce||Le()?setTimeout(()=>Xr(),0):ve&&setTimeout(()=>Xr(),200));let is=null,eh=()=>{is&&(is.disconnect(),is.observe(Ie),is.observe(de))},ra=()=>{if(Le()){Hr(),Ui();return}let r=Lt(o),a=o.launcher?.sidebarMode??!1,p=t.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640,b=p.innerWidth<=y,D=f&&b&&ce;try{if(D){Wr(),Li=ll();return}let q=!1;qt&&(qt=!1,Wr(),q=!0);let U=ll();if(!q&&U!==Li&&(Wr(),q=!0),Li=U,q&&rl(),!ce&&!r){we.style.height="",we.style.width="";return}if(!a&&!r){let X=o?.launcher?.width??o?.launcherWidth??Jo;we.style.width=X,we.style.maxWidth=X}al(),xf()}finally{if(Hr(),Ja(),Ui(),ve&&ce){let U=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),z=o.launcher?.sidebarMode??!1,X=o.launcher?.mobileFullscreen??!0,oe=Lt(o)&&X&&U,pe=z||X&&U&&ce||oe;if(pe&&!bo){let Xe=t.getRootNode(),ct=Xe instanceof ShadowRoot?Xe.host:t.closest(".persona-host");ct&&!yo&&(yo=Vu(ct,o.launcher?.zIndex??an)),bo=Ku(t.ownerDocument)}else pe||(yo?.(),yo=null,bo?.(),bo=null)}}};ra();let tc=t.ownerDocument.defaultView??window;if(tc.addEventListener("resize",ra),fe.push(()=>tc.removeEventListener("resize",ra)),typeof ResizeObserver<"u"){is=new ResizeObserver(()=>{Ja()}),eh(),fe.push(()=>{is?.disconnect(),is=null});let r=new ResizeObserver(()=>{Fl()});r.observe(de),fe.push(()=>r.disconnect())}tc.addEventListener("resize",Fl),fe.push(()=>tc.removeEventListener("resize",Fl)),Bn=te.scrollTop;let th=Qo(te),nh=()=>{let r=te.scrollTop,a=Qo(te),p=a<th;if(th=a,!sr()){Bn=r,Ut();return}let{action:f,nextLastScrollTop:y}=Gh({following:Wn.isFollowing(),currentScrollTop:r,lastScrollTop:Bn,nearBottom:cs(te,Do),userScrollThreshold:hw,isAutoScrolling:Cn||dl||p,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Bn=y,f==="resume"){bl()||wn();return}f==="pause"&&Di()};if(te.addEventListener("scroll",nh,{passive:!0}),fe.push(()=>te.removeEventListener("scroll",nh)),typeof ResizeObserver<"u"){let r=new ResizeObserver(()=>{Tw(),su(ke)});r.observe(ke),r.observe(te),fe.push(()=>r.disconnect())}let oh=()=>{sr()&&Wn.isFollowing()&&bl()&&Di()},rh=te.ownerDocument;rh.addEventListener("selectionchange",oh),fe.push(()=>{rh.removeEventListener("selectionchange",oh)});let nx=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),sh=r=>{nx.has(r.key)&&(Vr(),qg()&&sr()&&Wn.isFollowing()&&Di())},ih=r=>{r.target?.closest("a, button, [tabindex], input, textarea, select")&&(Vr(),qg()&&sr()&&Wn.isFollowing()&&Di())};te.addEventListener("keydown",sh),te.addEventListener("focusin",ih),fe.push(()=>{te.removeEventListener("keydown",sh),te.removeEventListener("focusin",ih)});let ah=r=>{if(r.deltaY!==0&&Vr(),!sr())return;let a=Qh({following:Wn.isFollowing(),deltaY:r.deltaY,nearBottom:cs(te,Do),resumeWhenNearBottom:!0});a==="pause"?Di():a==="resume"&&!bl()&&wn()};te.addEventListener("wheel",ah,{passive:!0}),te.addEventListener("touchmove",Vr,{passive:!0}),te.addEventListener("pointerdown",Vr,{passive:!0}),fe.push(()=>{te.removeEventListener("touchmove",Vr),te.removeEventListener("pointerdown",Vr)}),fe.push(()=>te.removeEventListener("wheel",ah)),Rt.addEventListener("click",()=>{so(),te.scrollTop=te.scrollHeight,Bn=te.scrollTop,wn(),gr(!0),Ut()}),fe.push(()=>Rt.remove()),fe.push(()=>{zf(),so()});let lh=()=>{_e&&(_r&&(_e.removeEventListener("click",_r),_r=null),Fe()?(_e.style.display="",_r=()=>{pt(!1,"user")},_e.addEventListener("click",_r)):_e.style.display="none")};lh(),(()=>{let{clearChatButton:r}=Be;r&&r.addEventListener("click",()=>{if(wo()){Op({focusComposer:!0}).catch(p=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",p)});return}A.clearMessages(),Wt.clear(),wn(),si(Be.composerOverlay);try{localStorage.removeItem(Ci),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ci}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ci)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),K?.clear&&fl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),Z={},he.syncFromMetadata(),Ye?.clearAttachments(),hl(),ws(void 0),fo(void 0),$r(),Re?.clear(),ot?.reset(),gt?.update()})})();let ch=[["keydown",KS],["input",jS],["input",go],["input",Rr],["keyup",Rr],["paste",GS],["focus",rw]],dh=r=>{if(r)for(let[a,p]of ch)et?.addListener(r,a,p)},ox=r=>{if(r)for(let[a,p]of ch)et?.removeListener(r,a,p)},ph=()=>{et&&(et.addListener(et.form,"submit",US),et.addListener(et.footer,"click",Rr),dh(le),ne&&et.addListener(ne,"click",Yp))};ph();let uh=()=>{Pt?.onComposerSwap((r,a)=>{ox(a),le=r,et&&(et.input=r),dh(r),Hd(),ep(),go()})};uh();let Jp=!1;function gh(){if(!Jp){Jp=!0;try{let r=le?.value??"",a=Ie.ownerDocument??document,p=le?a.activeElement===le:!1;Gp(),et?.destroy(),et=null,Pt?.destroy(),Pt=null;let f=null,y=()=>(f=Le()?ed({config:o}):_a({config:o}),f.footer),b=Zg(y)??y();Pn.replaceComposer(b),Ie=Pn.composer.footer;let D=f!==null&&b===f.footer;xs=!D,$g=D?f.setSendButtonMode:()=>{},Jg(Ie),tf(Ie),nf(),of(),rf(),uh(),sf(),Rd(),af(),ph();let q=Or.indexOf(Bo);Bo.destroy(),Bo=Da(or),q>=0&&(Or[q]=Bo),le&&(le.value=r),go(),Rr(),Al(),Ts(),$i(A.isStreaming()),ze.active&&ss("recording"),Wr(),eh(),Hr(),to(),Sl(),p&&le?.focus()}finally{Jp=!1}}}let sa=t.ownerDocument??document;sa.addEventListener("keydown",Qm,!0);let fh=()=>{jd()},mh=()=>{sa.visibilityState==="hidden"&&jd()};typeof window<"u"&&(window.addEventListener("pagehide",fh),sa.addEventListener("visibilitychange",mh),fe.push(()=>{window.removeEventListener("pagehide",fh),sa.removeEventListener("visibilitychange",mh)}));let hh="persona-attachment-drop-active",ia=0,Zp=()=>{ia=0,de.classList.remove(hh)},Qs=()=>o.attachments?.enabled===!0&&Ye!==null&&!vo(),yh=r=>{!hd(r.dataTransfer)||!Qs()||(ia++,ia===1&&de.classList.add(hh))},bh=r=>{!hd(r.dataTransfer)||!Qs()||(ia--,ia<=0&&Zp())},vh=r=>{!hd(r.dataTransfer)||!Qs()||(r.preventDefault(),r.dataTransfer.dropEffect="copy")},Ch=r=>{if(!hd(r.dataTransfer)||!Qs())return;r.preventDefault(),r.stopPropagation(),Zp();let a=Array.from(r.dataTransfer.files??[]);a.length!==0&&Ye.handleFiles(a)},vr=!0;de.addEventListener("dragenter",yh,vr),de.addEventListener("dragleave",bh,vr),t.addEventListener("dragover",vh,vr),t.addEventListener("drop",Ch,vr);let nc=t.ownerDocument,wh=r=>{Qs()&&r.preventDefault()},Sh=r=>{Qs()&&r.preventDefault()};nc.addEventListener("dragover",wh),nc.addEventListener("drop",Sh),fe.push(()=>{et?.destroy(),et=null,Gp(),mo?.destroy(),mo=null,Ro?.destroy(),Ro=null,ar?.destroy(),ar=null,lr?.destroy(),lr=null,ir=null,kd=null,jd(),Bi.destroy(),js&&clearTimeout(js),$r(),rs?.abort(),rs=null,Ye?.destroy(),Ye=null,be.destroy(),sa.removeEventListener("keydown",Qm,!0),Pt?.destroy()}),fe.push(()=>{de.removeEventListener("dragenter",yh,vr),de.removeEventListener("dragleave",bh,vr),t.removeEventListener("dragover",vh,vr),t.removeEventListener("drop",Ch,vr),nc.removeEventListener("dragover",wh),nc.removeEventListener("drop",Sh),Zp()}),fe.push(()=>{A.cancel()}),St?fe.push(()=>{St?.destroy()}):dn&&fe.push(()=>{dn?.remove()});let xt={update(r){let a=o.toolCall,p=o.messageActions,f=o.layout?.messages,y=o.colorScheme,b=o.loadingIndicator,D=o.iterationDisplay,q=o.features?.showReasoning,U=o.features?.showToolCalls,z=o.features?.toolCallDisplay,X=o.features?.reasoningDisplay,oe=o.features?.streamAnimation?.type,pe=o.features?.history?.enabled===!0,Xe=o.features?.history?.provider,ct=o.getIdentityProof,ut=o.clientToken,Vt=o.contextMentions;o=cC({...o,features:i},r),i=o.features,o=wg(o),s(),Nd(),Ia(t,o),Ua(t,o),$a(t,o),Lo(),oo(),o.colorScheme!==y&&Af();let Dt=Ag.getForInstance(o.plugins);l.length=0,l.push(...Dt),xm(),ce=o.launcher?.enabled??!0,at=o.launcher?.autoExpand??!1,Io=o.features?.showReasoning??!0,j=o.features?.showToolCalls??!0,_=o.features?.scrollToBottom??{};let At=Hn();V=o.features?.scrollBehavior??{},At!==Hn()&&(so(),wn()),_f(),Vg(),Ut();let nn=C;if(C=o.features?.showEventStreamToggle??!1,C&&!nn){if(Re||(ja(),A.setSSEEventCallback((Y,je)=>{o.onSSEEvent?.(Y,je),bd(Y,je)})),!Ze&&Ae){let Y=o.features?.eventStream?.classNames,je="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"+(Y?.toggleButton?" "+Y.toggleButton:"");Ze=k("button",je),Ze.style.width="28px",Ze.style.height="28px",Ze.style.color=gn.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let Ge=en(MC,"18px","currentColor",1.5);Ge&&Ze.appendChild(Ge);let tt=Be.clearChatButtonWrapper,yt=Be.closeButtonWrapper,Zt=tt||yt;Zt&&Zt.parentNode===Ae?Ae.insertBefore(Ze,Zt):Ae.appendChild(Ze),Ze.addEventListener("click",()=>{zt?Ss():Ld()})}}else!C&&nn&&(Ss(),Ze&&(Ze.remove(),Ze=null),Re?.clear(),Me?.destroy(),Re=null,Me=null,ot?.reset(),ot=null,Ve=null);if(o.launcher?.enabled===!1&&St&&(St.destroy(),St=null),o.launcher?.enabled===!1&&dn&&(dn.remove(),dn=null),o.launcher?.enabled!==!1&&!St&&!dn){let{instance:Y,element:je}=dg({config:o,plugins:l,onToggle:Zm});St=Y,Y||(dn=je),t.appendChild(je)}St&&St.update(o),ta(),Ir&&o.launcher?.subtitle!==void 0&&(Ir.textContent=o.launcher.subtitle);let Je=o.layout?.header;if(Je?.layout!==Ue&&Ae){let Y=Je?Zc(o,Je,{showClose:Fe(),onClose:()=>pt(!1,"user")}):fs({config:o,showClose:Fe(),onClose:()=>pt(!1,"user")});Pn.replaceHeader(Y),Ae=Pn.header.element,wt=Pn.header.iconHolder,rr=Pn.header.headerTitle,Ir=Pn.header.headerSubtitle,_e=Pn.header.closeButton,Ue=Je?.layout,ta()}else if(Je){if(wt&&(wt.style.display=Je.showIcon===!1?"none":""),rr&&(rr.style.display=Je.showTitle===!1?"none":""),Ir&&(Ir.style.display=Je.showSubtitle===!1?"none":""),_e){let Y=Fe()&&Je.showCloseButton!==!1;_e.style.display=Y?"":"none"}if(Be.clearChatButtonWrapper){let Y=Je.showClearChat;if(Y!==void 0){Be.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:je}=Be;je&&!je.classList.contains("persona-absolute")&&(Y?je.classList.remove("persona-ml-auto"):je.classList.add("persona-ml-auto"))}}}let xo=o.layout?.showHeader!==!1;Ae&&(Ae.style.display=xo?"":"none");let Ko=o.layout?.showFooter!==!1;Ie&&(Ie.style.display=Ko?"":"none"),Hr(),Ut(),ce!==Te?ce?pt(at,"auto"):(ve=!0,Ui()):at!==F&&pt(at,"auto"),F=at,Te=ce,ra(),lh();let as=JSON.stringify(o.toolCall)!==JSON.stringify(a),ao=JSON.stringify(o.messageActions)!==JSON.stringify(p),Yt=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),lo=o.loadingIndicator?.render!==b?.render||o.loadingIndicator?.renderIdle!==b?.renderIdle||o.loadingIndicator?.showBubble!==b?.showBubble,Xs=o.iterationDisplay!==D,L=(o.features?.showReasoning??!0)!==(q??!0)||(o.features?.showToolCalls??!0)!==(U??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(z)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(X);(as||ao||Yt||lo||Xs||L)&&A&&(qr++,qn(ke,A.getMessages(),vt));let Se=o.features?.streamAnimation?.type;if(Se!==oe&&Se&&Se!=="none"){let Y=Ud(Se,o.features?.streamAnimation?.plugins);Y&&ma(Y,t)}let se=o.launcher??{},Mt=se.headerIconHidden??!1,Ot=o.layout?.header?.showIcon,Jt=Mt||Ot===!1,_t=se.headerIconName,$t=se.headerIconSize??"48px";if(wt){let Y=Ae,je=Y?.querySelector(".persona-flex-col");if(Jt)wt.style.display="none",Y&&je&&!Y.contains(je)&&Y.insertBefore(je,Y.firstChild);else{if(wt.style.display="",wt.style.height=$t,wt.style.width=$t,Y&&je&&(Y.contains(wt)?wt.nextSibling!==je&&(wt.remove(),Y.insertBefore(wt,je)):Y.insertBefore(wt,je)),_t){let tt=parseFloat($t)||24,yt=ge(_t,tt*.6,"currentColor",1);yt?wt.replaceChildren(yt):wt.textContent=se.agentIconText??"\u{1F4AC}"}else if(se.iconUrl){let tt=wt.querySelector("img");if(tt)tt.src=se.iconUrl,tt.style.height=$t,tt.style.width=$t;else{let yt=document.createElement("img");yt.src=se.iconUrl,yt.alt="",yt.className="persona-rounded-xl persona-object-cover",yt.style.height=$t,yt.style.width=$t,wt.replaceChildren(yt)}}else{let tt=wt.querySelector("svg"),yt=wt.querySelector("img");(tt||yt)&&wt.replaceChildren(),wt.textContent=se.agentIconText??"\u{1F4AC}"}let Ge=wt.querySelector("img");Ge&&(Ge.style.height=$t,Ge.style.width=$t)}}let Et=o.layout?.header?.showTitle,rn=o.layout?.header?.showSubtitle;if(rr&&(rr.style.display=Et===!1?"none":""),Ir&&(Ir.style.display=rn===!1?"none":""),_e){let Y=Fe()&&o.layout?.header?.showCloseButton!==!1;if(_e.style.display=Y?"":"none",!Le()){let Kt=se.closeButtonSize??"";_e.style.height=Kt,_e.style.width=Kt,_e.style.minWidth=Kt,_e.style.minHeight=Kt}let je=se.closeButtonPlacement??"inline",{closeButtonWrapper:Ge}=Be,tt=je==="top-right",yt=Ge?.classList.contains("persona-absolute");if(Ge&&tt!==yt)if(Ge.remove(),tt){Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Kt=Ki??de;Kt.style.position="relative",Kt.appendChild(Ge)}else{let Kt=se.clearChat?.placement??"inline",Gt=se.clearChat?.enabled??!0;Ge.className=Gt&&Kt==="inline"?"":"persona-ml-auto",Ae&&Ae.appendChild(Ge)}if(_e.style.color=se.closeButtonColor||gn.actionIconColor,se.closeButtonBackgroundColor?(_e.style.backgroundColor=se.closeButtonBackgroundColor,_e.classList.remove("hover:persona-bg-gray-100")):(_e.style.backgroundColor="",_e.classList.add("hover:persona-bg-gray-100")),se.closeButtonBorderWidth||se.closeButtonBorderColor){let Kt=se.closeButtonBorderWidth||"0px",Gt=se.closeButtonBorderColor||"transparent";_e.style.border=`${Kt} solid ${Gt}`,_e.classList.remove("persona-border-none")}else _e.style.border="",_e.classList.add("persona-border-none");se.closeButtonBorderRadius?(_e.style.borderRadius=se.closeButtonBorderRadius,_e.classList.remove("persona-rounded-full")):(_e.style.borderRadius="",_e.classList.add("persona-rounded-full")),se.closeButtonPaddingX?(_e.style.paddingLeft=se.closeButtonPaddingX,_e.style.paddingRight=se.closeButtonPaddingX):(_e.style.paddingLeft="",_e.style.paddingRight=""),se.closeButtonPaddingY?(_e.style.paddingTop=se.closeButtonPaddingY,_e.style.paddingBottom=se.closeButtonPaddingY):(_e.style.paddingTop="",_e.style.paddingBottom=""),Jc(_e,se.closeButtonIconName??"x",{iconSize:Le()?ig:void 0,iconText:se.closeButtonIconText??"\xD7"});let Zt=se.closeButtonTooltipText??"Close chat",co=se.closeButtonShowTooltip??!0;_e.setAttribute("aria-label",Zt),Ge&&Qt({anchor:_e,trigger:Ge,text:()=>_e?.getAttribute("aria-label")??Zt,enabled:co})}let{clearChatButton:He,clearChatButtonWrapper:De}=Be;if(He){let Y=se.clearChat??{},je=Y.enabled??!0,Ge=o.layout?.header?.showClearChat,tt=Ge!==void 0?Ge:je,yt=Y.placement??"inline";if(De){De.style.display=tt?"":"none";let{closeButtonWrapper:Zt}=Be;!Le()&&Zt&&!Zt.classList.contains("persona-absolute")&&(tt?Zt.classList.remove("persona-ml-auto"):Zt.classList.add("persona-ml-auto"));let co=yt==="top-right",Kt=De.classList.contains("persona-absolute");if(!Le()&&co!==Kt&&tt){if(De.remove(),co){De.className="persona-absolute persona-top-4 persona-z-50",De.style.right="48px";let Ao=Ki??de;Ao.style.position="relative",Ao.appendChild(De)}else{De.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",De.style.right="";let Ao=Be.closeButtonWrapper;Ae&&Ao&&Ao.parentElement===Ae?Ae.insertBefore(De,Ao):Ae&&Ae.appendChild(De)}let Gt=Be.closeButtonWrapper;Gt&&!Gt.classList.contains("persona-absolute")&&(co?Gt.classList.add("persona-ml-auto"):Gt.classList.remove("persona-ml-auto"))}}if(tt){if(!Le()){let Gt=Y.size??"";He.style.height=Gt,He.style.width=Gt,He.style.minWidth=Gt,He.style.minHeight=Gt}let Zt=Y.iconColor??"";if(He.style.color=Zt||gn.actionIconColor,Jc(He,Y.iconName??"refresh-cw",{iconSize:Le()?ag:void 0}),Y.backgroundColor?(He.style.backgroundColor=Y.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let Gt=Y.borderWidth||"0px",Ao=Y.borderColor||"transparent";He.style.border=`${Gt} solid ${Ao}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");Y.borderRadius?(He.style.borderRadius=Y.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),Y.paddingX?(He.style.paddingLeft=Y.paddingX,He.style.paddingRight=Y.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),Y.paddingY?(He.style.paddingTop=Y.paddingY,He.style.paddingBottom=Y.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let co=Y.tooltipText??"Clear chat",Kt=Y.showTooltip??!0;He.setAttribute("aria-label",co),De&&Qt({anchor:He,trigger:De,text:()=>He?.getAttribute("aria-label")??co,enabled:Kt})}}let Ce=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Eg],sn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[qa.message,qa.messageAndClick];he=Tg({parsers:Ce,handlers:sn,getSessionMetadata:ae,updateSessionMetadata:re,emit:w.emit,documentRef:typeof document<"u"?document:null}),vt=PC(o,he,Po),jw(),A.updateConfig(o),(o.features?.history?.enabled===!0!==pe||o.features?.history?.provider!==Xe||o.getIdentityProof!==ct||o.clientToken!==ut)&&(xn({restoreFocus:!1}),mm()),yr(),Fl(),qn(ke,A.getMessages(),vt),Ts(),Al(),qw(),$i(A.isStreaming()),Vt!==o.contextMentions&&gh();let Cr=o.voiceRecognition?.enabled===!0,An=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Mn=Tn(o.voiceRecognition?.provider);if(Cr&&(An||Mn))if(!ne||!Ln){let Y=li(o);if(Y){ne=Y.button,Ln=Y.wrapper;let je=uo&&uo.parentElement===Ka?uo:null;Ka?Ka.insertBefore(Ln,je):eo?.appendChild(Ln),et&&(et.micButton=ne),et?.addListener(ne,"click",Yp),ne.disabled=vo()||A.isStreaming()&&!Jd()}}else{let Y=o.voiceRecognition??{},je=o.sendButton??{},Ge=Y.iconName??"mic",tt=Y.iconSize,yt=parseFloat(tt??"")||pn;ne.classList.add(Nn),ne.classList.toggle(po,!tt),ne.style.width=tt??"",ne.style.height=tt??"",ne.style.minWidth=tt??"",ne.style.minHeight=tt??"";let Zt=Y.iconColor??je.textColor;ne.innerHTML="";let co=ge(Ge,yt,Zt||"currentColor",1.5);co?ne.appendChild(co):ne.textContent="\u{1F3A4}";let Kt=Y.backgroundColor??je.backgroundColor;Kt?ne.style.backgroundColor=Kt:ne.style.backgroundColor="",Zt?ne.style.color=Zt:ne.style.color="var(--persona-text, #111827)",Y.borderWidth?(ne.style.borderWidth=Y.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),Y.borderColor?ne.style.borderColor=Y.borderColor:ne.style.borderColor="",Y.paddingX?(ne.style.paddingLeft=Y.paddingX,ne.style.paddingRight=Y.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),Y.paddingY?(ne.style.paddingTop=Y.paddingY,ne.style.paddingBottom=Y.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let Gt=Y.tooltipText??"Start voice recognition",Ao=Y.showTooltip??!1;ne.setAttribute("aria-label",Gt),Ln&&Qt({anchor:ne,trigger:Ln,text:()=>ne?.getAttribute("aria-label")??Gt,enabled:Ao}),Ln.style.display="",ne.disabled=vo()||A.isStreaming()&&!Jd()}else ne&&Ln&&(Ln.style.display="none",Tn(o.voiceRecognition?.provider)?A.isVoiceActive()&&A.toggleVoice():So&&br());if(o.attachments?.enabled===!0){if(!bn||!bt){let Y=o.attachments??{};vn||(vn=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),vn.style.display="none",(le.parentElement??eo).insertBefore(vn,le)),ft||(ft=document.createElement("input"),ft.type="file",ft.accept=(Y.allowedTypes??Yo).join(","),ft.multiple=(Y.maxFiles??4)>1,ft.style.display="none",ft.setAttribute("aria-label","Attach files"),(le.parentElement??eo).insertBefore(ft,le)),bn=k("div","persona-send-button-wrapper"),bt=k("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Nn} ${po}`),bt.type="button",bt.setAttribute("aria-label",Y.buttonTooltipText??"Attach file");let je=Y.buttonIconName??"paperclip";bt.style.fontSize="18px",bt.style.lineHeight="1";let Ge=ge(je,pn,"currentColor",1.5);Ge?bt.appendChild(Ge):bt.textContent="\u{1F4CE}",bt.addEventListener("click",yt=>{yt.preventDefault(),ft?.click()}),bn.appendChild(bt);let tt=Y.buttonTooltipText??"Attach file";Qt({anchor:bt,trigger:bn,text:()=>bt?.getAttribute("aria-label")??tt}),Sd?Sd.append(bn):eo.appendChild(bn),et&&(et.attachmentButton=bt,et.attachmentInput=ft??void 0,et.attachmentPreviews=vn??void 0),!Ye&&ft&&vn&&(Ye=Ma.fromConfig(Y,Kg),Ye.setPreviewsContainer(vn),et?.addListener(ft,"change",async()=>{Ye&&ft?.files&&(await Ye.handleFileSelect(ft.files),ft.value="")}))}else{bn.style.display="";let Y=o.attachments??{};ft&&(ft.accept=(Y.allowedTypes??Yo).join(","),ft.multiple=(Y.maxFiles??4)>1),Ye&&Ye.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles,adapter:Y.adapter})}if(de.querySelector(".persona-attachment-drop-overlay")?.remove(),de.appendChild(IC(o.attachments?.dropOverlay)),bt){let Y=o.attachments??{},je=Y.buttonTooltipText??"Attach file";bt.setAttribute("aria-label",je),bt.textContent="";let Ge=ge(Y.buttonIconName??"paperclip",pn,"currentColor",1.5);Ge?bt.appendChild(Ge):bt.textContent="\u{1F4CE}",bn&&Qt({anchor:bt,trigger:bn,text:()=>bt?.getAttribute("aria-label")??je})}}else bn&&(bn.style.display="none"),Ye&&Ye.clearAttachments(),de.querySelector(".persona-attachment-drop-overlay")?.remove();let We=o.sendButton??{},Go=We.useIcon??!1,It=We.iconText??"\u2191",En=We.iconName,la=We.tooltipText??"Send message",ix=We.showTooltip??!1,ca=We.size,ax=parseFloat(ca??"")||Hu,oc=We.backgroundColor,da=We.textColor;if(Go){if(xe.style.width=ca??"",xe.style.height=ca??"",xe.style.minWidth=ca??"",xe.style.minHeight=ca??"",xe.style.fontSize="18px",xe.style.lineHeight="1",da?xe.style.color=da:xe.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!A.isStreaming())if(xe.innerHTML="",En){let Y=parseFloat(We.iconSize??"")||Math.round(ax*.5),je=da?.trim()||"currentColor",Ge=We.iconStrokeWidth??2,tt=ge(En,Y,je,Ge),yt=ge(We.stopIconName??"square",Y,je,Ge);tt&&yt?xe.appendChild(Ru(tt,yt)):tt?xe.appendChild(tt):xe.textContent=It}else xe.textContent=It;xe.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Nn}`,oc?(xe.style.backgroundColor=oc,xe.classList.remove("persona-bg-persona-primary")):(xe.style.backgroundColor="",xe.classList.add("persona-bg-persona-primary"))}else xe.textContent=o.copy?.sendButtonLabel??"Send",xe.style.width="",xe.style.height="",xe.style.minWidth="",xe.style.minHeight="",xe.style.fontSize="",xe.style.lineHeight="",xe.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?(xe.style.backgroundColor=oc,xe.classList.remove("persona-bg-persona-accent")):xe.classList.add("persona-bg-persona-accent"),da?xe.style.color=da:xe.classList.add("persona-text-white");We.borderWidth?(xe.style.borderWidth=We.borderWidth,xe.style.borderStyle="solid"):(xe.style.borderWidth="",xe.style.borderStyle=""),We.borderColor?xe.style.borderColor=We.borderColor:xe.style.borderColor="",We.paddingX?(xe.style.paddingLeft=We.paddingX,xe.style.paddingRight=We.paddingX):(xe.style.paddingLeft="",xe.style.paddingRight=""),We.paddingY?(xe.style.paddingTop=We.paddingY,xe.style.paddingBottom=We.paddingY):(xe.style.paddingTop="",xe.style.paddingBottom=""),A.isStreaming()||xe.setAttribute("aria-label",la),Sl(),uo&&Qt({anchor:xe,trigger:uo,text:()=>xe.getAttribute("aria-label")??la,enabled:ix}),cf();let xh=qc(be.getState().activeModeIds,o.composer?.modes);be.setActiveModeIds(xh),vs().length>0!==!!Ro&&Rd(),Ro?.render(xh,vs());for(let Y of[...Cs.keys()])$c(Y,o.composer?.modeGroups)||Cs.delete(Y);Cs.forEach(Y=>Y.repaint()),ir?.repaint(),mo?.resolve();let rc=kr(o,Le());if(Fd(),rc){ke.style.maxWidth=rc,ke.style.marginLeft="auto",ke.style.marginRight="auto",ke.style.width="100%",In.style.maxWidth=rc,In.style.marginLeft="auto",In.style.marginRight="auto",In.style.width="100%";for(let Y of[eo,or,vn,rt])Y&&(Y.style.maxWidth=rc,Y.style.marginLeft="auto",Y.style.marginRight="auto",Y.style.width="100%")}else{ke.style.maxWidth="",ke.style.marginLeft="",ke.style.marginRight="",ke.style.width="",In.style.maxWidth="",In.style.marginLeft="",In.style.marginRight="",In.style.width="";for(let Y of[eo,or,vn,rt])Y&&(Y.style.maxWidth="",Y.style.marginLeft="",Y.style.marginRight="",Y.style.width="")}let wr=o.statusIndicator??{},lx=wr.visible??!0;if(rt.style.display=lx?"":"none",A){let Y=A.getStatus();Va(rt,(Ge=>Ge==="idle"?wr.idleText??Nt.idle:Ge==="connecting"?wr.connectingText??Nt.connecting:Ge==="connected"?wr.connectedText??Nt.connected:Ge==="error"?wr.errorText??Nt.error:Nt[Ge])(Y),wr,Y)}rt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let cx=wr.align==="left"?"persona-text-left":wr.align==="center"?"persona-text-center":"persona-text-right";rt.classList.add(cx),Hd(),ep(),to(),vd()},open(){Fe()&&pt(!0,"api")},close(){Fe()&&pt(!1,"api")},toggle(){Fe()&&pt(!ve,"api")},reconnect(){A.reconnectNow()},clearChat(){Wo=!1,A.clearMessages(),Wt.clear(),wn();try{localStorage.removeItem(Ci),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ci}`)}catch(a){console.error("[AgentWidget] Failed to clear default localStorage:",a)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ci)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(a){console.error("[AgentWidget] Failed to clear custom localStorage:",a)}let r=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(r),K?.clear&&fl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),Z={},he.syncFromMetadata(),Ye?.clearAttachments(),hl(),ws(void 0),fo(void 0),$r(),Re?.clear(),ot?.reset(),gt?.update()},setMessage(r){return!le||A.isStreaming()||vo()?!1:(!ve&&Fe()&&pt(!0,"system"),le.value=r,le.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(r){if(A.isStreaming()||Qr())return!1;let a=r?.trim()||le.value.trim();return a?(!ve&&Fe()&&pt(!0,"system"),le.value="",le.style.height="auto",go(),Yl(a,{consumeDraft:!1}),!0):!1},getComposerState(){return be.getState()},setQuote(r){let a=r?.text?.trim();a&&fo({...r,text:a})},clearQuote(){fo(void 0)},startVoiceRecognition(){return A.isStreaming()?!1:Tn(o.voiceRecognition?.provider)?(A.isVoiceActive()||A.isBargeInActive()||(!ve&&Fe()&&pt(!0,"system"),ze.manuallyDeactivated=!1,ro(),A.toggleVoice().then(()=>{ze.active=A.isVoiceActive(),_o("user"),A.isVoiceActive()&&Gs()})),!0):So?!0:Jm()?(!ve&&Fe()&&pt(!0,"system"),ze.manuallyDeactivated=!1,ro(),Zl("user"),!0):!1},stopVoiceRecognition(){return Tn(o.voiceRecognition?.provider)?!A.isVoiceActive()&&!A.isBargeInActive()?!1:((A.isBargeInActive()?A.deactivateBargeIn():A.toggleVoice()).then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,ro(),_o("user"),Vo()}),!0):So?(ze.manuallyDeactivated=!0,ro(),br("user"),!0):!1},injectMessage(r){return!ve&&Fe()&&pt(!0,"system"),A.injectMessage(r)},injectAssistantMessage(r){!ve&&Fe()&&pt(!0,"system");let a=A.injectAssistantMessage(r);return ln&&(ln=!1,Zn&&(clearTimeout(Zn),Zn=null),setTimeout(()=>{A&&!A.isStreaming()&&A.continueConversation()},100)),a},injectUserMessage(r){return!ve&&Fe()&&pt(!0,"system"),A.injectUserMessage(r)},injectSystemMessage(r){return!ve&&Fe()&&pt(!0,"system"),A.injectSystemMessage(r)},injectMessageBatch(r){return!ve&&Fe()&&pt(!0,"system"),A.injectMessageBatch(r)},injectComponentDirective(r){return!ve&&Fe()&&pt(!0,"system"),A.injectComponentDirective(r)},injectTestMessage(r){!ve&&Fe()&&pt(!0,"system"),A.injectTestEvent(r)},async connectStream(r,a){return A.connectStream(r,a)},__pushEventStreamEvent(r){C&&(ja(),bd(r.type,r.payload))},showEventStream(){C&&Ld()},hideEventStream(){zt&&Ss()},isEventStreamVisible(){return zt},listConversations(r){return A.listConversations(r)},getActiveConversationId(){return A.getActiveConversationId()},openConversation(r,a){return Dp(r,{focusComposer:a?.focus===!0})},startNewConversation(r){return Op({focusComposer:r?.focus===!0})},deleteConversation(r){return Um(r)},renameConversation(r,a){return _p(r,{title:a})},setConversationStarred(r,a){return _p(r,{starred:a})},clearConversationHistory(r){return $m(r)},resetHistoryIdentity(){return qm()},async getVisitorToken(){let r=zn;if(!r)return null;let a=await r.get();return r===zn?a:null},getHistoryIdentityStatus(){return Dn?Dn.getIdentityStatus():vp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(r){return ea({...r?.returnSurface?{returnSurface:r.returnSurface}:{},...r?.focus!==void 0?{focus:r.focus}:{}})},hideHistory(r){xn(r?.restoreFocus!==void 0?{restoreFocus:r.restoreFocus}:void 0)},isHistoryVisible(){return Ct},showArtifacts(){mn(o)&&(Wo=!1,As=!0,oo(),qe?.setMobileOpen(!0))},hideArtifacts(){mn(o)&&(Wo=!0,oo())},upsertArtifact(r){return mn(o)?(Sr(o.features?.artifacts,{artifactType:r.artifactType,...r.artifactType==="markdown"&&r.file?{file:r.file}:{},...r.presentation?{presentation:r.presentation}:{}})==="panel"&&(Wo=!1,As=!0),A.upsertArtifact(r)):null},selectArtifact(r){mn(o)&&A.selectArtifact(r)},clearArtifacts(){mn(o)&&A.clearArtifacts()},getArtifacts(){return A?.getArtifacts()??[]},getSelectedArtifactId(){return A?.getSelectedArtifactId()??null},focusInput(){return ce&&!ve&&!Le()||!le?!1:(le.focus(),!0)},async resolveApproval(r,a,p){let y=A.getMessages().find(b=>b.variant==="approval"&&b.approval?.id===r);if(!y?.approval)throw new Error(`Approval not found: ${r}`);if(y.approval.toolType==="webmcp"){A.resolveWebMcpApproval(y.id,a);return}return A.resolveApproval(y.approval,a,p)},setFollowUpSuggestions(r){fw(r)},clearFollowUpSuggestions(){Of()},getMessages(){return A.getMessages()},getStatus(){return A.getStatus()},getPersistentMetadata(){return{...Z}},updatePersistentMetadata(r){re(r)},on(r,a){return w.on(r,a)},off(r,a){w.off(r,a)},isOpen(){return Fe()&&ve},isVoiceActive(){return ze.active},toggleReadAloud(r){A.toggleReadAloud(r)},stopReadAloud(){A.stopSpeaking()},getReadAloudState(r){return A.getReadAloudState(r)},onReadAloudChange(r){return A.onReadAloudChange(r)},getState(){return{open:Fe()&&ve,launcherEnabled:ce,voiceActive:ze.active,streaming:A.isStreaming()}},showCSATFeedback(r){!ve&&Fe()&&pt(!0,"system");let a=ke.querySelector(".persona-feedback-container");a&&a.remove();let p=xC({onSubmit:async(f,y)=>{A.isClientTokenMode()&&await A.submitCSATFeedback(f,y),r?.onSubmit?.(f,y)},onDismiss:r?.onDismiss,...r});ke.appendChild(p),p.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(r){!ve&&Fe()&&pt(!0,"system");let a=ke.querySelector(".persona-feedback-container");a&&a.remove();let p=AC({onSubmit:async(f,y)=>{A.isClientTokenMode()&&await A.submitNPSFeedback(f,y),r?.onSubmit?.(f,y)},onDismiss:r?.onDismiss,...r});ke.appendChild(p),p.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(r,a){return A.submitCSATFeedback(r,a)},async submitNPSFeedback(r,a){return A.submitNPSFeedback(r,a)},destroy(){up(),Jr!=null&&(clearInterval(Jr),Jr=null),fe.forEach(r=>r()),Ke.remove(),jt?.remove(),St?.destroy(),dn?.remove(),_r&&_e.removeEventListener("click",_r)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let r=window.AgentWidgetBrowser,a={controller:xt,getMessages:xt.getMessages,getStatus:xt.getStatus,getMetadata:xt.getPersistentMetadata,updateMetadata:xt.updatePersistentMetadata,clearHistory:()=>xt.clearChat(),setVoiceActive:p=>p?xt.startVoiceRecognition():xt.stopVoiceRecognition()};window.AgentWidgetBrowser=a,fe.push(()=>{window.AgentWidgetBrowser===a&&(window.AgentWidgetBrowser=r)})}if(typeof window<"u"){let r=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),a=z=>{let X=z.detail;(!X?.instanceId||X.instanceId===r)&&xt.focusInput()};if(window.addEventListener("persona:focusInput",a),fe.push(()=>{window.removeEventListener("persona:focusInput",a)}),C){let z=oe=>{let pe=oe.detail;(!pe?.instanceId||pe.instanceId===r)&&xt.showEventStream()},X=oe=>{let pe=oe.detail;(!pe?.instanceId||pe.instanceId===r)&&xt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",X),fe.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",X)})}let p=z=>{let X=z.detail;(!X?.instanceId||X.instanceId===r)&&xt.showHistory()},f=z=>{let X=z.detail;(!X?.instanceId||X.instanceId===r)&&xt.hideHistory()};window.addEventListener("persona:showHistory",p),window.addEventListener("persona:hideHistory",f),fe.push(()=>{window.removeEventListener("persona:showHistory",p),window.removeEventListener("persona:hideHistory",f)});let y=z=>{let X=z.detail;(!X?.instanceId||X.instanceId===r)&&xt.showArtifacts()},b=z=>{let X=z.detail;(!X?.instanceId||X.instanceId===r)&&xt.hideArtifacts()},D=z=>{let X=z.detail;X?.instanceId&&X.instanceId!==r||X?.artifact&&xt.upsertArtifact(X.artifact)},q=z=>{let X=z.detail;X?.instanceId&&X.instanceId!==r||typeof X?.id=="string"&&xt.selectArtifact(X.id)},U=z=>{let X=z.detail;(!X?.instanceId||X.instanceId===r)&&xt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",q),window.addEventListener("persona:clearArtifacts",U),fe.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",q),window.removeEventListener("persona:clearArtifacts",U)})}let Qn=AT(o.persistState);if(Qn&&Fe()){let r=MT(Qn.storage),a=`${Qn.keyPrefix}widget-open`,p=`${Qn.keyPrefix}widget-voice`,f=`${Qn.keyPrefix}widget-voice-mode`;if(r){let y=Qn.persist?.openState&&r.getItem(a)==="true",b=Qn.persist?.voiceState&&r.getItem(p)==="true",D=Qn.persist?.voiceState&&r.getItem(f)==="true";if(y&&(St?.setPanelOpen(!0,"auto"),setTimeout(()=>{xt.open(),setTimeout(()=>{if(b||D)xt.startVoiceRecognition();else if(Qn.persist?.focusInput){let q=t.querySelector("textarea");q&&q.focus()}},100)},0)),Qn.persist?.openState&&(w.on("widget:opened",()=>{r.setItem(a,"true")}),w.on("widget:closed",()=>{r.setItem(a,"false")})),Qn.persist?.voiceState&&(w.on("voice:state",q=>{r.setItem(p,q.active?"true":"false")}),w.on("user:message",q=>{r.setItem(f,q.viaVoice?"true":"false")})),Qn.clearOnChatClear){let q=()=>{r.removeItem(a),r.removeItem(p),r.removeItem(f)},U=()=>q();window.addEventListener("persona:clear-chat",U),fe.push(()=>{window.removeEventListener("persona:clear-chat",U)})}}}if(J&&Fe()&&(St?.setPanelOpen(!0,"auto"),setTimeout(()=>{xt.open()},0)),Ws(),!mw){let r=sc(()=>{A&&(qr++,Wt.clear(),qn(ke,A.getMessages(),vt))});fe.push(r)}M=()=>{A&&(qr++,Wt.clear(),qn(ke,A.getMessages(),vt))},A.getMessages().length>0&&wl(),x=()=>{A&&(qr++,Wt.clear(),qn(ke,A.getMessages(),vt))};let rx=Fh(()=>{A&&(qr++,Wt.clear(),qn(ke,A.getMessages(),vt))});fe.push(rx);let sx=yg(()=>{A&&(qr++,Wt.clear(),qn(ke,A.getMessages(),vt),er()?.updateInlineArtifactBlocks(ke,$n.artifacts,{suppressTransition:!0}),oo())});return fe.push(sx),xt};var HC=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,e*parseFloat(s[1])/100):420},kT=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},PT=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},IT=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let s=o.offsetHeight>0;o.style.height="100%";let i=o.offsetHeight>0;o.remove(),!(!s||i)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.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 ${e.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.")},RC=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},Dg=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},WC=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Dg(t)},Rg=t=>{t.style.transition=""},Wg=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Bg=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},yd=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},LT=(t,e,n,o,s)=>{s?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},HT=(t,e,n,o,s,i)=>{let l=i?e:t;s==="left"?l.firstElementChild!==o&&l.replaceChildren(o,n):l.lastElementChild!==o&&l.replaceChildren(n,o)},RT=t=>{let e=di(t),n=e.components?.panel,o=(s,i)=>s==null||s===""?i:un(e,s)??s;return{inset:o(n?.inset,zc),canvasBackground:o(n?.canvasBackground,jc)}},BC=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},WT=(t,e,n,o,s,i,l,c)=>{let d=Jn(i),u=d.reveal==="push",g=c!=null,m=c?.inset??"",v=c?.canvasBackground??"";LT(t,e,n,o,u),HT(t,e,n,o,d.side,u),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=d.side,t.dataset.personaDockOpen=l?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.minWidth="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let h=t.ownerDocument.defaultView,T=i?.launcher?.mobileFullscreen??!0,M=i?.launcher?.mobileBreakpoint??640,E=h!=null?h.innerWidth<=M:!1;if(T&&E&&l){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Wg(e),Rg(o),WC(o),Bg(n),yd(s,o),BC(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(i?.launcher?.zIndex??an),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",u&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),WC(o),kT(o,d.maxHeight),BC(o,g&&l,m,v),d.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Wg(e),Rg(o),Bg(n),yd(s,o);let P=d.animate?"transform 180ms ease":"none",N=d.side==="right"?"translateX(100%)":"translateX(-100%)",x=l?"translateX(0)":N;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=P,o.style.transform=x,o.style.pointerEvents=l?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Rg(o),Dg(o),yd(s,o);let P=HC(d.width,t.clientWidth),N=Math.max(0,t.clientWidth),x=d.animate?"margin-left 180ms ease":"none",R=d.side==="right"?l?-P:0:l?0:-P;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${N+P}px`,e.style.transition=x,e.style.marginLeft=`${R}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${N}px`,n.style.maxWidth=`${N}px`,n.style.minWidth=`${N}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=l?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",Wg(e),Dg(o),Bg(n),yd(s,o);let P=d.reveal==="emerge";P?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let N=l?d.width:"0px",x=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${g?", padding 180ms ease":""}`:"none",R=!l;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${N}`,o.style.width=N,o.style.maxWidth=N,o.style.minWidth=N,o.style.minHeight="0",PT(o,d.maxHeight),o.style.overflow=P||R?"hidden":"visible",o.style.transition=x,P){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let w=g?`calc(${HC(d.width,t.clientWidth)}px - (2 * ${m}))`:d.width;s.style.width=w,s.style.minWidth=w,s.style.maxWidth=w,s.style.boxSizing="border-box"}}},BT=(t,e)=>{let n=t.ownerDocument.createElement("div");return RC(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){RC(n,o)},destroy(){n.remove()}}},DT=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let s=t.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let i=t.nextSibling,l=n.createElement("div"),c=n.createElement("div"),d=n.createElement("div"),u=n.createElement("aside"),g=n.createElement("div"),m=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;c.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",u.appendChild(g),o.insertBefore(l,t),d.appendChild(t);let v=null,h=()=>{v?.disconnect(),v=null},T=null,M=()=>{T=e?.launcher?.detachedPanel===!0?RT(e):null};M();let E=()=>{WT(l,c,d,u,g,e,m,T)},I=null,P=()=>{I?.(),I=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(I=Vc(()=>{M(),E()}))},N=()=>{h(),Jn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(v=new ResizeObserver(()=>{E()}),v.observe(l)))},x=!1,R=()=>{E(),N(),m&&!x&&l.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,IT(l,Jn(e)))},w=l.ownerDocument.defaultView,O=()=>{R()};return w?.addEventListener("resize",O),Jn(e).reveal==="push"?(c.appendChild(d),c.appendChild(u),l.appendChild(c)):(l.appendChild(d),l.appendChild(u)),R(),P(),{mode:"docked",host:g,shell:l,syncWidgetState(K){let ie=K.launcherEnabled?K.open:!0;m!==ie&&(m=ie,R())},updateConfig(K){e=K,(e?.launcher?.enabled??!0)===!1&&(m=!0),M(),R(),P()},destroy(){w?.removeEventListener("resize",O),I?.(),I=null,h(),o.isConnected&&(i&&i.parentNode===o?o.insertBefore(t,i):o.appendChild(t)),l.remove()}}},DC=(t,e)=>Lt(e)?DT(t,e):BT(t,e);var za={desktop:{w:1280,h:800},mobile:{w:390,h:844}},OC=.15,_C=1.5,Og="persona-preview-shell-theme",OT={load:()=>null,save:()=>{},clear:()=>{}},_T=["How do I get started?","Pricing & plans","Talk to support"];function _g(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function NT(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function NC(t){let e=NT(t);return`* { box-sizing: border-box; }
|
|
129
129
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
130
130
|
html { color-scheme: ${t}; }
|
|
131
131
|
body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
|
|
@@ -208,10 +208,10 @@ _Details: ${n.message}_`:o}var xu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
208
208
|
<body>
|
|
209
209
|
${n?i:s}
|
|
210
210
|
</body>
|
|
211
|
-
</html>`}var $T=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],qT=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function zT(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&qT(e)?[...$T(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function jT(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},s={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:_T:t.suggestionChips,initialMessages:zT(e,t,n),storageAdapter:OT};return e==="artifact"&&(s.features={...s.features,artifacts:{...s.features?.artifacts,enabled:!0}}),e==="messages"&&(s.features={...s.features,history:{presentation:"panel",...s.features?.history,enabled:!0}}),s}function VT(t,e){let n=t.theme?ci(t.theme,{validate:!1}):ci();return{...nt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Si(t,e){let n=t.scene??"conversation";return jT(VT(t,e),n,t.appendedMessages??[])}function $C(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Si(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Si(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Si(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Si(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Si(t,n),shellMode:n}]}function KT(t,e){let n={...e},o=[],s=[],i=null,l=!1,c=1,d=1,u=0;function g(){return n.device??"desktop"}function m(){return n.zoom??c}function
|
|
212
|
-
${
|
|
213
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
214
|
-
</div>`,S=
|
|
211
|
+
</html>`}var $T=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],qT=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function zT(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&qT(e)?[...$T(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function jT(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},s={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:_T:t.suggestionChips,initialMessages:zT(e,t,n),storageAdapter:OT};return e==="artifact"&&(s.features={...s.features,artifacts:{...s.features?.artifacts,enabled:!0}}),e==="messages"&&(s.features={...s.features,history:{presentation:"panel",...s.features?.history,enabled:!0}}),s}function VT(t,e){let n=t.theme?ci(t.theme,{validate:!1}):ci();return{...nt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Si(t,e){let n=t.scene??"conversation";return jT(VT(t,e),n,t.appendedMessages??[])}function $C(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Si(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Si(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Si(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Si(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Si(t,n),shellMode:n}]}function KT(t,e){let n={...e},o=[],s=[],i=null,l=!1,c=1,d=1,u=0;function g(){return n.device??"desktop"}function m(){return n.zoom??c}function v(){let P=getComputedStyle(t),N=parseFloat(P.paddingLeft)+parseFloat(P.paddingRight),x=parseFloat(P.paddingTop)+parseFloat(P.paddingBottom),R=40,w=(n.compareMode??"off")!=="off",O=(t.clientWidth-N-R)/(w?2:1),K=t.clientHeight-x-R;if(O<=0||K<=0)return 1;let ie=za[g()]??za.desktop;return Math.min(O/ie.w,K/ie.h,1)}function h(){c=v();let P=Math.max(OC,Math.min(_C,m()));d=P;let N=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let x of N){let R=x.dataset.device??"desktop",w=za[R]??za.desktop;x.style.width=`${w.w*P}px`,x.style.height=`${w.h*P}px`,R==="mobile"&&(x.style.borderRadius=`${32*P}px`);let O=x.querySelector("iframe");O&&(O.style.width=`${w.w}px`,O.style.height=`${w.h}px`,O.style.transformOrigin="top left",O.style.transition="none",O.style.transform=`scale(${P})`)}n.onScaleChange?.(P)}function T(){n.onBeforeDestroy?.();for(let P of o)P.destroy();for(let P of s)P();o=[],s=[]}function M(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function E(){if(l)return;T();let P=++u,N=$C(n),x=g(),R=(n.compareMode??"off")!=="off",w=(n.scene??"conversation")==="minimized",O=n.widgetCssPath??"/widget-dist/widget.css",K=n.buildSrcdoc??UC,ie=x==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",Z=$=>`<div class="${ie}" data-mount-id="${$.mountId}" data-device="${x}" data-shell-mode="${$.shellMode}">
|
|
212
|
+
${R?`<div class="preview-frame-meta"><span class="preview-frame-label">${_g($.label)}</span></div>`:""}
|
|
213
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${$.mountId}"></iframe>
|
|
214
|
+
</div>`,S=R?`<div class="preview-compare-grid">${N.map($=>`<div class="preview-compare-cell">${Z($)}</div>`).join("")}</div>`:`<div class="preview-single">${Z(N[0])}</div>`;n.morphContainer?n.morphContainer(t,S):t.innerHTML=S,h();let B=M(),W=0,H=B.length,J=()=>{if(l||P!==u)return;for(let ae of B){let re=ae.dataset.mountId;if(!re||!ae.contentDocument)continue;let ue=N.find(ye=>ye.mountId===re);if(!ue)continue;let Ee=()=>{},he=Lt(ue.config),ce=he?(()=>{let ye=ae.contentDocument?.getElementById(`preview-content-${re}`);if(!ye)return null;let F=DC(ye,ue.config),Te=ae.contentDocument.createElement("div");Te.id=re,Te.style.height="100%",Te.style.display="flex",Te.style.flexDirection="column",Te.style.flex="1",Te.style.minHeight="0",F.host.appendChild(Te);let Ue=()=>F.syncWidgetState(at.getState()),qt=Ee;return Ee=()=>{F.destroy(),qt()},Te.__syncDock=Ue,Te.__hostLayout=F,Te})():ae.contentDocument.getElementById(re);if(!ce)continue;let at=LC(ce,ue.config);if(o.push(at),he&&ce.__syncDock){let ye=ce.__syncDock,F=at.on("widget:opened",ye),Te=at.on("widget:closed",ye),Ue=Ee;Ee=()=>{F(),Te(),Ue()},ye()}s.push(Ee),w&&at.close()}let $=n.scene??"conversation";if($==="messages")for(let ae of o)ae.showHistory({focus:!1});if($==="artifact"||n.config?.features?.artifacts?.enabled)for(let ae of o)ae.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
215
215
|
|
|
216
216
|
This is a preview of the artifact sidebar.
|
|
217
217
|
|
|
@@ -219,4 +219,4 @@ This is a preview of the artifact sidebar.
|
|
|
219
219
|
|
|
220
220
|
- Markdown rendering
|
|
221
221
|
- Document toolbar
|
|
222
|
-
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:
|
|
222
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:B,controllers:[...o]})};for(let $ of B){let ae=$.dataset.mountId;if(!ae)continue;let re=N.find(ue=>ue.mountId===ae);re&&($.addEventListener("load",()=>{W++,W>=H&&J()},{once:!0}),$.srcdoc=K(ae,re.shellMode,Lt(re.config),O))}H===0&&J()}function I(){if(l)return;let P=$C(n);if(o.length!==P.length){E();return}if(P.some(x=>{let R=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${x.mountId}"]`);return!R||R.dataset.shellMode!==x.shellMode})){E();return}o.forEach((x,R)=>{x.update(P[R].config),(n.scene??"conversation")==="minimized"&&x.close()});for(let x of P){let R=t.querySelector(`iframe[data-mount-id="${x.mountId}"]`);R&&FC(R,x.shellMode)}n.onAfterUpdate?.({iframes:M(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(i=new ResizeObserver(()=>{l||h()}),i.observe(t)),E(),{update(P){if(l)return;let N=P.device!==void 0&&P.device!==n.device||P.scene!==void 0&&P.scene!==n.scene||P.compareMode!==void 0&&P.compareMode!==n.compareMode||P.widgetCssPath!==void 0&&P.widgetCssPath!==n.widgetCssPath;n={...n,...P},N?E():I()},destroy(){l||(l=!0,T(),i?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){l||(n={...n,zoom:void 0},h())},getIframes(){return M()},getScale(){return d},setZoom(P){l||(n={...n,zoom:P},h())}}}export{KT as createThemePreview};
|