@runtypelabs/persona 4.19.0 → 4.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/approval-ui.d.cts +77 -5
- package/dist/approval-ui.d.ts +77 -5
- package/dist/artifacts-ui.d.cts +77 -5
- package/dist/artifacts-ui.d.ts +77 -5
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +77 -5
- package/dist/context-mentions.d.ts +77 -5
- package/dist/event-stream-view.d.cts +77 -5
- package/dist/event-stream-view.d.ts +77 -5
- package/dist/forms-ui.d.cts +77 -5
- package/dist/forms-ui.d.ts +77 -5
- package/dist/index.cjs +50 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +78 -6
- package/dist/index.d.ts +78 -6
- package/dist/index.global.js +31 -31
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +50 -50
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js.map +1 -1
- package/dist/session-reconnect.d.cts +77 -5
- package/dist/session-reconnect.d.ts +77 -5
- package/dist/smart-dom-reader.d.cts +77 -5
- package/dist/smart-dom-reader.d.ts +77 -5
- package/dist/theme-editor-preview.cjs +49 -49
- package/dist/theme-editor-preview.d.cts +77 -5
- package/dist/theme-editor-preview.d.ts +77 -5
- package/dist/theme-editor-preview.js +28 -28
- package/dist/theme-editor.d.cts +77 -5
- package/dist/theme-editor.d.ts +77 -5
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +46 -5
- package/dist/theme-reference.d.ts +46 -5
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/components/composer-actions.ts +27 -1
- package/src/components/composer-model-picker.ts +4 -14
- package/src/components/composer-overflow-menu.ts +14 -0
- package/src/components/composer-parts.ts +20 -0
- package/src/index-core.ts +2 -0
- package/src/styles/widget-styles.test.ts +83 -1
- package/src/styles/widget.css +50 -14
- package/src/theme-reference.ts +1 -1
- package/src/types/theme.ts +47 -5
- package/src/types.ts +33 -0
- package/src/ui.composer-action-visibility.test.ts +202 -0
- package/src/ui.composer-models.test.ts +37 -0
- package/src/ui.composer-modes.test.ts +82 -0
- package/src/ui.composer-overflow.test.ts +78 -0
- package/src/utils/__snapshots__/tokens-parity.test.ts.snap +1633 -686
- package/src/utils/composer-modes.test.ts +33 -0
- package/src/utils/composer-modes.ts +19 -2
- package/src/utils/tokens-parity.test.ts +20 -0
- package/src/utils/tokens.test.ts +76 -0
- package/src/utils/tokens.ts +4 -4
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import{a as hc,b as
|
|
2
|
-
`),n=!1;for(let o=0;o<e.length-1;o++){let s=e[o],i=e[o+1];if(!
|
|
3
|
-
`):t};var Zh="var(--persona-md-table-scroll-fade, 24px)",ey=new WeakSet;function ny(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 ty(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":Zh),t.style.setProperty("--persona-fade-r",s<=1?"0px":Zh)}function tu(t){ey.has(t)||(ey.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&ty(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(ty)}var{setLoader:qT,load:ox}=Pt({fallbackImport:()=>import("./webmcp-runtime-P3CHZRHF.js")});var oy=ox;function Yn(t){return t==="card"?"collapsed":t}function Zs(t){return t.split(";",1)[0].trim().toLowerCase()}function rx(t,e){if(!t)return;let n=Object.entries(t);for(let[s,i]of n)if(Zs(s)===e)return{mode:Yn(i),selector:Zs(s)};let o=`${e.split("/",1)[0]}/*`;for(let[s,i]of n)if(Zs(s)===o)return{mode:Yn(i),selector:o}}function sx(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:Yn(o.files),matchedBy:{type:"files"}};let c=e.file.mimeType?Zs(e.file.mimeType):void 0,p=c?rx(o.files.byMediaType,c):void 0;if(c&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:c,selector:p.selector}};if(o.files.default)return{mode:Yn(o.files.default),matchedBy:{type:"files"}}}let s=o.byKind?.[e.artifactType];if(s)return{mode:Yn(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let i=o.byType?.[e.artifactType];if(i)return{mode:Yn(i),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let l=e.presentation?.preferredMode;return l?{mode:Yn(l),matchedBy:{type:"preferredMode"}}:o.default?{mode:Yn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function wr(t,e){return sx(t,e).mode}function ba(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 ix="agent_",ax="flow_";function ry(t){return t.startsWith(ix)?{kind:"agentId",agentId:t}:t.startsWith(ax)?{kind:"flowId",flowId:t}:null}function sy(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=ry(c);if(u)return u;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[l];if(!p)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:p(c).payload}}let s=ry(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 vc(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ei(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function iy(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}import{parse as lx,ARR as cx,OBJ as dx,STR as px}from"partial-json";var nu="ask_user_question",va=8,ti="data-persona-ask-sheet-for",ux="Other",gx="Other\u2026",ly="Type your own answer here",cy="Send",mx="Next",fx="Back",hx="Submit all",yx="Skip",bx=3,ou="data-ask-current-index",ru="data-ask-question-count",dy="data-ask-answers",su="data-ask-grouped",py="data-ask-layout",vx=t=>t.layout==="pills"?"pills":"rows",Cx=t=>t.getAttribute(py)==="pills"?"pills":"rows",ay=!1,uy=t=>t.replace(/["\\]/g,"\\$&"),ms=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===nu,iu=t=>t?.features?.askUserQuestion??{},ni=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=lx(s,px|dx|cx);if(i&&typeof i=="object")return{payload:i,complete:n}}catch{}return{payload:null,complete:n}},Ca=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>va&&!ay&&(ay=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${va}.`)),e.slice(0,va)},wx=t=>Ca(t)[0]??null,Sx=(t,e)=>Ca(t)[e]??null,xx=(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))},gy=(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},Ax=(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 p=gy(n,o,e);p&&i.appendChild(p)}else i.textContent=t.label,t.description&&(i.title=t.description);return i},Mx=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},Ex=(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,p=(Array.isArray(t?.options)?t.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(p.length===0&&!n){for(let g=0;g<bx;g++)i.appendChild(Mx(o));return i}if(p.forEach((g,f)=>{i.appendChild(Ax(g,f,o,l))}),t?.allowFreeText!==!1){let g=o==="rows"?ux:gx;if(o==="rows"){let f=k("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(p.length)),f.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??ly,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",e.freeTextLabel??g),v.appendChild(h),f.appendChild(v);let M=gy(o,l,p.length);M&&f.appendChild(M),i.appendChild(f)}else{let f=k("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=e.freeTextLabel??g,i.appendChild(f)}}return i},my=(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??ly,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??cy,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Tx=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??cy,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},kx=(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??fx,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??yx,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 p=t===e-1;return c.textContent=p?n.submitAllLabel??hx:n.nextLabel??mx,c.setAttribute("data-ask-user-action",p?"submit-all":"next"),c.disabled=!0,i.appendChild(c),o.appendChild(i),o},fs=t=>{let e=t.getAttribute(dy);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},fy=(t,e)=>{t.setAttribute(dy,JSON.stringify(e))},Xn=t=>{let e=Number(t.getAttribute(ou)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Px=(t,e)=>{t.setAttribute(ou,String(Math.max(0,Math.floor(e))))},oi=t=>{let e=Number(t.getAttribute(ru)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Sr=t=>t.getAttribute(su)==="true",Ix=(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},Lx=(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)))},Cc=(t,e)=>{let{payload:n}=ni(e),o=Ca(n),s=fs(t),i={},l=new Set;return o.forEach((c,p)=>{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,p)&&(i[u]=s[p]))}),i},hy=t=>{let e=fs(t),n=Xn(t),o=e[n],s=new Set;typeof o=="string"?s.add(o):Array.isArray(o)&&o.forEach(p=>s.add(p));let i=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');i.forEach(p=>{let u=p.getAttribute("data-option-label")??"",g=s.has(u);p.setAttribute("aria-pressed",g?"true":"false"),p.classList.toggle("persona-ask-pill-selected",g)});let l=new Set(Array.from(i).map(p=>p.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="")},yy=t=>{if(!Sr(t))return;let e=fs(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}},au=(t,e,n)=>{let o=iu(n),s=Cx(t),{payload:i,complete:l}=ni(e),c=Sr(t),p=Xn(t),u=oi(t),g=c?Sx(i,p):wx(i),f=!!g?.multiSelect,v=t.querySelector('[data-ask-step-inline="true"]');v&&(v.textContent=c?`${p+1}/${u}`:"");let h=t.querySelector('[data-ask-stepper="true"]');h&&h.remove();let M=t.querySelector('[data-ask-question="true"]');if(M){let P=typeof g?.question=="string"?g.question:"";M.textContent=P,M.classList.toggle("persona-ask-question-skeleton",!P&&!l)}let A=t.querySelector('[data-ask-pill-list="true"]');if(A){let P=Ex(g,o,l,s);A.replaceWith(P)}if(s!=="rows"){let P=t.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(my(o,s))}let T=t.querySelector('[data-ask-multi-actions="true"]');!c&&f&&!T?t.appendChild(Tx(o)):(!f||c)&&T&&T.remove(),t.setAttribute("data-multi-select",f?"true":"false");let F=t.querySelector('[data-ask-nav-row="true"]');if(c){let P=kx(p,u,o);F?F.replaceWith(P):t.appendChild(P)}else F&&F.remove();hy(t),yy(t)},Hx=(t,e,n)=>{let o=iu(e),s=vx(o),i=t.toolCall.id,l=Ca(n),c=Math.max(1,l.length),p=c>1,u=Ix(t,l),g=p?Lx(t,c):0,f=k("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(ti,i),f.setAttribute("data-tool-call-id",i),f.setAttribute("data-message-id",t.id),f.setAttribute(ru,String(c)),f.setAttribute(ou,String(g)),f.setAttribute(su,p?"true":"false"),f.setAttribute(py,s),fy(f,u),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),xx(f,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 M=k("span","persona-ask-sheet-step-inline");M.setAttribute("data-ask-step-inline","true"),M.textContent="",v.appendChild(M),f.appendChild(v);let T=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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),s!=="rows"&&f.appendChild(my(o,s)),au(f,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Rx=(t,e,n)=>{let{payload:o}=ni(e),s=Math.max(1,Ca(o).length);s>oi(t)&&(t.setAttribute(ru,String(s)),s>1&&!Sr(t)&&t.setAttribute(su,"true")),au(t,e,n)};var wc=(t,e,n)=>{if(!n||!ms(t)||iu(e).enabled===!1)return;let s=t.toolCall.id;n.querySelectorAll(`[${ti}]`).forEach(u=>{u.getAttribute(ti)!==s&&u.remove()});let l=n.querySelector(`[${ti}="${uy(s)}"]`);if(l){Rx(l,t,e);return}let{payload:c}=ni(t),p=Hx(t,e,c);n.appendChild(p)},ri=(t,e)=>{if(!t)return;let n=e?`[${ti}="${uy(e)}"]`:`[${ti}]`;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)})},lu=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),xr=(t,e)=>{let n=fs(t),o=Xn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,fy(t,n),hy(t),yy(t)},Sc=(t,e,n,o)=>{let s=oi(t),i=Math.max(0,Math.min(s-1,o));Px(t,i),au(t,e,n)};var Ar="suggest_replies";var Wx={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},vy={name:Ar,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:Wx,origin:"sdk",annotations:{readOnlyHint:!0}},Cy=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),wa=t=>t.variant==="tool"&&t.toolCall?.name===Ar,Bx=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},wy=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!wa(n))continue;let o=Bx(n.toolCall?.args);return o.length>0?o:null}return null},by=new Set,_x=(t,e,n)=>{let o=`${t}:${e}:${n}`;by.has(o)||(by.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Mr=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=l=>{let c=e?.[l],p=n?.[l];c===void 0||p===void 0||c!==p&&_x(l,p,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 Ox={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:va,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},Dx={name:nu,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:Ox,origin:"sdk",annotations:{readOnlyHint:!0}},xc=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(Dx),Mr(t).expose&&e.push(vy),e};var Sy="4.19.0";var si=Sy;var ii="[Image]";function xy(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function Ac(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Eo(t){return{type:"text",text:t}}function Ay(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var My=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Fx=["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"],Qo=[...My,...Fx];function Ux(t){return My.includes(t)||t.startsWith("image/")}function Mc(t){return Ux(t.type)}function Ey(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function Ty(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;Mc(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 ky(t,e=Qo,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 $x(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Py(t,e){let n=$x(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 qx=["user","assistant","system"],zx=0;function Iy(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function Ec(t){return typeof t=="string"?t:void 0}function jx(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?Eo(e.text):null;case"image":return typeof e.image=="string"?Ay(e.image,{mimeType:Ec(e.mimeType),alt:Ec(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?Ey(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...Ec(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...Ec(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function Vx(t,e){let n=Iy(e),o=t.map(l=>Iy(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 p=c-i+1,u=i>0?s[i-1]:null,g=c+1<o.length?o[c+1]:null,f=g!==null&&n!==null?Math.min(g,n):g??n;for(let v=0;v<p;v+=1)s[i+v]=f!==null?f-(p-v):u!==null?u+v+1:zx+v;i=c+1}return s.map(l=>new Date(l).toISOString())}function Ly(t,e){let n=Vx(t,e?.beforeCreatedAt),o=[];return t.forEach((s,i)=>{if(typeof s?.id!="string"||s.id===""||!qx.includes(s.role))return;let l=s.role,c=n[i];if(s.displayAvailable===!1){let p={historyDisplayUnavailable:!0};o.push({id:s.id,role:l,content:"",createdAt:c,agentMetadata:p});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 p=s.content.map(jx).filter(g=>g!==null),u=xy(p);o.push({id:s.id,role:l,content:u||(Ac(p)?ii:""),createdAt:c,...p.length>0&&{contentParts:p}});return}o.push({id:s.id,role:l,content:"",createdAt:c})}),o}function Sa(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 xa(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,p=s.sequence??0;return c!==p?c-p:o.id.localeCompare(s.id)})}var Kx="https://api.runtype.com/v1/dispatch",Hy="https://api.runtype.com",$e=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Ry=32768,cu=49152,Wy=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:typeof e.flowId=="string"?e.flowId: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:""}},By=t=>"reason"in t?t.reason:void 0,_y="The identity proof was not admitted; account history is unavailable",Oy="The identity proof was rejected",Dy="The request carried no visitor credential",Ny="The stored visitor belongs to a different signed-in user",Fy=(t,e)=>t instanceof $e&&t.code===e;function Gx(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 du=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 Qx(t){switch(t){case"json":return kh;case"regex-json":return Th;case"xml":return Ph;default:return Eh}}var Uy=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function Yx(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=Uy(n);if(!Uy(o))return t;if(!s||o===n||o.startsWith(n))return e;let l=ga(t);return ga(e)!==null&&l===null?e:t}var Aa=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??Kx,this.headers={"Content-Type":"application/json","X-Persona-Version":si,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??Qx(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 oy().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Ch,getToolDisplayTitle:lc,loadPolyfill:Sh});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=sy(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$/,"")||Hy}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}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&&By(n)===By(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=null;n&&(await this.historyInternals.historyBootstrapReady,o=await this.readVisitorToken());let s=this.routing(),i=s.agentId??s.flowId,l=n?e.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...n&&{visitorHistory:!0},...n&&o?{visitorToken:o}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...l?{conversationId:l}:e.storedSessionId?{sessionId:e.storedSessionId}:{}},p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si},body:JSON.stringify(c)});if(!p.ok){let g=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&g.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new $e("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw n&&p.status===401&&g.error==="visitor_required"?new $e("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new $e("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${g.hint||g.error}`):p.status===403?new Error(`Origin not allowed: ${g.hint||g.error}`):new Error(g.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId??u.flow?.id?{targetId:u.targetId??u.flow?.id}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){if(!this.isHistoryCapable()){let o=this.config.getStoredSessionId?.()||null,s=await this.createClientSession({storedSessionId:o});return this.config.setStoredSessionId?.(s.sessionId),s}await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=await this.readVisitorToken();if(e&&n)try{let o=await this.createClientSession({conversationId:e});return this.finishInit(o,e,!1)}catch(o){if(!Fy(o,"not_found")&&!Fy(o,"visitor_required"))throw o;return this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&this.isHistoryCapable()&&!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())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 $e("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 $e("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":si},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 $e("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 $e("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 $e("proof_not_admitted",_y);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 $e("invalid_identity_proof",Oy);if(s.includes("visitor token required"))throw new $e("visitor_token_missing",Dy);if(s.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new $e("visitor_identity_mismatch",Ny);return this.reinitWithProof(n)}if(s.includes("expired")||s.includes("not found"))return this.clearClientSession(),this.initSession();throw new $e("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new $e("not_found","Conversation not found");if(e.status===429){let s=Number.parseInt(e.headers.get("Retry-After")??"",10);return new $e("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 $e("proof_not_admitted",_y);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 $e("invalid_identity_proof",Oy)):s.includes("visitor token required")?new $e("visitor_token_missing",Dy):s.includes("visitor_identity_mismatch")?new $e("visitor_identity_mismatch",Ny):new $e("unauthorized",o||"History request was not authorized")}return new $e("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 $e("identity_contract_violation","Server reported an ignored identity proof on a success response"):new $e("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(s==="admitted")throw new $e("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 p=l?.revision()??0,u=await this.readVisitorToken();if(!u&&!n.visitorTokenOptional)throw new $e("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":si,...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 f=g.headers.get("X-History-Identity-Status"),v=await g.json().catch(()=>{});if(l&&l.revision()!==p)throw new $e("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(f,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 $e("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(Wy),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}:{}}),s=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:Wy(s),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 p of n){let u=p.displayContent.length;if(u>Ry)throw new $e("payload_too_large",`displayContent exceeds the ${Ry} character limit`);o+=u}if(o>cu)throw new $e("payload_too_large",`Display projection batch exceeds the ${cu} 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<=cu,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=iy();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 h=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:h}),h}let c=await this.buildPayload(e.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([h])=>h!=="sessionId"&&h!=="session_id")):void 0,u=this.isHistoryCapable(),g={sessionId:l.sessionId,messages:e.messages.filter(du).map(h=>{let M=u?Sa(h):void 0;return{id:h.id,role:h.role,content:h.contentParts??h.llmContent??h.rawContent??h.content,...M!==void 0&&{displayContent:M}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},{response:f,commit:v}=await this.sendWithClientToolsDiff(l.sessionId,c.clientTools,h=>{let M={...g,...h};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",M),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si},body:JSON.stringify(M),signal:e.signal})});if(!f.ok){let h=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let A=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:A}),A}if(f.status===429){let A=new Error(h.hint||"Message limit reached for this session.");throw i({type:"error",error:A}),A}if(f.status===410&&h.error==="conversation_deleted"){let A=new $e("conversation_deleted","This conversation was deleted");throw i({type:"error",error:A}),A}let M=new Error(h.error||"Failed to send message");throw i({type:"error",error:M}),M}if(!f.body){let h=new Error("No response body received");throw i({type:"error",error:h}),h}v(),i({type:"status",status:"connected"});try{await this.streamResponse(f.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 $e)&&!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?wh(n):void 0,c=this.clientToolsFingerprintSessionId===e,p=i&&c&&this.lastSentClientToolsFingerprint===l,u=!i&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,g=!1,f;for(let v=0;;v++){if(f=await o({...i&&(g||!p)&&n?{clientTools:n}:{},...u?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),f.status===409&&v===0&&i&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,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(/\/+$/,"")||Hy}/resume`,l;s&&(l=(await this.initSession()).sessionId);let c={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(l&&(p.sessionId=l),s&&l){let u=[...xc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:g,commit:f}=await this.sendWithClientToolsDiff(l,u,v=>{let h={...p,...v};return this.debug&&console.debug("[AgentWidgetClient] client token resume",h),fetch(i,{method:"POST",headers:c,body:JSON.stringify(h),signal:o?.signal})},{emptyMeansReplace:!0});return g.ok&&f(),g}return fetch(i,{method:"POST",headers:c,body:JSON.stringify(p),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(du).filter(u=>u.role==="user"||u.role==="assistant"||u.role==="system").filter(u=>!u.variant||u.variant==="assistant").sort((u,g)=>{let f=new Date(u.createdAt).getTime(),v=new Date(g.createdAt).getTime();return f-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=[...xc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let p=await this.buildContextAggregate(e);return p&&(l.context=p),l}async buildPayload(e,n){let o=e.slice().filter(du).sort((u,g)=>{let f=new Date(u.createdAt).getTime(),v=new Date(g.createdAt).getTime();return f-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=[...xc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.buildContextAggregate(e);c&&(i.context=c);let p=this.normalizeComposerOptions(n);if(p&&(i.composerOptions=p),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 p=g=>{let f={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=f,s(f),f},u=g=>o.current?o.current:p(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)),p(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="",p=Date.now(),u=0,g=()=>p+u++,f=H=>{let ee=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,b=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,D=H.tools?H.tools.map(N=>({...N,chunks:N.chunks?[...N.chunks]:void 0})):void 0;return{...H,reasoning:ee,toolCall:b,tools:D}},v=H=>{if(H.role!=="assistant"||H.variant)return!0;let ee=Array.isArray(H.contentParts)&&H.contentParts.length>0,b=typeof H.rawContent=="string"&&H.rawContent.trim()!=="";return typeof H.content=="string"&&H.content.trim()!==""||ee||b||!!H.stopReason},h=H=>{v(H)&&n({type:"message",message:f(H)})},M=null,A=null,T={current:null},F={current:null},P=null,K="",x=new Map,L=new Map,w=new Map,_=new Map,G=new Map,ie={lastId:null,byStep:new Map},oe={lastId:null,byCall:new Map},S=H=>{if(H==null)return null;try{return String(H)}catch{return null}},O=H=>S(H.stepId??H.step_id??H.step??H.parentId??H.flowStepId??H.flow_step_id),R=H=>S(H.callId??H.call_id??H.requestId??H.request_id??H.toolCallId??H.tool_call_id??H.stepId??H.step_id),I=o,Y=!1,V=()=>{if(M)return M;let H,ee="",b=P;return!Y&&I?(H=I,Y=!0,ee=s??""):I&&b?H=`${I}_${b}`:H=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,M={id:H,role:"assistant",content:ee,createdAt:new Date().toISOString(),streaming:!0,sequence:g()},h(M),M},ae=(H,ee)=>{ie.lastId=ee,H&&ie.byStep.set(H,ee)},ce=(H,ee)=>{let b=H.reasoningId??H.id,D=O(H);if(b){let U=String(b);return ae(D,U),U}if(D){let U=ie.byStep.get(D);if(U)return ie.lastId=U,U}if(ie.lastId&&!ee)return ie.lastId;if(!ee)return null;let N=`reason-${g()}`;return ae(D,N),N},me=H=>{let ee=_.get(H);if(ee)return ee;let b={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:g(),reasoning:{id:H,status:"streaming",chunks:[]}};return _.set(H,b),h(b),b},we=(H,ee)=>{oe.lastId=ee,H&&oe.byCall.set(H,ee)},ue=new Set,_e=new Map,ct=new Set,Ce=new Map,$=H=>{if(!H)return!1;let ee=H.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},Pe=(H,ee)=>{let b=H.toolId??H.id,D=R(H);if(b){let U=String(b);return we(D,U),U}if(D){let U=oe.byCall.get(D);if(U)return oe.lastId=U,U}if(oe.lastId&&!ee)return oe.lastId;if(!ee)return null;let N=`tool-${g()}`;return we(D,N),N},Ne=H=>{let ee=G.get(H);if(ee)return ee;let b={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:g(),toolCall:{id:H,status:"pending"}};return G.set(H,b),h(b),b},xe=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let ee=Number(H);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let b=Date.parse(H);if(!Number.isNaN(b))return b}return Date.now()},Oe=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},ye=new Map,gt=new Map,Zn=new Map,Cs=(H,ee,b)=>{let D=Zn.get(H);D||(D=[],Zn.set(H,D));let N=0,U=D.length;for(;N<U;){let te=N+U>>>1;D[te].seq<ee?N=te+1:U=te}D[N]?.seq===ee?D[N]={seq:ee,text:b}:D.splice(N,0,{seq:ee,text:b});let Z="";for(let te=0;te<D.length;te++)Z+=D[te].text;return Z},Jt=(H,ee)=>{let b=Oe(ee),D=gt.get(H.id),N=Yx(D,b);H.rawContent=N;let U=ye.get(H.id),Z=qe=>{let Lt=H.content??"";qe.trim()!==""&&(Lt.trim().length===0||qe.startsWith(Lt)||qe.trimStart().startsWith(Lt.trim()))&&(H.content=qe)},te=()=>{if(U){let qe=U.close?.();qe instanceof Promise&&qe.catch(()=>{})}ye.delete(H.id),gt.delete(H.id),H.streaming=!1,h(H)};if(!U){Z(b),te();return}let le=ga(N);if(le!==null&&le.trim()!==""){Z(le),te();return}let Ae=qe=>{let Lt=typeof qe=="string"?qe:qe?.text??null;if(Lt!==null&&Lt.trim()!=="")return Lt;let Ct=U.getExtractedText();return Ct!==null&&Ct.trim()!==""?Ct:b},mt;try{mt=U.processChunk(N)}catch{Z(b),te();return}if(mt instanceof Promise){mt.then(qe=>{Z(Ae(qe)),te()}).catch(()=>{Z(b),te()});return}Z(Ae(mt)),te()},Fn=null,Io=(H,ee,b,D)=>{H.rawContent=ee,ye.has(H.id)||ye.set(H.id,this.createStreamParser());let N=ye.get(H.id),U=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(U&>.set(H.id,ee),N.__isPlainTextParser===!0){H.content=D!==void 0?ee:H.content+b,gt.delete(H.id),ye.delete(H.id),H.rawContent=void 0,h(H);return}let te=N.processChunk(ee);if(te instanceof Promise)te.then(le=>{let Ae=typeof le=="string"?le:le?.text??null;Ae!==null&&Ae.trim()!==""?(H.content=Ae,h(H)):!U&&!ee.trim().startsWith("<")&&(H.content=D!==void 0?ee:H.content+b,gt.delete(H.id),ye.delete(H.id),H.rawContent=void 0,h(H))}).catch(()=>{H.content=D!==void 0?ee:H.content+b,gt.delete(H.id),ye.delete(H.id),H.rawContent=void 0,h(H)});else{let le=typeof te=="string"?te:te?.text??null;le!==null&&le.trim()!==""?(H.content=le,h(H)):!U&&!ee.trim().startsWith("<")&&(H.content=D!==void 0?ee:H.content+b,gt.delete(H.id),ye.delete(H.id),H.rawContent=void 0,h(H))}},It=(H,ee)=>{let b=ee??H.content;if(b==null||b===""){H.streaming=!1,h(H);return}let N=gt.get(H.id)??Oe(b);H.rawContent=N;let U=ye.get(H.id),Z=null,te=!1;if(U&&(Z=U.getExtractedText(),Z===null&&(Z=ga(N)),Z===null)){let le=U.processChunk(N);le instanceof Promise?(te=!0,le.then(Ae=>{let mt=typeof Ae=="string"?Ae:Ae?.text??null;mt!==null&&(H.content=mt,H.streaming=!1,ye.delete(H.id),gt.delete(H.id),h(H))}).catch(()=>{})):Z=typeof le=="string"?le:le?.text??null}if(!te){Z!==null&&Z.trim()!==""?H.content=Z:gt.has(H.id)||(H.content=Oe(b));let le=ye.get(H.id);if(le){let Ae=le.close?.();Ae instanceof Promise&&Ae.catch(()=>{}),ye.delete(H.id)}gt.delete(H.id),H.streaming=!1,h(H)}},Pr=(H,ee,b)=>{let D=L.get(H);if(D)return D;let N={id:`nested-${ee}-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g(),...b?{variant:b}:{},...b==="reasoning"?{reasoning:{id:H,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return L.set(H,N),h(N),N},yn=[],po,xi=new Map,Ir=0,ln="agent",Ai=!1,xt=null,dt=null,eo=new Map,Va=this.config.iterationDisplay??"separate";for(po=()=>{for(let H=0;H<yn.length;H++){let ee=yn[H].payloadType,b=yn[H].payload;if(!Ai&&ln!=="flow"&&typeof b.stepType=="string"&&(ln="flow"),ee==="reasoning_start"){let D=typeof b.id=="string"?b.id:null,N=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(D&&N){x.set(D,N),Pr(D,N,"reasoning");continue}let U=ce(b,!0)??`reason-${g()}`,Z=me(U);Z.reasoning=Z.reasoning??{id:U,status:"streaming",chunks:[]},Z.reasoning.startedAt=Z.reasoning.startedAt??xe(b.startedAt??b.timestamp),Z.reasoning.completedAt=void 0,Z.reasoning.durationMs=void 0,(b.scope==="loop"||b.scope==="turn")&&(Z.reasoning.scope=b.scope),Z.streaming=!0,Z.reasoning.status="streaming",h(Z)}else if(ee==="reasoning_delta"){let D=typeof b.id=="string"?b.id:null;if(D&&x.has(D)&&L.has(D)){let te=L.get(D),le=b.reasoningText??b.text??b.delta??"";le&&b.hidden!==!0&&te.reasoning&&(te.reasoning.chunks.push(String(le)),h(te));continue}let N=ce(b,!1)??ce(b,!0)??`reason-${g()}`,U=me(N);U.reasoning=U.reasoning??{id:N,status:"streaming",chunks:[]},U.reasoning.startedAt=U.reasoning.startedAt??xe(b.startedAt??b.timestamp);let Z=b.reasoningText??b.text??b.delta??"";if(Z&&b.hidden!==!0){let te=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(te!==void 0){let le=Cs(N,te,String(Z));U.reasoning.chunks=[le]}else U.reasoning.chunks.push(String(Z))}if(U.reasoning.status=b.done?"complete":"streaming",b.done){U.reasoning.completedAt=xe(b.completedAt??b.timestamp);let te=U.reasoning.startedAt??Date.now();U.reasoning.durationMs=Math.max(0,(U.reasoning.completedAt??Date.now())-te)}U.streaming=U.reasoning.status!=="complete",h(U)}else if(ee==="reasoning_complete"){let D=typeof b.id=="string"?b.id:null;if(D&&x.has(D)&&L.has(D)){let le=L.get(D);if(le.reasoning){let Ae=typeof b.text=="string"?b.text:"";Ae&&le.reasoning.chunks.length===0&&le.reasoning.chunks.push(Ae),le.reasoning.status="complete",le.streaming=!1,h(le)}x.delete(D),L.delete(D);continue}let N=ce(b,!1)??ce(b,!0)??`reason-${g()}`,U=typeof b.text=="string"?b.text:"";!_.get(N)&&(U||b.scope==="loop")&&me(N);let Z=_.get(N);if(Z?.reasoning){(b.scope==="loop"||b.scope==="turn")&&(Z.reasoning.scope=b.scope),U&&Z.reasoning.chunks.length===0&&Z.reasoning.chunks.push(U),Z.reasoning.status="complete",Z.reasoning.completedAt=xe(b.completedAt??b.timestamp);let le=Z.reasoning.startedAt??Date.now();Z.reasoning.durationMs=Math.max(0,(Z.reasoning.completedAt??Date.now())-le),Z.streaming=!1,h(Z)}let te=O(b);te&&ie.byStep.delete(te)}else if(ee==="tool_start"){M&&(M.streaming=!1,h(M),M=null),typeof b.iteration=="number"&&(Ir=b.iteration);let D=(typeof b.toolCallId=="string"?b.toolCallId:void 0)??Pe(b,!0)??`tool-${g()}`,N=b.toolName??b.name;if($(N)){ue.add(D);continue}we(R(b),D);let U=Ne(D),Z=U.toolCall??{id:D,status:"pending"};Z.name=N??Z.name,Z.status="running",b.parameters!==void 0?Z.args=b.parameters:b.args!==void 0&&(Z.args=b.args),Z.startedAt=Z.startedAt??xe(b.startedAt??b.timestamp),Z.completedAt=void 0,Z.durationMs=void 0,U.toolCall=Z,U.streaming=!0,b.executionId&&(U.agentMetadata={executionId:b.executionId,iteration:b.iteration}),h(U)}else if(ee==="tool_output_delta"){let D=Pe(b,!1)??Pe(b,!0)??`tool-${g()}`;if(ue.has(D))continue;let N=Ne(D),U=N.toolCall??{id:D,status:"running"};U.startedAt=U.startedAt??xe(b.startedAt??b.timestamp);let Z=b.text??b.delta??b.message??"";Z&&(U.chunks=U.chunks??[],U.chunks.push(String(Z))),U.status="running",N.toolCall=U,N.streaming=!0;let te=b.agentContext;(te||b.executionId)&&(N.agentMetadata=N.agentMetadata??{executionId:te?.executionId??b.executionId,iteration:te?.iteration??b.iteration}),h(N)}else if(ee==="tool_complete"){let D=Pe(b,!1)??Pe(b,!0)??`tool-${g()}`;if(ue.has(D)){ue.delete(D);continue}let N=Ne(D),U=N.toolCall??{id:D,status:"running"};U.status="complete",b.result!==void 0&&(U.result=b.result),typeof b.duration=="number"&&(U.duration=b.duration),U.completedAt=xe(b.completedAt??b.timestamp);let Z=b.duration??b.executionTime;if(typeof Z=="number")U.durationMs=Z;else{let Ae=U.startedAt??Date.now();U.durationMs=Math.max(0,(U.completedAt??Date.now())-Ae)}N.toolCall=U,N.streaming=!1;let te=b.agentContext;(te||b.executionId)&&(N.agentMetadata=N.agentMetadata??{executionId:te?.executionId??b.executionId,iteration:te?.iteration??b.iteration}),h(N);let le=R(b);le&&oe.byCall.delete(le)}else if(ee==="await"&&b.toolName){let D=typeof b.toolCallId=="string"&&b.toolCallId.length>0?b.toolCallId:void 0,N=D??b.toolId??`local-${g()}`,U=Ne(N),Z=b.toolName,te=b.origin==="webmcp"&&!Xs(Z)?`webmcp:${Z}`:Z,le=Xs(te),Ae=U.toolCall??{id:N,status:"pending"};Ae.name=te,Ae.args=b.parameters,Ae.status=le?"running":"complete",Ae.chunks=Ae.chunks??[],Ae.startedAt=Ae.startedAt??xe(b.startedAt??b.timestamp??b.awaitedAt),le?(Ae.completedAt=void 0,Ae.duration=void 0,Ae.durationMs=void 0):Ae.completedAt=Ae.completedAt??Ae.startedAt,U.toolCall=Ae,U.streaming=!1,U.agentMetadata={...U.agentMetadata,executionId:b.executionId??U.agentMetadata?.executionId,awaitingLocalTool:!0,...D?{webMcpToolCallId:D}:{}},h(U)}else if(ee==="text_start"){let D=typeof b.id=="string"?b.id:null,N=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(D&&N){x.set(D,N);continue}let U=M;U&&(ln==="flow"?(It(U),Fn=U):(U.streaming=!1,h(U)),M=null),P=typeof b.id=="string"?b.id:P,K=""}else if(ee==="text_delta"){let D=typeof b.id=="string"?b.id:null,N=D?x.get(D):void 0;if(D&&N){let Z=typeof b.delta=="string"?b.delta:"",te=(w.get(D)??"")+Z;if(w.set(D,te),te.trim()==="")continue;let le=Pr(D,N);le.agentMetadata={...le.agentMetadata,executionId:b.executionId,parentToolId:N},Io(le,te,Z,void 0);continue}if(P=typeof b.id=="string"?b.id:P,ln==="flow"){let Z=typeof b.delta=="string"?b.delta:"";if(K+=Z,K.trim()==="")continue;let te=V();te.agentMetadata={executionId:b.executionId,iteration:b.iteration},Io(te,K,Z,void 0),A=te;continue}let U=V();U.content+=b.delta??"",U.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:xt??void 0,agentName:dt?.agentName},A=U,h(U)}else if(ee==="text_complete"){let D=typeof b.id=="string"?b.id:null;if(D&&x.has(D)){let U=L.get(D);U&&It(U),x.delete(D),w.delete(D),L.delete(D);continue}let N=M;N&&(ln==="flow"?(It(N),Fn=N):((N.content??"")===""&&typeof b.text=="string"&&(N.content=b.text),N.streaming=!1,h(N)),M=null),P=null,K=""}else if(ee==="step_complete"){let D=b.stepType,N=b.executionType;if(D==="tool"||N==="context")continue;if(b.success===!1){let U=b.error,Z=typeof U=="string"&&U!==""?U:U!=null&&typeof U=="object"&&Reflect.has(U,"message")?String(U.message??"Step failed"):"Step failed";n({type:"error",error:new Error(Z)});let te=M;te&&te.streaming&&(te.streaming=!1,h(te)),n({type:"status",status:"idle"});continue}{let U=Fn;Fn=null;let Z=b.stopReason,te=b.result?.response;if(U)Z&&(U.stopReason=Z),te!=null?Jt(U,te):U.streaming!==!1&&(ye.delete(U.id),gt.delete(U.id),U.streaming=!1,h(U));else{let le=te!=null&&te!=="";if(le||Z){let Ae=V();Z&&(Ae.stopReason=Z),le?It(Ae,te):(Ae.streaming=!1,h(Ae))}}continue}}else if(ee==="execution_start")ln=b.kind==="flow"?"flow":"agent",Ai=!0,ln==="agent"&&(dt={executionId:b.executionId,agentId:b.agentId??"virtual",agentName:b.agentName??"",status:"running",currentIteration:0,maxTurns:b.maxTurns??1,startedAt:xe(b.startedAt)});else if(ee==="turn_start"){let D=typeof b.iteration=="number"?b.iteration:Ir;if(D!==Ir){if(dt&&(dt.currentIteration=D),Va==="separate"&&D>1){let N=M;N&&(N.streaming=!1,h(N),eo.set(D-1,N),M=null)}Ir=D}xt=typeof b.id=="string"?b.id:null,A=null}else if(ee==="tool_input_delta"){let D=b.toolCallId??oe.lastId;if(D){let N=G.get(D);N?.toolCall&&(N.toolCall.chunks=N.toolCall.chunks??[],N.toolCall.chunks.push(b.delta??""),h(N))}}else{if(ee==="tool_input_complete")continue;if(ee==="turn_complete"){let D=b.stopReason,N=M??A;if(D&&N!==null){let U=b.id;(!U||N.agentMetadata?.turnId===U)&&(N.stopReason=D,h(N))}xt===b.id&&(xt=null)}else if(ee==="media_start"){let D=String(b.id);xi.set(D,{mediaType:typeof b.mediaType=="string"?b.mediaType:void 0,role:typeof b.role=="string"?b.role:void 0,toolCallId:b.toolCallId,parts:[]})}else if(ee==="media_delta"){let D=xi.get(String(b.id));D&&typeof b.delta=="string"&&D.parts.push(b.delta)}else if(ee==="media_complete"){let D=String(b.id),N=xi.get(D);xi.delete(D);let U=(typeof b.mediaType=="string"?b.mediaType:void 0)??N?.mediaType??"application/octet-stream",Z=typeof b.data=="string"?b.data:void 0,te=typeof b.url=="string"?b.url:N&&N.parts.length>0?N.parts.join(""):void 0,le=null;if(Z)le={type:"media",data:Z,mediaType:U};else if(te){let Lt=U.toLowerCase();le={type:Lt==="image"||Lt.startsWith("image/")?"image-url":"file-url",url:te,mediaType:U}}let Ae=b.toolCallId??N?.toolCallId,mt=le?[le]:[],qe=[];for(let Lt of mt){if(!Lt||typeof Lt!="object")continue;let Ct=Lt,Lr=typeof Ct.type=="string"?Ct.type:void 0,En=typeof Ct.mediaType=="string"?Ct.mediaType.toLowerCase():"",Nt=null,cn="";if(Lr==="media"){let tn=typeof Ct.data=="string"?Ct.data:void 0;if(!tn)continue;cn=En.length>0?En:"application/octet-stream",Nt=`data:${cn};base64,${tn}`}else if(Lr==="image-url"){let tn=typeof Ct.url=="string"?Ct.url:void 0;if(!tn)continue;cn=En,Nt=tn}else if(Lr==="file-url"){let tn=typeof Ct.url=="string"?Ct.url:void 0;if(!tn)continue;cn=En,Nt=tn}else continue;if(Nt)if(Lr==="image-url"||cn.startsWith("image/"))qe.push({type:"image",image:Nt,...cn.includes("/")?{mimeType:cn}:{}});else if(cn.startsWith("audio/"))qe.push({type:"audio",audio:Nt,mimeType:cn});else if(cn.startsWith("video/"))qe.push({type:"video",video:Nt,mimeType:cn});else{let tn=cn||"application/octet-stream";qe.push({type:"file",data:Nt,mimeType:tn,filename:Gx(tn)})}}if(qe.length>0){let Lt=g(),Ct=Ae,En={id:`agent-media-${typeof Ct=="string"&&Ct.length>0?`${Ct}-${Lt}`:String(Lt)}`,role:"assistant",content:"",contentParts:qe,createdAt:new Date().toISOString(),streaming:!1,sequence:Lt,agentMetadata:{executionId:b.executionId,iteration:typeof b.iteration=="number"?b.iteration:Ir}};h(En);let Nt=M;Nt&&(Nt.streaming=!1,h(Nt)),M=null,T.current=null}}else if(ee==="execution_complete"){let D=b.kind??ln;D==="agent"&&dt&&(dt.status=b.success?"complete":"error",dt.completedAt=xe(b.completedAt),dt.stopReason=b.stopReason);let N=M;N&&(D==="flow"&&N.streaming!==!1?It(N):(N.streaming=!1,h(N)),M=null),P=null,K="",Fn=null,n({type:"status",status:"idle",terminal:!0})}else if(ee==="execution_error"){let D=typeof b.error=="string"?b.error:b.error?.message??"Execution error";n({type:"error",error:new Error(D)})}else if(ee!=="ping"){if(ee==="approval_start"){let D=b.approvalId??`approval-${g()}`,N={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:g(),approval:{id:D,status:"pending",agentId:dt?.agentId??"virtual",executionId:b.executionId??dt?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};h(N)}else if(ee==="step_await"&&b.awaitReason==="approval_required"){let D=b.approvalId??`approval-${g()}`,N={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:g(),approval:{id:D,status:"pending",agentId:dt?.agentId??"virtual",executionId:b.executionId??dt?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};h(N)}else if(ee==="approval_complete"){let D=b.approvalId;if(D){let U={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:g(),approval:{id:D,status:b.decision??"approved",agentId:dt?.agentId??"virtual",executionId:b.executionId??dt?.executionId??"",toolName:b.toolName??"",description:b.description??"",resolvedAt:Date.now()}};h(U)}}else if(ee==="artifact_start"||ee==="artifact_delta"||ee==="artifact_update"||ee==="artifact_complete"){if(ee==="artifact_start"){let D=b.artifactType,N=String(b.id),U=typeof b.title=="string"?b.title:void 0,Z=b.file,te;Z&&typeof Z=="object"&&!Array.isArray(Z)&&typeof Z.path=="string"&&typeof Z.mimeType=="string"&&(te={path:Z.path,mimeType:Z.mimeType,...typeof Z.language=="string"?{language:Z.language}:{}}),n({type:"artifact_start",id:N,artifactType:D,title:U,component:typeof b.component=="string"?b.component:void 0,...te?{file:te}:{}});let le=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?{...b.props}:void 0;if(Ce.set(N,{markdown:"",title:U,file:te,...le?{props:le}:{}}),!ct.has(N)){ct.add(N);let Ae=wr(this.config.features?.artifacts,{artifactType:D,...te?{file:te}:{}}),mt=typeof b.component=="string"?b.component:void 0,qe={id:`artifact-ref-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g(),rawContent:ba(Ae,{artifactId:N,title:U,artifactType:D,status:"streaming",...te?{file:te}:{},...mt?{component:mt}:{}})};_e.set(N,qe),h(qe)}}else if(ee==="artifact_delta"){let D=String(b.id),N=typeof b.delta=="string"?b.delta:String(b.delta??"");n({type:"artifact_delta",id:D,artDelta:N});let U=Ce.get(D);U&&(U.markdown+=N)}else if(ee==="artifact_update"){let D=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};n({type:"artifact_update",id:String(b.id),props:D,component:typeof b.component=="string"?b.component:void 0});let N=Ce.get(String(b.id));N&&(N.props={...N.props??{},...D})}else if(ee==="artifact_complete"){let D=String(b.id);n({type:"artifact_complete",id:D});let N=_e.get(D);if(N){N.streaming=!1;try{let U=JSON.parse(N.rawContent??"{}");if(U.props){U.props.status="complete";let Z=Ce.get(D);Z?.markdown&&(U.props.markdown=Z.markdown),Z?.file&&(U.props.file=Z.file),U.component==="PersonaArtifactInline"&&Z?.props&&Object.keys(Z.props).length>0&&(U.props.componentProps=Z.props)}N.rawContent=JSON.stringify(U)}catch{}Ce.delete(D),h(N),_e.delete(D)}}}else if(ee==="transcript_insert"){let D=b.message;if(!D||typeof D!="object")continue;let N=String(D.id??`msg-${g()}`),U=D.role,te={id:N,role:U==="user"?"user":U==="system"?"system":"assistant",content:typeof D.content=="string"?D.content:"",rawContent:typeof D.rawContent=="string"?D.rawContent:void 0,createdAt:typeof D.createdAt=="string"?D.createdAt:new Date().toISOString(),streaming:D.streaming===!0,...typeof D.variant=="string"?{variant:D.variant}:{},sequence:g()};if(h(te),te.rawContent)try{let Ae=JSON.parse(te.rawContent)?.props?.artifactId;typeof Ae=="string"&&ct.add(Ae)}catch{}M=null,T.current=null,ye.delete(N),gt.delete(N)}else if(ee==="error"){if(b.recoverable===!1&&b.error!=null&&b.error!==""){let D=typeof b.error=="string"?b.error:b.error?.message!=null?String(b.error.message):"Execution error";n({type:"error",error:new Error(D)});let N=M;N&&N.streaming&&(N.streaming=!1,h(N)),n({type:"status",status:"idle"})}}else if(ee==="step_error"||ee==="dispatch_error"||ee==="flow_error"){let D=null;if(b.error instanceof Error)D=b.error;else if(ee==="dispatch_error"){let N=b.message??b.error;N!=null&&N!==""&&(D=new Error(String(N)))}else{let N=b.error;typeof N=="string"&&N!==""?D=new Error(N):N!=null&&typeof N=="object"&&Reflect.has(N,"message")&&(D=new Error(String(N.message??N)))}if(D){n({type:"error",error:D});let N=M;N&&N.streaming&&(N.streaming=!1,h(N)),n({type:"status",status:"idle"})}}}}}yn.length=0};;){let{done:H,value:ee}=await i.read();if(H)break;c+=l.decode(ee,{stream:!0});let b=c.split(`
|
|
1
|
+
import{a as hc,b as jh,c as eu,d as ma,e as yc,f as fa,g as bc,h as ha,i as Vh,j as ya}from"./chunk-CPVD5P5B.js";import{b as wh,c as lc,d as Sh,e as Xs,f as xh,g as cc,h as Ah,i as Mh,j as Eh,k as dc,l as pc,m as Xp,n as uc,o as ga,p as Th,q as kh,r as Ph,s as Ih}from"./chunk-HBE7LFNT.js";import{a as Nh,b as Fh,c as Ko,d as gs,e as Uh,f as $h,g as qh,h as Zp,i as zh}from"./chunk-VK6JOIYJ.js";import{a as Pt,b as bh,c as ic,e as Ys,f as vh,g as ac,h as Ch,j as Hh,k as Rh,l as he,m as Dt,n as an,o as gc,p as Kh,q as Gh,u as Qh,v as Js,w as Go}from"./chunk-NIKYKSNZ.js";import{a as us,d as tu}from"./chunk-EFJBUH5F.js";import{a as Lh,c as Wh,d as fc,e as Jp,f as Dh}from"./chunk-UTVLOTWB.js";import{a as Bh,c as _h,d as Oh}from"./chunk-R2TMIMDI.js";import{a as en}from"./chunk-7NQ4ZTHF.js";import{b as mc}from"./chunk-Q735PSZL.js";import{a as k,c as Q,d as On}from"./chunk-76IELU7F.js";var Yh=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Xh=t=>t.includes("|"),Jh=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())},tx=t=>`| ${t.join(" | ")} |`,nx=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,ox=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Zh=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
2
|
+
`),n=!1;for(let o=0;o<e.length-1;o++){let s=e[o],i=e[o+1];if(!Xh(s)||Yh.test(s)||!Yh.test(i))continue;let l=Jh(s).length;if(l<1)continue;let c=nx(l);e[o+1]!==c&&(e[o+1]=c,n=!0);let p=o+2;for(;p<e.length;p++){let u=e[p];if(u.trim()===""||!Xh(u))break;let g=tx(ox(Jh(u),l));e[p]!==g&&(e[p]=g,n=!0)}o=p-1}return n?e.join(`
|
|
3
|
+
`):t};var ey="var(--persona-md-table-scroll-fade, 24px)",ty=new WeakSet;function oy(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 ny(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":ey),t.style.setProperty("--persona-fade-r",s<=1?"0px":ey)}function nu(t){ty.has(t)||(ty.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&ny(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(ny)}var{setLoader:KT,load:rx}=Pt({fallbackImport:()=>import("./webmcp-runtime-P3CHZRHF.js")});var ry=rx;function Yn(t){return t==="card"?"collapsed":t}function Zs(t){return t.split(";",1)[0].trim().toLowerCase()}function sx(t,e){if(!t)return;let n=Object.entries(t);for(let[s,i]of n)if(Zs(s)===e)return{mode:Yn(i),selector:Zs(s)};let o=`${e.split("/",1)[0]}/*`;for(let[s,i]of n)if(Zs(s)===o)return{mode:Yn(i),selector:o}}function ix(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:Yn(o.files),matchedBy:{type:"files"}};let c=e.file.mimeType?Zs(e.file.mimeType):void 0,p=c?sx(o.files.byMediaType,c):void 0;if(c&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:c,selector:p.selector}};if(o.files.default)return{mode:Yn(o.files.default),matchedBy:{type:"files"}}}let s=o.byKind?.[e.artifactType];if(s)return{mode:Yn(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let i=o.byType?.[e.artifactType];if(i)return{mode:Yn(i),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let l=e.presentation?.preferredMode;return l?{mode:Yn(l),matchedBy:{type:"preferredMode"}}:o.default?{mode:Yn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function wr(t,e){return ix(t,e).mode}function ba(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 ax="agent_",lx="flow_";function sy(t){return t.startsWith(ax)?{kind:"agentId",agentId:t}:t.startsWith(lx)?{kind:"flowId",flowId:t}:null}function iy(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=sy(c);if(u)return u;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[l];if(!p)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:p(c).payload}}let s=sy(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 vc(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ei(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function ay(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}import{parse as cx,ARR as dx,OBJ as px,STR as ux}from"partial-json";var ou="ask_user_question",va=8,ti="data-persona-ask-sheet-for",gx="Other",mx="Other\u2026",cy="Type your own answer here",dy="Send",fx="Next",hx="Back",yx="Submit all",bx="Skip",vx=3,ru="data-ask-current-index",su="data-ask-question-count",py="data-ask-answers",iu="data-ask-grouped",uy="data-ask-layout",Cx=t=>t.layout==="pills"?"pills":"rows",wx=t=>t.getAttribute(uy)==="pills"?"pills":"rows",ly=!1,gy=t=>t.replace(/["\\]/g,"\\$&"),ms=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===ou,au=t=>t?.features?.askUserQuestion??{},ni=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=cx(s,ux|px|dx);if(i&&typeof i=="object")return{payload:i,complete:n}}catch{}return{payload:null,complete:n}},Ca=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>va&&!ly&&(ly=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${va}.`)),e.slice(0,va)},Sx=t=>Ca(t)[0]??null,xx=(t,e)=>Ca(t)[e]??null,Ax=(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))},my=(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},Mx=(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 p=my(n,o,e);p&&i.appendChild(p)}else i.textContent=t.label,t.description&&(i.title=t.description);return i},Ex=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},Tx=(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,p=(Array.isArray(t?.options)?t.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(p.length===0&&!n){for(let g=0;g<vx;g++)i.appendChild(Ex(o));return i}if(p.forEach((g,f)=>{i.appendChild(Mx(g,f,o,l))}),t?.allowFreeText!==!1){let g=o==="rows"?gx:mx;if(o==="rows"){let f=k("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(p.length)),f.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??cy,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",e.freeTextLabel??g),v.appendChild(h),f.appendChild(v);let M=my(o,l,p.length);M&&f.appendChild(M),i.appendChild(f)}else{let f=k("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=e.freeTextLabel??g,i.appendChild(f)}}return i},fy=(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??cy,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??dy,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},kx=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??dy,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},Px=(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??hx,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??bx,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 p=t===e-1;return c.textContent=p?n.submitAllLabel??yx:n.nextLabel??fx,c.setAttribute("data-ask-user-action",p?"submit-all":"next"),c.disabled=!0,i.appendChild(c),o.appendChild(i),o},fs=t=>{let e=t.getAttribute(py);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},hy=(t,e)=>{t.setAttribute(py,JSON.stringify(e))},Xn=t=>{let e=Number(t.getAttribute(ru)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Ix=(t,e)=>{t.setAttribute(ru,String(Math.max(0,Math.floor(e))))},oi=t=>{let e=Number(t.getAttribute(su)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Sr=t=>t.getAttribute(iu)==="true",Lx=(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},Hx=(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)))},Cc=(t,e)=>{let{payload:n}=ni(e),o=Ca(n),s=fs(t),i={},l=new Set;return o.forEach((c,p)=>{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,p)&&(i[u]=s[p]))}),i},yy=t=>{let e=fs(t),n=Xn(t),o=e[n],s=new Set;typeof o=="string"?s.add(o):Array.isArray(o)&&o.forEach(p=>s.add(p));let i=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');i.forEach(p=>{let u=p.getAttribute("data-option-label")??"",g=s.has(u);p.setAttribute("aria-pressed",g?"true":"false"),p.classList.toggle("persona-ask-pill-selected",g)});let l=new Set(Array.from(i).map(p=>p.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="")},by=t=>{if(!Sr(t))return;let e=fs(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}},lu=(t,e,n)=>{let o=au(n),s=wx(t),{payload:i,complete:l}=ni(e),c=Sr(t),p=Xn(t),u=oi(t),g=c?xx(i,p):Sx(i),f=!!g?.multiSelect,v=t.querySelector('[data-ask-step-inline="true"]');v&&(v.textContent=c?`${p+1}/${u}`:"");let h=t.querySelector('[data-ask-stepper="true"]');h&&h.remove();let M=t.querySelector('[data-ask-question="true"]');if(M){let P=typeof g?.question=="string"?g.question:"";M.textContent=P,M.classList.toggle("persona-ask-question-skeleton",!P&&!l)}let A=t.querySelector('[data-ask-pill-list="true"]');if(A){let P=Tx(g,o,l,s);A.replaceWith(P)}if(s!=="rows"){let P=t.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(fy(o,s))}let T=t.querySelector('[data-ask-multi-actions="true"]');!c&&f&&!T?t.appendChild(kx(o)):(!f||c)&&T&&T.remove(),t.setAttribute("data-multi-select",f?"true":"false");let F=t.querySelector('[data-ask-nav-row="true"]');if(c){let P=Px(p,u,o);F?F.replaceWith(P):t.appendChild(P)}else F&&F.remove();yy(t),by(t)},Rx=(t,e,n)=>{let o=au(e),s=Cx(o),i=t.toolCall.id,l=Ca(n),c=Math.max(1,l.length),p=c>1,u=Lx(t,l),g=p?Hx(t,c):0,f=k("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(ti,i),f.setAttribute("data-tool-call-id",i),f.setAttribute("data-message-id",t.id),f.setAttribute(su,String(c)),f.setAttribute(ru,String(g)),f.setAttribute(iu,p?"true":"false"),f.setAttribute(uy,s),hy(f,u),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Ax(f,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 M=k("span","persona-ask-sheet-step-inline");M.setAttribute("data-ask-step-inline","true"),M.textContent="",v.appendChild(M),f.appendChild(v);let T=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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),s!=="rows"&&f.appendChild(fy(o,s)),lu(f,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Wx=(t,e,n)=>{let{payload:o}=ni(e),s=Math.max(1,Ca(o).length);s>oi(t)&&(t.setAttribute(su,String(s)),s>1&&!Sr(t)&&t.setAttribute(iu,"true")),lu(t,e,n)};var wc=(t,e,n)=>{if(!n||!ms(t)||au(e).enabled===!1)return;let s=t.toolCall.id;n.querySelectorAll(`[${ti}]`).forEach(u=>{u.getAttribute(ti)!==s&&u.remove()});let l=n.querySelector(`[${ti}="${gy(s)}"]`);if(l){Wx(l,t,e);return}let{payload:c}=ni(t),p=Rx(t,e,c);n.appendChild(p)},ri=(t,e)=>{if(!t)return;let n=e?`[${ti}="${gy(e)}"]`:`[${ti}]`;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)})},cu=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),xr=(t,e)=>{let n=fs(t),o=Xn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,hy(t,n),yy(t),by(t)},Sc=(t,e,n,o)=>{let s=oi(t),i=Math.max(0,Math.min(s-1,o));Ix(t,i),lu(t,e,n)};var Ar="suggest_replies";var Bx={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},Cy={name:Ar,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:Bx,origin:"sdk",annotations:{readOnlyHint:!0}},wy=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),wa=t=>t.variant==="tool"&&t.toolCall?.name===Ar,_x=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},Sy=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!wa(n))continue;let o=_x(n.toolCall?.args);return o.length>0?o:null}return null},vy=new Set,Ox=(t,e,n)=>{let o=`${t}:${e}:${n}`;vy.has(o)||(vy.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Mr=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=l=>{let c=e?.[l],p=n?.[l];c===void 0||p===void 0||c!==p&&Ox(l,p,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 Dx={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:va,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},Nx={name:ou,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:Dx,origin:"sdk",annotations:{readOnlyHint:!0}},xc=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(Nx),Mr(t).expose&&e.push(Cy),e};var xy="4.20.0";var si=xy;var ii="[Image]";function Ay(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function Ac(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Eo(t){return{type:"text",text:t}}function My(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var Ey=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ux=["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"],Qo=[...Ey,...Ux];function $x(t){return Ey.includes(t)||t.startsWith("image/")}function Mc(t){return $x(t.type)}function Ty(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function ky(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;Mc(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 Py(t,e=Qo,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 qx(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Iy(t,e){let n=qx(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 zx=["user","assistant","system"],jx=0;function Ly(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function Ec(t){return typeof t=="string"?t:void 0}function Vx(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?Eo(e.text):null;case"image":return typeof e.image=="string"?My(e.image,{mimeType:Ec(e.mimeType),alt:Ec(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?Ty(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...Ec(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...Ec(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function Kx(t,e){let n=Ly(e),o=t.map(l=>Ly(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 p=c-i+1,u=i>0?s[i-1]:null,g=c+1<o.length?o[c+1]:null,f=g!==null&&n!==null?Math.min(g,n):g??n;for(let v=0;v<p;v+=1)s[i+v]=f!==null?f-(p-v):u!==null?u+v+1:jx+v;i=c+1}return s.map(l=>new Date(l).toISOString())}function Hy(t,e){let n=Kx(t,e?.beforeCreatedAt),o=[];return t.forEach((s,i)=>{if(typeof s?.id!="string"||s.id===""||!zx.includes(s.role))return;let l=s.role,c=n[i];if(s.displayAvailable===!1){let p={historyDisplayUnavailable:!0};o.push({id:s.id,role:l,content:"",createdAt:c,agentMetadata:p});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 p=s.content.map(Vx).filter(g=>g!==null),u=Ay(p);o.push({id:s.id,role:l,content:u||(Ac(p)?ii:""),createdAt:c,...p.length>0&&{contentParts:p}});return}o.push({id:s.id,role:l,content:"",createdAt:c})}),o}function Sa(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 xa(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,p=s.sequence??0;return c!==p?c-p:o.id.localeCompare(s.id)})}var Gx="https://api.runtype.com/v1/dispatch",Ry="https://api.runtype.com",$e=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Wy=32768,du=49152,By=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:typeof e.flowId=="string"?e.flowId: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:""}},_y=t=>"reason"in t?t.reason:void 0,Oy="The identity proof was not admitted; account history is unavailable",Dy="The identity proof was rejected",Ny="The request carried no visitor credential",Fy="The stored visitor belongs to a different signed-in user",Uy=(t,e)=>t instanceof $e&&t.code===e;function Qx(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 pu=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 Yx(t){switch(t){case"json":return Ph;case"regex-json":return kh;case"xml":return Ih;default:return Th}}var $y=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function Xx(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=$y(n);if(!$y(o))return t;if(!s||o===n||o.startsWith(n))return e;let l=ga(t);return ga(e)!==null&&l===null?e:t}var Aa=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??Gx,this.headers={"Content-Type":"application/json","X-Persona-Version":si,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??Yx(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 ry().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:wh,getToolDisplayTitle:lc,loadPolyfill:xh});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=iy(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$/,"")||Ry}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}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&&_y(n)===_y(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=null;n&&(await this.historyInternals.historyBootstrapReady,o=await this.readVisitorToken());let s=this.routing(),i=s.agentId??s.flowId,l=n?e.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...n&&{visitorHistory:!0},...n&&o?{visitorToken:o}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...l?{conversationId:l}:e.storedSessionId?{sessionId:e.storedSessionId}:{}},p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si},body:JSON.stringify(c)});if(!p.ok){let g=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&g.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new $e("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw n&&p.status===401&&g.error==="visitor_required"?new $e("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new $e("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${g.hint||g.error}`):p.status===403?new Error(`Origin not allowed: ${g.hint||g.error}`):new Error(g.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId??u.flow?.id?{targetId:u.targetId??u.flow?.id}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){if(!this.isHistoryCapable()){let o=this.config.getStoredSessionId?.()||null,s=await this.createClientSession({storedSessionId:o});return this.config.setStoredSessionId?.(s.sessionId),s}await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=await this.readVisitorToken();if(e&&n)try{let o=await this.createClientSession({conversationId:e});return this.finishInit(o,e,!1)}catch(o){if(!Uy(o,"not_found")&&!Uy(o,"visitor_required"))throw o;return this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&this.isHistoryCapable()&&!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())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 $e("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 $e("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":si},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 $e("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 $e("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 $e("proof_not_admitted",Oy);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 $e("invalid_identity_proof",Dy);if(s.includes("visitor token required"))throw new $e("visitor_token_missing",Ny);if(s.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new $e("visitor_identity_mismatch",Fy);return this.reinitWithProof(n)}if(s.includes("expired")||s.includes("not found"))return this.clearClientSession(),this.initSession();throw new $e("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new $e("not_found","Conversation not found");if(e.status===429){let s=Number.parseInt(e.headers.get("Retry-After")??"",10);return new $e("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 $e("proof_not_admitted",Oy);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 $e("invalid_identity_proof",Dy)):s.includes("visitor token required")?new $e("visitor_token_missing",Ny):s.includes("visitor_identity_mismatch")?new $e("visitor_identity_mismatch",Fy):new $e("unauthorized",o||"History request was not authorized")}return new $e("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 $e("identity_contract_violation","Server reported an ignored identity proof on a success response"):new $e("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(s==="admitted")throw new $e("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 p=l?.revision()??0,u=await this.readVisitorToken();if(!u&&!n.visitorTokenOptional)throw new $e("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":si,...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 f=g.headers.get("X-History-Identity-Status"),v=await g.json().catch(()=>{});if(l&&l.revision()!==p)throw new $e("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(f,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 $e("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(By),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}:{}}),s=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:By(s),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 p of n){let u=p.displayContent.length;if(u>Wy)throw new $e("payload_too_large",`displayContent exceeds the ${Wy} character limit`);o+=u}if(o>du)throw new $e("payload_too_large",`Display projection batch exceeds the ${du} 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<=du,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=ay();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 h=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:h}),h}let c=await this.buildPayload(e.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([h])=>h!=="sessionId"&&h!=="session_id")):void 0,u=this.isHistoryCapable(),g={sessionId:l.sessionId,messages:e.messages.filter(pu).map(h=>{let M=u?Sa(h):void 0;return{id:h.id,role:h.role,content:h.contentParts??h.llmContent??h.rawContent??h.content,...M!==void 0&&{displayContent:M}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},{response:f,commit:v}=await this.sendWithClientToolsDiff(l.sessionId,c.clientTools,h=>{let M={...g,...h};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",M),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si},body:JSON.stringify(M),signal:e.signal})});if(!f.ok){let h=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let A=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:A}),A}if(f.status===429){let A=new Error(h.hint||"Message limit reached for this session.");throw i({type:"error",error:A}),A}if(f.status===410&&h.error==="conversation_deleted"){let A=new $e("conversation_deleted","This conversation was deleted");throw i({type:"error",error:A}),A}let M=new Error(h.error||"Failed to send message");throw i({type:"error",error:M}),M}if(!f.body){let h=new Error("No response body received");throw i({type:"error",error:h}),h}v(),i({type:"status",status:"connected"});try{await this.streamResponse(f.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 $e)&&!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?Sh(n):void 0,c=this.clientToolsFingerprintSessionId===e,p=i&&c&&this.lastSentClientToolsFingerprint===l,u=!i&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,g=!1,f;for(let v=0;;v++){if(f=await o({...i&&(g||!p)&&n?{clientTools:n}:{},...u?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),f.status===409&&v===0&&i&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,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(/\/+$/,"")||Ry}/resume`,l;s&&(l=(await this.initSession()).sessionId);let c={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(l&&(p.sessionId=l),s&&l){let u=[...xc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:g,commit:f}=await this.sendWithClientToolsDiff(l,u,v=>{let h={...p,...v};return this.debug&&console.debug("[AgentWidgetClient] client token resume",h),fetch(i,{method:"POST",headers:c,body:JSON.stringify(h),signal:o?.signal})},{emptyMeansReplace:!0});return g.ok&&f(),g}return fetch(i,{method:"POST",headers:c,body:JSON.stringify(p),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(pu).filter(u=>u.role==="user"||u.role==="assistant"||u.role==="system").filter(u=>!u.variant||u.variant==="assistant").sort((u,g)=>{let f=new Date(u.createdAt).getTime(),v=new Date(g.createdAt).getTime();return f-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=[...xc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let p=await this.buildContextAggregate(e);return p&&(l.context=p),l}async buildPayload(e,n){let o=e.slice().filter(pu).sort((u,g)=>{let f=new Date(u.createdAt).getTime(),v=new Date(g.createdAt).getTime();return f-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=[...xc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.buildContextAggregate(e);c&&(i.context=c);let p=this.normalizeComposerOptions(n);if(p&&(i.composerOptions=p),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 p=g=>{let f={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=f,s(f),f},u=g=>o.current?o.current:p(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)),p(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="",p=Date.now(),u=0,g=()=>p+u++,f=H=>{let ee=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,b=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,D=H.tools?H.tools.map(N=>({...N,chunks:N.chunks?[...N.chunks]:void 0})):void 0;return{...H,reasoning:ee,toolCall:b,tools:D}},v=H=>{if(H.role!=="assistant"||H.variant)return!0;let ee=Array.isArray(H.contentParts)&&H.contentParts.length>0,b=typeof H.rawContent=="string"&&H.rawContent.trim()!=="";return typeof H.content=="string"&&H.content.trim()!==""||ee||b||!!H.stopReason},h=H=>{v(H)&&n({type:"message",message:f(H)})},M=null,A=null,T={current:null},F={current:null},P=null,K="",x=new Map,L=new Map,w=new Map,O=new Map,G=new Map,ie={lastId:null,byStep:new Map},oe={lastId:null,byCall:new Map},S=H=>{if(H==null)return null;try{return String(H)}catch{return null}},_=H=>S(H.stepId??H.step_id??H.step??H.parentId??H.flowStepId??H.flow_step_id),R=H=>S(H.callId??H.call_id??H.requestId??H.request_id??H.toolCallId??H.tool_call_id??H.stepId??H.step_id),I=o,Y=!1,V=()=>{if(M)return M;let H,ee="",b=P;return!Y&&I?(H=I,Y=!0,ee=s??""):I&&b?H=`${I}_${b}`:H=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,M={id:H,role:"assistant",content:ee,createdAt:new Date().toISOString(),streaming:!0,sequence:g()},h(M),M},ae=(H,ee)=>{ie.lastId=ee,H&&ie.byStep.set(H,ee)},ce=(H,ee)=>{let b=H.reasoningId??H.id,D=_(H);if(b){let U=String(b);return ae(D,U),U}if(D){let U=ie.byStep.get(D);if(U)return ie.lastId=U,U}if(ie.lastId&&!ee)return ie.lastId;if(!ee)return null;let N=`reason-${g()}`;return ae(D,N),N},me=H=>{let ee=O.get(H);if(ee)return ee;let b={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:g(),reasoning:{id:H,status:"streaming",chunks:[]}};return O.set(H,b),h(b),b},Ce=(H,ee)=>{oe.lastId=ee,H&&oe.byCall.set(H,ee)},ue=new Set,_e=new Map,ct=new Set,we=new Map,$=H=>{if(!H)return!1;let ee=H.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},Pe=(H,ee)=>{let b=H.toolId??H.id,D=R(H);if(b){let U=String(b);return Ce(D,U),U}if(D){let U=oe.byCall.get(D);if(U)return oe.lastId=U,U}if(oe.lastId&&!ee)return oe.lastId;if(!ee)return null;let N=`tool-${g()}`;return Ce(D,N),N},Ne=H=>{let ee=G.get(H);if(ee)return ee;let b={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:g(),toolCall:{id:H,status:"pending"}};return G.set(H,b),h(b),b},xe=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let ee=Number(H);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let b=Date.parse(H);if(!Number.isNaN(b))return b}return Date.now()},Oe=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},ye=new Map,gt=new Map,Zn=new Map,Cs=(H,ee,b)=>{let D=Zn.get(H);D||(D=[],Zn.set(H,D));let N=0,U=D.length;for(;N<U;){let te=N+U>>>1;D[te].seq<ee?N=te+1:U=te}D[N]?.seq===ee?D[N]={seq:ee,text:b}:D.splice(N,0,{seq:ee,text:b});let Z="";for(let te=0;te<D.length;te++)Z+=D[te].text;return Z},Jt=(H,ee)=>{let b=Oe(ee),D=gt.get(H.id),N=Xx(D,b);H.rawContent=N;let U=ye.get(H.id),Z=qe=>{let Lt=H.content??"";qe.trim()!==""&&(Lt.trim().length===0||qe.startsWith(Lt)||qe.trimStart().startsWith(Lt.trim()))&&(H.content=qe)},te=()=>{if(U){let qe=U.close?.();qe instanceof Promise&&qe.catch(()=>{})}ye.delete(H.id),gt.delete(H.id),H.streaming=!1,h(H)};if(!U){Z(b),te();return}let le=ga(N);if(le!==null&&le.trim()!==""){Z(le),te();return}let Ae=qe=>{let Lt=typeof qe=="string"?qe:qe?.text??null;if(Lt!==null&&Lt.trim()!=="")return Lt;let Ct=U.getExtractedText();return Ct!==null&&Ct.trim()!==""?Ct:b},mt;try{mt=U.processChunk(N)}catch{Z(b),te();return}if(mt instanceof Promise){mt.then(qe=>{Z(Ae(qe)),te()}).catch(()=>{Z(b),te()});return}Z(Ae(mt)),te()},Fn=null,Io=(H,ee,b,D)=>{H.rawContent=ee,ye.has(H.id)||ye.set(H.id,this.createStreamParser());let N=ye.get(H.id),U=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(U&>.set(H.id,ee),N.__isPlainTextParser===!0){H.content=D!==void 0?ee:H.content+b,gt.delete(H.id),ye.delete(H.id),H.rawContent=void 0,h(H);return}let te=N.processChunk(ee);if(te instanceof Promise)te.then(le=>{let Ae=typeof le=="string"?le:le?.text??null;Ae!==null&&Ae.trim()!==""?(H.content=Ae,h(H)):!U&&!ee.trim().startsWith("<")&&(H.content=D!==void 0?ee:H.content+b,gt.delete(H.id),ye.delete(H.id),H.rawContent=void 0,h(H))}).catch(()=>{H.content=D!==void 0?ee:H.content+b,gt.delete(H.id),ye.delete(H.id),H.rawContent=void 0,h(H)});else{let le=typeof te=="string"?te:te?.text??null;le!==null&&le.trim()!==""?(H.content=le,h(H)):!U&&!ee.trim().startsWith("<")&&(H.content=D!==void 0?ee:H.content+b,gt.delete(H.id),ye.delete(H.id),H.rawContent=void 0,h(H))}},It=(H,ee)=>{let b=ee??H.content;if(b==null||b===""){H.streaming=!1,h(H);return}let N=gt.get(H.id)??Oe(b);H.rawContent=N;let U=ye.get(H.id),Z=null,te=!1;if(U&&(Z=U.getExtractedText(),Z===null&&(Z=ga(N)),Z===null)){let le=U.processChunk(N);le instanceof Promise?(te=!0,le.then(Ae=>{let mt=typeof Ae=="string"?Ae:Ae?.text??null;mt!==null&&(H.content=mt,H.streaming=!1,ye.delete(H.id),gt.delete(H.id),h(H))}).catch(()=>{})):Z=typeof le=="string"?le:le?.text??null}if(!te){Z!==null&&Z.trim()!==""?H.content=Z:gt.has(H.id)||(H.content=Oe(b));let le=ye.get(H.id);if(le){let Ae=le.close?.();Ae instanceof Promise&&Ae.catch(()=>{}),ye.delete(H.id)}gt.delete(H.id),H.streaming=!1,h(H)}},Pr=(H,ee,b)=>{let D=L.get(H);if(D)return D;let N={id:`nested-${ee}-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g(),...b?{variant:b}:{},...b==="reasoning"?{reasoning:{id:H,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return L.set(H,N),h(N),N},yn=[],po,xi=new Map,Ir=0,ln="agent",Ai=!1,xt=null,dt=null,eo=new Map,Va=this.config.iterationDisplay??"separate";for(po=()=>{for(let H=0;H<yn.length;H++){let ee=yn[H].payloadType,b=yn[H].payload;if(!Ai&&ln!=="flow"&&typeof b.stepType=="string"&&(ln="flow"),ee==="reasoning_start"){let D=typeof b.id=="string"?b.id:null,N=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(D&&N){x.set(D,N),Pr(D,N,"reasoning");continue}let U=ce(b,!0)??`reason-${g()}`,Z=me(U);Z.reasoning=Z.reasoning??{id:U,status:"streaming",chunks:[]},Z.reasoning.startedAt=Z.reasoning.startedAt??xe(b.startedAt??b.timestamp),Z.reasoning.completedAt=void 0,Z.reasoning.durationMs=void 0,(b.scope==="loop"||b.scope==="turn")&&(Z.reasoning.scope=b.scope),Z.streaming=!0,Z.reasoning.status="streaming",h(Z)}else if(ee==="reasoning_delta"){let D=typeof b.id=="string"?b.id:null;if(D&&x.has(D)&&L.has(D)){let te=L.get(D),le=b.reasoningText??b.text??b.delta??"";le&&b.hidden!==!0&&te.reasoning&&(te.reasoning.chunks.push(String(le)),h(te));continue}let N=ce(b,!1)??ce(b,!0)??`reason-${g()}`,U=me(N);U.reasoning=U.reasoning??{id:N,status:"streaming",chunks:[]},U.reasoning.startedAt=U.reasoning.startedAt??xe(b.startedAt??b.timestamp);let Z=b.reasoningText??b.text??b.delta??"";if(Z&&b.hidden!==!0){let te=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(te!==void 0){let le=Cs(N,te,String(Z));U.reasoning.chunks=[le]}else U.reasoning.chunks.push(String(Z))}if(U.reasoning.status=b.done?"complete":"streaming",b.done){U.reasoning.completedAt=xe(b.completedAt??b.timestamp);let te=U.reasoning.startedAt??Date.now();U.reasoning.durationMs=Math.max(0,(U.reasoning.completedAt??Date.now())-te)}U.streaming=U.reasoning.status!=="complete",h(U)}else if(ee==="reasoning_complete"){let D=typeof b.id=="string"?b.id:null;if(D&&x.has(D)&&L.has(D)){let le=L.get(D);if(le.reasoning){let Ae=typeof b.text=="string"?b.text:"";Ae&&le.reasoning.chunks.length===0&&le.reasoning.chunks.push(Ae),le.reasoning.status="complete",le.streaming=!1,h(le)}x.delete(D),L.delete(D);continue}let N=ce(b,!1)??ce(b,!0)??`reason-${g()}`,U=typeof b.text=="string"?b.text:"";!O.get(N)&&(U||b.scope==="loop")&&me(N);let Z=O.get(N);if(Z?.reasoning){(b.scope==="loop"||b.scope==="turn")&&(Z.reasoning.scope=b.scope),U&&Z.reasoning.chunks.length===0&&Z.reasoning.chunks.push(U),Z.reasoning.status="complete",Z.reasoning.completedAt=xe(b.completedAt??b.timestamp);let le=Z.reasoning.startedAt??Date.now();Z.reasoning.durationMs=Math.max(0,(Z.reasoning.completedAt??Date.now())-le),Z.streaming=!1,h(Z)}let te=_(b);te&&ie.byStep.delete(te)}else if(ee==="tool_start"){M&&(M.streaming=!1,h(M),M=null),typeof b.iteration=="number"&&(Ir=b.iteration);let D=(typeof b.toolCallId=="string"?b.toolCallId:void 0)??Pe(b,!0)??`tool-${g()}`,N=b.toolName??b.name;if($(N)){ue.add(D);continue}Ce(R(b),D);let U=Ne(D),Z=U.toolCall??{id:D,status:"pending"};Z.name=N??Z.name,Z.status="running",b.parameters!==void 0?Z.args=b.parameters:b.args!==void 0&&(Z.args=b.args),Z.startedAt=Z.startedAt??xe(b.startedAt??b.timestamp),Z.completedAt=void 0,Z.durationMs=void 0,U.toolCall=Z,U.streaming=!0,b.executionId&&(U.agentMetadata={executionId:b.executionId,iteration:b.iteration}),h(U)}else if(ee==="tool_output_delta"){let D=Pe(b,!1)??Pe(b,!0)??`tool-${g()}`;if(ue.has(D))continue;let N=Ne(D),U=N.toolCall??{id:D,status:"running"};U.startedAt=U.startedAt??xe(b.startedAt??b.timestamp);let Z=b.text??b.delta??b.message??"";Z&&(U.chunks=U.chunks??[],U.chunks.push(String(Z))),U.status="running",N.toolCall=U,N.streaming=!0;let te=b.agentContext;(te||b.executionId)&&(N.agentMetadata=N.agentMetadata??{executionId:te?.executionId??b.executionId,iteration:te?.iteration??b.iteration}),h(N)}else if(ee==="tool_complete"){let D=Pe(b,!1)??Pe(b,!0)??`tool-${g()}`;if(ue.has(D)){ue.delete(D);continue}let N=Ne(D),U=N.toolCall??{id:D,status:"running"};U.status="complete",b.result!==void 0&&(U.result=b.result),typeof b.duration=="number"&&(U.duration=b.duration),U.completedAt=xe(b.completedAt??b.timestamp);let Z=b.duration??b.executionTime;if(typeof Z=="number")U.durationMs=Z;else{let Ae=U.startedAt??Date.now();U.durationMs=Math.max(0,(U.completedAt??Date.now())-Ae)}N.toolCall=U,N.streaming=!1;let te=b.agentContext;(te||b.executionId)&&(N.agentMetadata=N.agentMetadata??{executionId:te?.executionId??b.executionId,iteration:te?.iteration??b.iteration}),h(N);let le=R(b);le&&oe.byCall.delete(le)}else if(ee==="await"&&b.toolName){let D=typeof b.toolCallId=="string"&&b.toolCallId.length>0?b.toolCallId:void 0,N=D??b.toolId??`local-${g()}`,U=Ne(N),Z=b.toolName,te=b.origin==="webmcp"&&!Xs(Z)?`webmcp:${Z}`:Z,le=Xs(te),Ae=U.toolCall??{id:N,status:"pending"};Ae.name=te,Ae.args=b.parameters,Ae.status=le?"running":"complete",Ae.chunks=Ae.chunks??[],Ae.startedAt=Ae.startedAt??xe(b.startedAt??b.timestamp??b.awaitedAt),le?(Ae.completedAt=void 0,Ae.duration=void 0,Ae.durationMs=void 0):Ae.completedAt=Ae.completedAt??Ae.startedAt,U.toolCall=Ae,U.streaming=!1,U.agentMetadata={...U.agentMetadata,executionId:b.executionId??U.agentMetadata?.executionId,awaitingLocalTool:!0,...D?{webMcpToolCallId:D}:{}},h(U)}else if(ee==="text_start"){let D=typeof b.id=="string"?b.id:null,N=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(D&&N){x.set(D,N);continue}let U=M;U&&(ln==="flow"?(It(U),Fn=U):(U.streaming=!1,h(U)),M=null),P=typeof b.id=="string"?b.id:P,K=""}else if(ee==="text_delta"){let D=typeof b.id=="string"?b.id:null,N=D?x.get(D):void 0;if(D&&N){let Z=typeof b.delta=="string"?b.delta:"",te=(w.get(D)??"")+Z;if(w.set(D,te),te.trim()==="")continue;let le=Pr(D,N);le.agentMetadata={...le.agentMetadata,executionId:b.executionId,parentToolId:N},Io(le,te,Z,void 0);continue}if(P=typeof b.id=="string"?b.id:P,ln==="flow"){let Z=typeof b.delta=="string"?b.delta:"";if(K+=Z,K.trim()==="")continue;let te=V();te.agentMetadata={executionId:b.executionId,iteration:b.iteration},Io(te,K,Z,void 0),A=te;continue}let U=V();U.content+=b.delta??"",U.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:xt??void 0,agentName:dt?.agentName},A=U,h(U)}else if(ee==="text_complete"){let D=typeof b.id=="string"?b.id:null;if(D&&x.has(D)){let U=L.get(D);U&&It(U),x.delete(D),w.delete(D),L.delete(D);continue}let N=M;N&&(ln==="flow"?(It(N),Fn=N):((N.content??"")===""&&typeof b.text=="string"&&(N.content=b.text),N.streaming=!1,h(N)),M=null),P=null,K=""}else if(ee==="step_complete"){let D=b.stepType,N=b.executionType;if(D==="tool"||N==="context")continue;if(b.success===!1){let U=b.error,Z=typeof U=="string"&&U!==""?U:U!=null&&typeof U=="object"&&Reflect.has(U,"message")?String(U.message??"Step failed"):"Step failed";n({type:"error",error:new Error(Z)});let te=M;te&&te.streaming&&(te.streaming=!1,h(te)),n({type:"status",status:"idle"});continue}{let U=Fn;Fn=null;let Z=b.stopReason,te=b.result?.response;if(U)Z&&(U.stopReason=Z),te!=null?Jt(U,te):U.streaming!==!1&&(ye.delete(U.id),gt.delete(U.id),U.streaming=!1,h(U));else{let le=te!=null&&te!=="";if(le||Z){let Ae=V();Z&&(Ae.stopReason=Z),le?It(Ae,te):(Ae.streaming=!1,h(Ae))}}continue}}else if(ee==="execution_start")ln=b.kind==="flow"?"flow":"agent",Ai=!0,ln==="agent"&&(dt={executionId:b.executionId,agentId:b.agentId??"virtual",agentName:b.agentName??"",status:"running",currentIteration:0,maxTurns:b.maxTurns??1,startedAt:xe(b.startedAt)});else if(ee==="turn_start"){let D=typeof b.iteration=="number"?b.iteration:Ir;if(D!==Ir){if(dt&&(dt.currentIteration=D),Va==="separate"&&D>1){let N=M;N&&(N.streaming=!1,h(N),eo.set(D-1,N),M=null)}Ir=D}xt=typeof b.id=="string"?b.id:null,A=null}else if(ee==="tool_input_delta"){let D=b.toolCallId??oe.lastId;if(D){let N=G.get(D);N?.toolCall&&(N.toolCall.chunks=N.toolCall.chunks??[],N.toolCall.chunks.push(b.delta??""),h(N))}}else{if(ee==="tool_input_complete")continue;if(ee==="turn_complete"){let D=b.stopReason,N=M??A;if(D&&N!==null){let U=b.id;(!U||N.agentMetadata?.turnId===U)&&(N.stopReason=D,h(N))}xt===b.id&&(xt=null)}else if(ee==="media_start"){let D=String(b.id);xi.set(D,{mediaType:typeof b.mediaType=="string"?b.mediaType:void 0,role:typeof b.role=="string"?b.role:void 0,toolCallId:b.toolCallId,parts:[]})}else if(ee==="media_delta"){let D=xi.get(String(b.id));D&&typeof b.delta=="string"&&D.parts.push(b.delta)}else if(ee==="media_complete"){let D=String(b.id),N=xi.get(D);xi.delete(D);let U=(typeof b.mediaType=="string"?b.mediaType:void 0)??N?.mediaType??"application/octet-stream",Z=typeof b.data=="string"?b.data:void 0,te=typeof b.url=="string"?b.url:N&&N.parts.length>0?N.parts.join(""):void 0,le=null;if(Z)le={type:"media",data:Z,mediaType:U};else if(te){let Lt=U.toLowerCase();le={type:Lt==="image"||Lt.startsWith("image/")?"image-url":"file-url",url:te,mediaType:U}}let Ae=b.toolCallId??N?.toolCallId,mt=le?[le]:[],qe=[];for(let Lt of mt){if(!Lt||typeof Lt!="object")continue;let Ct=Lt,Lr=typeof Ct.type=="string"?Ct.type:void 0,En=typeof Ct.mediaType=="string"?Ct.mediaType.toLowerCase():"",Nt=null,cn="";if(Lr==="media"){let tn=typeof Ct.data=="string"?Ct.data:void 0;if(!tn)continue;cn=En.length>0?En:"application/octet-stream",Nt=`data:${cn};base64,${tn}`}else if(Lr==="image-url"){let tn=typeof Ct.url=="string"?Ct.url:void 0;if(!tn)continue;cn=En,Nt=tn}else if(Lr==="file-url"){let tn=typeof Ct.url=="string"?Ct.url:void 0;if(!tn)continue;cn=En,Nt=tn}else continue;if(Nt)if(Lr==="image-url"||cn.startsWith("image/"))qe.push({type:"image",image:Nt,...cn.includes("/")?{mimeType:cn}:{}});else if(cn.startsWith("audio/"))qe.push({type:"audio",audio:Nt,mimeType:cn});else if(cn.startsWith("video/"))qe.push({type:"video",video:Nt,mimeType:cn});else{let tn=cn||"application/octet-stream";qe.push({type:"file",data:Nt,mimeType:tn,filename:Qx(tn)})}}if(qe.length>0){let Lt=g(),Ct=Ae,En={id:`agent-media-${typeof Ct=="string"&&Ct.length>0?`${Ct}-${Lt}`:String(Lt)}`,role:"assistant",content:"",contentParts:qe,createdAt:new Date().toISOString(),streaming:!1,sequence:Lt,agentMetadata:{executionId:b.executionId,iteration:typeof b.iteration=="number"?b.iteration:Ir}};h(En);let Nt=M;Nt&&(Nt.streaming=!1,h(Nt)),M=null,T.current=null}}else if(ee==="execution_complete"){let D=b.kind??ln;D==="agent"&&dt&&(dt.status=b.success?"complete":"error",dt.completedAt=xe(b.completedAt),dt.stopReason=b.stopReason);let N=M;N&&(D==="flow"&&N.streaming!==!1?It(N):(N.streaming=!1,h(N)),M=null),P=null,K="",Fn=null,n({type:"status",status:"idle",terminal:!0})}else if(ee==="execution_error"){let D=typeof b.error=="string"?b.error:b.error?.message??"Execution error";n({type:"error",error:new Error(D)})}else if(ee!=="ping"){if(ee==="approval_start"){let D=b.approvalId??`approval-${g()}`,N={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:g(),approval:{id:D,status:"pending",agentId:dt?.agentId??"virtual",executionId:b.executionId??dt?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};h(N)}else if(ee==="step_await"&&b.awaitReason==="approval_required"){let D=b.approvalId??`approval-${g()}`,N={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:g(),approval:{id:D,status:"pending",agentId:dt?.agentId??"virtual",executionId:b.executionId??dt?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};h(N)}else if(ee==="approval_complete"){let D=b.approvalId;if(D){let U={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:g(),approval:{id:D,status:b.decision??"approved",agentId:dt?.agentId??"virtual",executionId:b.executionId??dt?.executionId??"",toolName:b.toolName??"",description:b.description??"",resolvedAt:Date.now()}};h(U)}}else if(ee==="artifact_start"||ee==="artifact_delta"||ee==="artifact_update"||ee==="artifact_complete"){if(ee==="artifact_start"){let D=b.artifactType,N=String(b.id),U=typeof b.title=="string"?b.title:void 0,Z=b.file,te;Z&&typeof Z=="object"&&!Array.isArray(Z)&&typeof Z.path=="string"&&typeof Z.mimeType=="string"&&(te={path:Z.path,mimeType:Z.mimeType,...typeof Z.language=="string"?{language:Z.language}:{}}),n({type:"artifact_start",id:N,artifactType:D,title:U,component:typeof b.component=="string"?b.component:void 0,...te?{file:te}:{}});let le=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?{...b.props}:void 0;if(we.set(N,{markdown:"",title:U,file:te,...le?{props:le}:{}}),!ct.has(N)){ct.add(N);let Ae=wr(this.config.features?.artifacts,{artifactType:D,...te?{file:te}:{}}),mt=typeof b.component=="string"?b.component:void 0,qe={id:`artifact-ref-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g(),rawContent:ba(Ae,{artifactId:N,title:U,artifactType:D,status:"streaming",...te?{file:te}:{},...mt?{component:mt}:{}})};_e.set(N,qe),h(qe)}}else if(ee==="artifact_delta"){let D=String(b.id),N=typeof b.delta=="string"?b.delta:String(b.delta??"");n({type:"artifact_delta",id:D,artDelta:N});let U=we.get(D);U&&(U.markdown+=N)}else if(ee==="artifact_update"){let D=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};n({type:"artifact_update",id:String(b.id),props:D,component:typeof b.component=="string"?b.component:void 0});let N=we.get(String(b.id));N&&(N.props={...N.props??{},...D})}else if(ee==="artifact_complete"){let D=String(b.id);n({type:"artifact_complete",id:D});let N=_e.get(D);if(N){N.streaming=!1;try{let U=JSON.parse(N.rawContent??"{}");if(U.props){U.props.status="complete";let Z=we.get(D);Z?.markdown&&(U.props.markdown=Z.markdown),Z?.file&&(U.props.file=Z.file),U.component==="PersonaArtifactInline"&&Z?.props&&Object.keys(Z.props).length>0&&(U.props.componentProps=Z.props)}N.rawContent=JSON.stringify(U)}catch{}we.delete(D),h(N),_e.delete(D)}}}else if(ee==="transcript_insert"){let D=b.message;if(!D||typeof D!="object")continue;let N=String(D.id??`msg-${g()}`),U=D.role,te={id:N,role:U==="user"?"user":U==="system"?"system":"assistant",content:typeof D.content=="string"?D.content:"",rawContent:typeof D.rawContent=="string"?D.rawContent:void 0,createdAt:typeof D.createdAt=="string"?D.createdAt:new Date().toISOString(),streaming:D.streaming===!0,...typeof D.variant=="string"?{variant:D.variant}:{},sequence:g()};if(h(te),te.rawContent)try{let Ae=JSON.parse(te.rawContent)?.props?.artifactId;typeof Ae=="string"&&ct.add(Ae)}catch{}M=null,T.current=null,ye.delete(N),gt.delete(N)}else if(ee==="error"){if(b.recoverable===!1&&b.error!=null&&b.error!==""){let D=typeof b.error=="string"?b.error:b.error?.message!=null?String(b.error.message):"Execution error";n({type:"error",error:new Error(D)});let N=M;N&&N.streaming&&(N.streaming=!1,h(N)),n({type:"status",status:"idle"})}}else if(ee==="step_error"||ee==="dispatch_error"||ee==="flow_error"){let D=null;if(b.error instanceof Error)D=b.error;else if(ee==="dispatch_error"){let N=b.message??b.error;N!=null&&N!==""&&(D=new Error(String(N)))}else{let N=b.error;typeof N=="string"&&N!==""?D=new Error(N):N!=null&&typeof N=="object"&&Reflect.has(N,"message")&&(D=new Error(String(N.message??N)))}if(D){n({type:"error",error:D});let N=M;N&&N.streaming&&(N.streaming=!1,h(N)),n({type:"status",status:"idle"})}}}}}yn.length=0};;){let{done:H,value:ee}=await i.read();if(H)break;c+=l.decode(ee,{stream:!0});let b=c.split(`
|
|
4
4
|
|
|
5
5
|
`);c=b.pop()??"";for(let D of b){let N=D.split(`
|
|
6
|
-
`),U="message",Z="",te=null;for(let qe of N)qe.startsWith("event:")?U=qe.replace("event:","").trim():qe.startsWith("data:")?Z+=qe.replace("data:","").trim():qe.startsWith("id:")&&(te=qe.slice(3).trim());let le=()=>{te!==null&&te!==""&&n({type:"cursor",id:te})};if(!Z){le();continue}let Ae;try{Ae=JSON.parse(Z)}catch(qe){n({type:"error",error:qe instanceof Error?qe:new Error("Failed to parse chat stream payload")});continue}let mt=U!=="message"?U:Ae.type??"message";if(this.onSSEEvent?.(mt,Ae),this.parseSSEEvent){T.current=M;let qe=await this.handleCustomSSEEvent(Ae,n,T,h,g,F);if(T.current&&T.current!==M&&(M=T.current),qe){le();continue}}yn.push({payloadType:mt,payload:Ae}),po(),le()}}po()}};var
|
|
6
|
+
`),U="message",Z="",te=null;for(let qe of N)qe.startsWith("event:")?U=qe.replace("event:","").trim():qe.startsWith("data:")?Z+=qe.replace("data:","").trim():qe.startsWith("id:")&&(te=qe.slice(3).trim());let le=()=>{te!==null&&te!==""&&n({type:"cursor",id:te})};if(!Z){le();continue}let Ae;try{Ae=JSON.parse(Z)}catch(qe){n({type:"error",error:qe instanceof Error?qe:new Error("Failed to parse chat stream payload")});continue}let mt=U!=="message"?U:Ae.type??"message";if(this.onSSEEvent?.(mt,Ae),this.parseSSEEvent){T.current=M;let qe=await this.handleCustomSSEEvent(Ae,n,T,h,g,F);if(T.current&&T.current!==M&&(M=T.current),qe){le();continue}}yn.push({payloadType:mt,payload:Ae}),po(),le()}}po()}};var Jx=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function Zx(t){let e=t?.text?.trim()??"";return e?Lh(Jx(t),e):""}function qy(t){let e=Zx(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[Eo(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
|
|
7
7
|
|
|
8
|
-
`)}:{}}function Tc(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function
|
|
8
|
+
`)}:{}}function Tc(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function zy(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 uu(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 jy(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 uu(t,n.id)?n.id:null}return null}function gu(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 mu(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 Ma=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):mu(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 kc=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 eA=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Vy(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:eA()}catch{return!1}}var{setLoader:Pk,load:tA}=Pt({fallbackImport:()=>import("./voice-runtime-EFR3R5ES.js")});var fu=tA;function hu(t){if(!t)return"";let e=nA(t);return Ky(e!==null?e:t)}function nA(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 Ky(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
|
|
10
|
+
`),e.trim()}var Gy=null;var yu=()=>Gy?Gy():import("./runtype-tts-entry-UJAEF7NZ.js");var{setLoader:Wk,load:oA}=Pt({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var Qy=oA;var rA=["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 sA(t,e){return rA.some(n=>t[n]!==e[n])}var To=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function bu(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 bu=t=>({isError:!0,content:[{type:"text",text:t}]}),sA=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Qy=t=>Xs(t)||t===Ar,Pc=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.ttsSpokenMessageIds=new Set;this.readAloud=new kc(()=>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&&(Xs(n.name)||n.name===Ar&&Mr(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.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 Aa(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&&mu().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||hu().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 jy(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.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=Ma.isSupported()?new Ma({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 hu().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:p})=>{let u=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new p(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");let o=++this.voiceSetupGeneration;this.voiceSetupPromise=mu().then(s=>{o===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{o===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let o=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,i,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=c.id}if(l){this.pendingVoiceUserMessageId=null;let c=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=c.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let c=this.injectMessage({role:"assistant",content:i,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=c.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(s=>{this.voiceLevel=Number.isFinite(s)?Math.max(0,Math.min(1,s)):0}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:o,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),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(){this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}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.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 To("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 us("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 To("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 To("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.historyOpenEpoch)throw c.discard(),new To("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 p of l.messages)this.acknowledgedProjections.set(p.id,p.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}`,p=this.olderPageRequests.get(c);if(p)return p;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=xa(this.messages,l.messages);this.messages=this.sortMessages(c.map(p=>this.ensureSequence(p))),this.historyNextMessageCursor=l.nextCursor;for(let p of l.messages)this.acknowledgedProjections.set(p.id,p.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 To("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 To("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 To("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 To("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.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(f=>f.id)),p=this.messages.some(f=>c.has(f.id)),u=l.messages[0]?.createdAt,g;if(!p)g=l.messages.map(f=>this.ensureSequence(f));else{let f=this.resumable?this.activeAssistantMessageId:null,v=this.messages.filter(h=>c.has(h.id)||h.id===f?!0:u!==void 0&&h.createdAt<u);g=xa(v,l.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=l.nextCursor,this.activeConversationRevision=l.conversationRevision||s||null,this.acknowledgedProjections.clear();for(let f of l.messages)this.acknowledgedProjections.set(f.id,f.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=Sa(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=Sa(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 $e&&(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 $e?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 $e&&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=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!rA(this.config,o)){this.config=o,this.client.updateConfig(o),s&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let i=this.client.getSSEEventCallback();this.config=o,this.client=new Aa(this.config,this.historyInternals),s&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),i&&this.client.setSSEEventCallback(i)}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:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=e,h={id:l??(n==="user"?vc():n==="assistant"?ei():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};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:p,createdAt:u,sequence:g,streaming:f=!1,voiceProcessing:v,rawContent:h}=o,A={id:p??(s==="user"?vc():s==="assistant"?ei():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:u??new Date().toISOString(),sequence:g??this.nextSequence(),streaming:f,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...v!==void 0&&{voiceProcessing:v},...h!==void 0&&{rawContent:h}};n.push(A)}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:p}=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},...p!==void 0&&{sequence:p}})}async applyMentionBundle(e,n,o){let s;try{s=await o()}catch{return}let i=s.blocks.join(`
|
|
12
|
+
_Details: ${n.message}_`:o}var vu=t=>({isError:!0,content:[{type:"text",text:t}]}),iA=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Yy=t=>Xs(t)||t===Ar,Pc=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.ttsSpokenMessageIds=new Set;this.readAloud=new kc(()=>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&&(Xs(n.name)||n.name===Ar&&Mr(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.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 Aa(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&&fu().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||yu().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 Vy(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.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=Ma.isSupported()?new Ma({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 yu().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:p})=>{let u=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new p(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");let o=++this.voiceSetupGeneration;this.voiceSetupPromise=fu().then(s=>{o===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{o===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let o=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,i,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=c.id}if(l){this.pendingVoiceUserMessageId=null;let c=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=c.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let c=this.injectMessage({role:"assistant",content:i,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=c.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(s=>{this.voiceLevel=Number.isFinite(s)?Math.max(0,Math.min(1,s)):0}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:o,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),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(){this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}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.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 To("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 us("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 To("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 To("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.historyOpenEpoch)throw c.discard(),new To("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 p of l.messages)this.acknowledgedProjections.set(p.id,p.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}`,p=this.olderPageRequests.get(c);if(p)return p;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=xa(this.messages,l.messages);this.messages=this.sortMessages(c.map(p=>this.ensureSequence(p))),this.historyNextMessageCursor=l.nextCursor;for(let p of l.messages)this.acknowledgedProjections.set(p.id,p.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 To("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 To("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 To("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 To("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.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(f=>f.id)),p=this.messages.some(f=>c.has(f.id)),u=l.messages[0]?.createdAt,g;if(!p)g=l.messages.map(f=>this.ensureSequence(f));else{let f=this.resumable?this.activeAssistantMessageId:null,v=this.messages.filter(h=>c.has(h.id)||h.id===f?!0:u!==void 0&&h.createdAt<u);g=xa(v,l.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=l.nextCursor,this.activeConversationRevision=l.conversationRevision||s||null,this.acknowledgedProjections.clear();for(let f of l.messages)this.acknowledgedProjections.set(f.id,f.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=Sa(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=Sa(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 $e&&(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 $e?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 $e&&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=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!sA(this.config,o)){this.config=o,this.client.updateConfig(o),s&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let i=this.client.getSSEEventCallback();this.config=o,this.client=new Aa(this.config,this.historyInternals),s&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),i&&this.client.setSSEEventCallback(i)}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:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=e,h={id:l??(n==="user"?vc():n==="assistant"?ei():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};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:p,createdAt:u,sequence:g,streaming:f=!1,voiceProcessing:v,rawContent:h}=o,A={id:p??(s==="user"?vc():s==="assistant"?ei():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:u??new Date().toISOString(),sequence:g??this.nextSequence(),streaming:f,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...v!==void 0&&{voiceProcessing:v},...h!==void 0&&{rawContent:h}};n.push(A)}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:p}=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},...p!==void 0&&{sequence:p}})}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,p=s.contentParts.length>0;if(c){let u=[];i&&u.push(Eo(i)),u.push(...s.contentParts),u.push(...e.contentParts),e.contentParts=u}else if(p){let u=[];l&&u.push(Eo(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=vc(),l=ei();this.activeAssistantMessageId=null;let c=n?.contentParts&&Ac(n.contentParts)?ii:"",p={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(p),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,n?.mentions){let f=this.messages.find(v=>v.id===i)??p;if(await this.applyMentionBundle(f,o,n.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let f=this.messages.find(h=>h.id===i)??p,v=$y({quote:n.quote,text:f.llmContent??f.content,contentParts:f.contentParts});v.contentParts&&(f.contentParts=v.contentParts),v.llmContent!==void 0&&(f.llmContent=v.llmContent),(v.contentParts||v.llmContent!==void 0)&&(f.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(f){if(this.status==="resuming"||this.reconnecting)return;let v=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));if(!v){let h=yu(f,this.config.errorMessage);if(h){let M={id:l,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(f instanceof Error?this.callbacks.onError?.(f):this.callbacks.onError?.(new Error(String(f))))}}resubmitFrom(e,n){let o=qy(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,f=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]}:{},...f?.length?{contentSegments:[...f]}:{},...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=ei();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=yu(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 p=this.config.approval,u=p&&typeof p=="object"?p.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 f=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}`)}f=g.body}else g instanceof ReadableStream&&(f=g);f?await this.connectStream(f,{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 f=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||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,f=Array.isArray(g?.questions)?g.questions:[];if(f.length===1){let v=typeof f[0]?.question=="string"?f[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,p=e.toolCall?.args,u=Array.isArray(p?.questions)?p.questions:[];if(u.length===0){let g=typeof n=="string"?n:Object.entries(n).map(([f,v])=>`${f}: ${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((f,v)=>{let h=typeof f?.question=="string"?f.question:"";if(!h)return;let M=g[h],A=Array.isArray(M)?M.join(", "):typeof M=="string"?M:"";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:A||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let g=await this.client.resumeFlow(s,{[i]:n});if(!g.ok){let f=await g.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${g.status}`)}g.body?await this.connectStream(g.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(g){let f=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||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!==Ar?!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=await Promise.all(n.map(async c=>{let p=c.toolCall?.name,u=c.toolCall?.id;if(!p||!u)return null;let g=`${e}:${u}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(g),o.push(g);let f=this.markWebMcpToolRunning(c),v=c.agentMetadata?.webMcpToolCallId??p;if(p===Ar)return{dedupeKey:g,resumeKey:v,output:Cy(),toolMessage:c,startedAt:f,completedAt:Date.now()};let h=this.client.executeWebMcpToolCall(p,c.toolCall?.args,s.signal),M;if(!h)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await h}catch(A){let T=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));return T||this.callbacks.onError?.(A instanceof Error?A:new Error(String(A))),this.markWebMcpToolComplete(c,bu(T?"Aborted by cancel()":sA(A)),f),this.webMcpInflightKeys.delete(g),null}return s.signal.aborted?(this.markWebMcpToolComplete(c,bu("Aborted by cancel()"),f),this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:v,output:M,toolMessage:c,startedAt:f,completedAt:Date.now()}})),l=[];try{if(l=i.filter(u=>u!==null),l.length===0)return;let c={};for(let u of l)c[u.resumeKey]=u.output;let p=await this.client.resumeFlow(e,c,{signal:s.signal});if(!p.ok){let u=await p.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${p.status}`)}for(let u of l)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===Ar?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,bu("Aborted by cancel()"),u.startedAt)}finally{for(let c of o)this.webMcpInflightKeys.delete(c);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 step_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 step_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});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=wr(this.config.features?.artifacts,e),s=ba(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=wr(this.config.features?.artifacts,n),i=ba(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=Gy().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=>yu(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=ei(),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=fu(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return gu(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=fu(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,f=n.approval;l.approval={...g,...f,executionId:f.executionId||g.executionId,toolName:f.toolName||g.toolName,description:f.description||g.description,toolType:f.toolType??g.toolType,reason:f.reason??g.reason,parameters:f.parameters??g.parameters}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,u=n.toolCall?.id;if(c&&Qy(c)&&p&&u&&n.agentMetadata?.awaitingLocalTool===!0){let g=`${p}:${u}`,f=this.webMcpInflightKeys.has(g),v=this.webMcpResolvedKeys.has(g),h=s.toolCall?.name,M=s.agentMetadata?.executionId===p&&s.toolCall?.id===u&&h!==void 0&&Qy(h)&&s.toolCall?.status==="complete";(f||v||M)&&(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 iA,FileCode as aA,FileSpreadsheet as lA,FileText as vu,X as cA}from"lucide";var dA={add:t=>Ty(t)},pA=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Ic={allowedTypes:Qo,maxFileSize:10*1024*1024,maxFiles:4};function uA(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function gA(t){return t==="application/pdf"?vu:t.startsWith("text/")?vu:t.includes("word")?vu:t.includes("excel")||t.includes("spreadsheet")?lA:t==="application/json"?aA:iA}var Ea=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Ic.allowedTypes,maxFileSize:e.maxFileSize??Ic.maxFileSize,maxFiles:e.maxFiles??Ic.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:dA}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:Ic.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=ky(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:uA(),file:o,previewUrl:Mc(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=pA(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=Mc(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 f=gA(e.file.type),v=en(f,20,"var(--persona-muted, #6b7280)",1.5);v&&g.appendChild(v);let h=k("span");h.textContent=Py(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=Q("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=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=he("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 p=k("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");p.type="button",p.setAttribute("aria-label","Remove attachment"),p.style.position="absolute",p.style.top="-4px",p.style.insetInlineEnd="-4px",p.style.width="18px",p.style.height="18px",p.style.borderRadius="50%",p.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",p.style.border="none",p.style.cursor="pointer",p.style.display="flex",p.style.alignItems="center",p.style.justifyContent="center",p.style.padding="0";let u=en(cA,10,"var(--persona-text-inverse, #ffffff)",2);u?p.appendChild(u):(p.textContent="\xD7",p.style.color="var(--persona-text-inverse, #ffffff)",p.style.fontSize="14px",p.style.lineHeight="1"),p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(p),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 Yy=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),mA=(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 Xy(){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(f=>Object.freeze({...f}))),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),p=()=>{if(o=!1,s||e.size===0)return;let g=c();for(let f of[...e])try{f(g)}catch(v){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",v)}},u=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(p))};return{getState:c,subscribe:g=>(e.add(g),()=>e.delete(g)),setText:g=>{t.text!==g&&(t.text=g,u())},setAttachments:g=>{mA(t.attachments,g)||(t.attachments=[...g],u())},setMentionRefs:g=>{Yy(t.mentionRefs,g)||(t.mentionRefs=[...g],u())},setSelectedModelId:g=>{t.selectedModelId!==g&&(t.selectedModelId=g,u())},setActiveModeIds:g=>{Yy(t.activeModeIds,g)||(t.activeModeIds=[...g],u())},setQuote:g=>{let f=t.quote;f?.text===g?.text&&f?.messageId===g?.messageId&&f?.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&&p()},destroy:()=>{s=!0,o=!1,e.clear()}}}var Mn=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},Jy=(t,e)=>{let n=k("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Zy(t,e={}){let n=Mn(t,"[data-persona-composer-form]"),o=Mn(t,"[data-persona-composer-input]");if(!n||!o){let F=`[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(F);return typeof console<"u"&&console.warn(F),null}let s={header:Mn(t,"[data-persona-composer-header]"),body:Mn(t,"[data-persona-composer-body]"),actionsStart:Mn(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Mn(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Mn(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Mn(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Mn(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=Jy("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,p=(T,F,P,K,x)=>{if(F)return F;i.add(T);let L=Jy(P,K);return x.appendChild(L),L},u=p("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),g=p("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),f=p("suggestions",s.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),v=p("status",s.status,"persona-widget-composer__status","data-persona-composer-status",t),h=[],M=(T,F)=>T.target===F.target&&T.type===F.type&&T.handler===F.handler,A=Mn(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:f,status:v,attachmentInput:A,attachmentPreviews:Mn(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Mn(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Mn(t,"[data-persona-composer-submit]")??void 0,micButton:Mn(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(T,F,P,K)=>{T.addEventListener(F,P,K),h.push({target:T,type:F,handler:P,options:K})},removeListener:(T,F,P,K)=>{T.removeEventListener(F,P,K),h=h.filter(x=>!M(x,{target:T,type:F,handler:P}))},destroy:()=>{for(let T of h)T.target.removeEventListener(T.type,T.handler,T.options);h=[]}}}var fA=8,hA=8,Cu=10,eb=200,tb=300,nb=0,Hc=t=>Math.max(0,t);function ob(t){t.delayMs!==void 0&&(eb=Hc(t.delayMs)),t.skipDelayMs!==void 0&&(tb=Hc(t.skipDelayMs))}var yA=()=>Date.now()<nb,bA=t=>{nb=t>0?Date.now()+t:0},Lc=new WeakMap,Su="data-persona-tooltip-suppressed",vA=t=>typeof t.closest=="function"&&t.closest(`[${Su}]`)!==null;function rb(t){Lc.get(t)?.hide()}var sb=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,CA=t=>{let e=t.getRootNode?.();return sb(e)?e:t.ownerDocument.body},wu=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),wA=[...["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 Yt(t){Lc.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:s,enabled:i=!0,gap:l=fA,viewportPadding:c=hA}=t,p=()=>e.ownerDocument,u=()=>p().defaultView??window,g=null,f=null,v=null,h=null,M,A=!1,T=!1,F=!1,P=()=>(typeof o=="function"?o():o).trim(),K=()=>(typeof s=="function"?s():s??"").trim(),x=()=>Hc(t.delayMs??eb),L=()=>Hc(t.skipDelayMs??tb),w=()=>{M!==void 0&&(u().clearTimeout(M),M=void 0)},_=()=>{w();let me=g!==null;h?.(),h=null,g?.remove(),g=null,f=null,v=null,me&&bA(L())},G=()=>{if(!g)return;let me=p(),we=u(),ue=e.getBoundingClientRect(),_e=g.getBoundingClientRect(),ct=me.documentElement.clientWidth||we.innerWidth,Ce=me.documentElement.clientHeight||we.innerHeight,$=ct-c-_e.width,Pe=ue.left+ue.width/2-_e.width/2,Ne=wu(Pe,c,$),xe=ue.top-c,Oe=Ce-c-ue.bottom,ye=_e.height+l,gt=xe>=ye||xe>=Oe?"top":"bottom",Zn=gt==="top"?ue.top-l-_e.height:ue.bottom+l,Cs=Ce-c-_e.height,Jt=wu(Zn,c,Cs),Fn=ue.left+ue.width/2,Io=Math.max(Cu,_e.width-Cu),It=wu(Fn-Ne,Cu,Io);g.dataset.placement=gt,g.style.left=`${Ne}px`,g.style.top=`${Jt}px`,g.style.setProperty("--persona-tooltip-arrow-x",`${It}px`)},ie=()=>{if(F||!i||g||!e.isConnected||vA(e))return;let me=P(),we=CA(e);if(!me||!we)return;let ue=p(),_e=u();g=ue.createElement("div"),g.className="persona-control-tooltip",g.setAttribute("role","tooltip"),g.dataset.state="measuring",g.style.zIndex=String(gc);let ct=_e.getComputedStyle?.(e);if(ct){for(let ye of wA){let gt=ct.getPropertyValue(ye).trim();gt&&g.style.setProperty(ye,gt)}ct.fontFamily&&(g.style.fontFamily=ct.fontFamily)}f=ue.createElement("span"),f.className="persona-control-tooltip__label",f.textContent=me,g.appendChild(f);let Ce=K();Ce&&(v=ue.createElement("span"),v.className="persona-control-tooltip__hint",v.textContent=Ce,g.appendChild(v));let $=ue.createElement("span");$.className="persona-control-tooltip__arrow",g.appendChild($),we.appendChild(g),G(),g.dataset.state="open";let Pe=()=>{if(!e.isConnected){_();return}f&&(f.textContent=P()),v&&(v.textContent=K()),G()};_e.addEventListener("scroll",Pe,!0),_e.addEventListener("resize",Pe);let Ne=e.getRootNode(),xe=sb(Ne)?Ne:ue.documentElement,Oe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||_()});Oe?.observe(xe,{childList:!0,subtree:!0}),h=()=>{_e.removeEventListener("scroll",Pe,!0),_e.removeEventListener("resize",Pe),Oe?.disconnect()}},oe=me=>{if(!(F||g)){if(w(),me||x()<=0||yA()){ie();return}M=u().setTimeout(()=>{M=void 0,ie()},x())}},S=()=>{A||T?oe(T):_()},O=()=>{let me=u();(!me.matchMedia||!me.matchMedia("(hover: none)").matches)&&(A=!0,S())},R=()=>{A=!1,S()},I=()=>{try{T=e.matches(":focus-visible")}catch{T=!0}S()},Y=()=>{T=!1,S()},V=()=>{A=!1,T=!1,_()},ae=me=>{me.key==="Escape"&&V()};n.addEventListener("mouseenter",O),n.addEventListener("mouseleave",R),e.addEventListener("focus",I),e.addEventListener("blur",Y),e.addEventListener("keydown",ae),e.addEventListener("click",V);let ce={get isOpen(){return g!==null},show:ie,hide:_,reposition:G,destroy:()=>{F||(F=!0,_(),n.removeEventListener("mouseenter",O),n.removeEventListener("mouseleave",R),e.removeEventListener("focus",I),e.removeEventListener("blur",Y),e.removeEventListener("keydown",ae),e.removeEventListener("click",V),Lc.delete(e))}};return Lc.set(e,ce),ce}var ib=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];ib(i)&&ib(s)?n[o]=ai(i,s):n[o]=s}return n}var Yo="min(440px, calc(100vw - 24px))",lb="440px",xu="How can I help...",SA={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:Yo,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:SA,copy:{inputPlaceholder:xu,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 ab(t,e){if(!(!t&&!e))return t?e?ai(t,e):t:e}function Rc(t){return t?{...nt,...t,theme:ab(nt.theme,t.theme),darkTheme:ab(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,p=t.features?.streamAnimation,u=nt.features?.askUserQuestion,g=t.features?.askUserQuestion,f=nt.features?.history,v=t.features?.history,h=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},M=o===void 0&&s===void 0?void 0:{...o,...s},A=i===void 0&&l===void 0?void 0:{...i,...l},T=c===void 0&&p===void 0?void 0:{...c,...p},F=u===void 0&&g===void 0?void 0:{...u,...g,styles:{...u?.styles,...g?.styles}},P=f===void 0&&v===void 0?void 0:{...f,...v,copy:{...f?.copy,...v?.copy}};return{...nt.features,...t.features,...M!==void 0?{scrollToBottom:M}:{},...A!==void 0?{scrollBehavior:A}:{},...h!==void 0?{artifacts:h}:{},...T!==void 0?{streamAnimation:T}:{},...F!==void 0?{askUserQuestion:F}:{},...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 Au(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 Wc(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function cb(t,e){t.style.maxHeight=`${e*Au(t)}px`,t.style.overflowY="auto"}function Pa(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 db(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function pb(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||!db(e)}function xA(t){return(t.submitKey??"enter")!=="enter"||db(t)?"enter":"send"}function Bc(t,e){t.setAttribute("enterkeyhint",xA(e))}function _c(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 Mu(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 Dn="persona-composer-control",co="persona-composer-control--glyph",Tu=40,un=24,Oc=(t,e)=>{let n=k("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??xu,n.dir="auto",Bc(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:Pa(n)}),_c(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=Wc(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 p=o*Au(n);return s=`${p}px`,n.style.maxHeight=s,p},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}},MA="[data-persona-glyph-stack]",ku=(t,e,n="send")=>{let o=Q("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},Dc=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",p=t?.copy?.sendButtonLabel??"Send",u=t?.copy?.stopButtonLabel??"Stop",g=e.showTooltip??!1,f=e.size,v=parseFloat(f??"")||Tu,h=e.backgroundColor,M=e.textColor,A=k("div","persona-send-button-wrapper"),T=Q("button",{className:On("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Dn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!M&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?M||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":M||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}}),F=null,P=null,K=null;if(n){let w=parseFloat(e.iconSize??"")||Math.round(v*.5),_=e.iconStrokeWidth??2,G=M?.trim()||"currentColor";s&&(F=he(s,w,G,_)),P=he(i,w,G,_),F&&P?(K=ku(F,P),T.appendChild(K)):F?T.appendChild(F):(T.textContent=o,P=null)}else T.textContent=p;T.setAttribute("aria-label",l),A.appendChild(T),Yt({anchor:T,trigger:A,text:()=>T.getAttribute("aria-label")??"",enabled:g});let x="send";return{button:T,wrapper:A,setMode:w=>{if(w===x)return;x=w;let _=w==="stop"?c:l;T.setAttribute("aria-label",_),T.setAttribute("data-persona-send-mode",w),n?(T.querySelector(MA)??K)?.setAttribute("data-mode",w):T.textContent=w==="stop"?u:p},glyphStack:K}},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",p=e.iconSize,u=parseFloat(p??"")||un,g=e.backgroundColor??t?.sendButton?.backgroundColor,f=e.iconColor??t?.sendButton?.textColor,v=k("div","persona-send-button-wrapper"),h=Q("button",{className:On("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Dn,!p&&co),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:f||"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}}),A=he(c,u,f||"currentColor",1.5);A?h.appendChild(A):h.textContent="\u{1F3A4}",v.appendChild(h);let T=e.tooltipText??"Start voice recognition",F=e.showTooltip??!1;return Yt({anchor:h,trigger:v,text:()=>h.getAttribute("aria-label")??T,enabled:F}),{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??Qo).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=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Dn} ${co}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),c=he(s,un,"currentColor",1.5);c?l.appendChild(c):l.textContent="\u{1F4CE}",l.addEventListener("click",u=>{u.preventDefault(),o.click()}),i.appendChild(l);let p=e.buttonTooltipText??"Attach file";return Yt({anchor:l,trigger:i,text:()=>l.getAttribute("aria-label")??p}),{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=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var EA='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Pu="data-persona-menu-focus",TA=new Set(["ArrowDown","ArrowUp","Home","End"]);function ub(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(EA)??t}var kA=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function gb(t){let e=t.label,n=!1,o=k("div","persona-send-button-wrapper"),s=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Dn} ${co}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=Q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),l=()=>{let I=t.getButtonSize?.()??"";s.style.width=I,s.style.height=I,s.style.minWidth=I,s.style.minHeight=I,s.style.lineHeight="1",s.replaceChildren();let Y=he("plus",un,"currentColor",1.5);Y?s.appendChild(Y):s.textContent="+"},c=()=>{s.setAttribute("aria-label",e),s.setAttribute("title",e),i.setAttribute("aria-label",e)};c(),l();let p=[],u=-1,g=!1,f=()=>{let Y=i.getRootNode().activeElement;return Y instanceof HTMLElement?Y:null},v=()=>{let I=f();for(let Y of p){let V=!!I&&ub(Y)===I;Y.toggleAttribute(Pu,V&&g)}},h=()=>p.filter(I=>I.isConnected||i.contains(I)).map(ub).filter(I=>!kA(I)),M=(I,Y)=>{I.forEach((V,ae)=>{V.setAttribute("tabindex",ae===Y?"0":"-1")})},A=I=>{let Y=h();if(Y.length===0)return;let V=(I%Y.length+Y.length)%Y.length;u=V,M(Y,V),Y[V].focus(),v()},T=()=>o.ownerDocument??document,F=null,P=null,K=null,x=()=>{F&&(T().removeEventListener("focusin",F,!0),F=null)},L=()=>{P&&(i.removeEventListener("focusin",P),P=null),K&&(i.removeEventListener("pointerdown",K,!0),K=null)},w=null,_=()=>(w||(w=mc({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),x()}})),w),G=()=>w?.isOpen===!0,ie=(I=!1)=>{if(G()){w?.close(),s.setAttribute("aria-expanded","false"),x(),L(),u=-1,g=!1;for(let Y of p)Y.removeAttribute(Pu);I&&s.focus()}},oe=(I=0,Y=!1)=>{if(n||G())return;g=Y,_().open(),s.setAttribute("aria-expanded","true");let V=h();M(V,-1),A(I<0?V.length-1:I),F=ae=>{let ce=typeof ae.composedPath=="function"?ae.composedPath():[];ce.includes(i)||ce.includes(o)||ie()},T().addEventListener("focusin",F,!0),P=()=>v(),i.addEventListener("focusin",P),K=()=>{g=!1},i.addEventListener("pointerdown",K,!0)},S=I=>{I.preventDefault(),I.stopPropagation(),G()?ie(!0):oe(0)},O=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),g=!0,G()?A(0):oe(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),g=!0,G()?A(-1):oe(-1,!0))},R=I=>{switch(TA.has(I.key)&&(g=!0),I.key){case"ArrowDown":I.preventDefault(),A(u+1);return;case"ArrowUp":I.preventDefault(),A(u-1);return;case"Home":I.preventDefault(),A(0);return;case"End":I.preventDefault(),A(h().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),ie(!0);return;case"Tab":ie(!0);return;default:}};return s.addEventListener("click",S),s.addEventListener("keydown",O),i.addEventListener("keydown",R),{trigger:o,triggerButton:s,panel:i,setItems:I=>{for(let V of p)I.includes(V)||V.removeAttribute(Pu);if(p=[...I],!G())return;let Y=h();M(Y,Math.min(u,Y.length-1)),v()},isOpen:G,open:()=>oe(0),close:ie,setLabel:I=>{I!==e&&(e=I,c())},applyButtonSize:l,destroy:()=>{n=!0,x(),L(),s.removeEventListener("click",S),s.removeEventListener("keydown",O),i.removeEventListener("keydown",R),w?.destroy(),w=null,o.remove(),i.remove(),p=[]}}}var ko={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},mb="data-persona-composer-action",Iu="data-persona-composer-disable-when-streaming",PA="core:overflow",IA=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function LA(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 Lu(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 fb=(t,e)=>{!t||typeof console>"u"||console.warn(e)},HA=(t,e)=>e.includes(":")?e:`${t}:${e}`;function RA(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let p=o.get(c.id);if(p){fb(e,`[Persona] composer action "${c.id}" is already contributed by ${hb(p)}; the ${hb(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,p,u)=>{let g=u?HA(u,c.id):c.id,f=c.order??ko.custom;c.placement==="end"&&f>=ko.send&&(fb(e,`[Persona] composer action "${g}" ordered at ${f} would render after send; clamped to ${ko.send-1}.`),f=ko.send-1),i({id:g,placement:c.placement,presentation:c.presentation??"bar",order:f,sequence:s++,source:p,pluginId:u,action:c})};for(let c of t.configActions??[])l(c,"config");for(let c of t.plugins){if(!c.contributeComposerActions)continue;let p;try{p=c.contributeComposerActions(t.contributionContext)}catch(u){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,u);continue}for(let u of p??[])l(u,"plugin",c.id)}return n.sort((c,p)=>c.order===p.order?c.sequence-p.sequence:c.order-p.order)}var hb=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",yb=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,Er=t=>t.kind==="custom",Hu=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,WA=t=>{let e=Hu(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},BA='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function _A(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(BA)||o.childNodes.forEach(n)};return n(t),e.trim()}var OA=t=>_A(t).length===0;function bb(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(S,O)=>{let R=S.button;if(!R)return;R.setAttribute("role","menuitem"),R.setAttribute("tabindex","-1"),R.className="persona-composer-overflow-menu__item";for(let V of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])R.style[V]="";R.style.lineHeight="1",O.tooltipText?R.setAttribute("title",O.tooltipText):R.removeAttribute("title"),R.replaceChildren();let I=k("span","persona-composer-overflow-menu__icon");if(O.iconName){let V=he(O.iconName,16,"currentColor",1.5);V&&I.appendChild(V)}let Y=k("span","persona-composer-overflow-menu__label");Y.textContent=O.shortLabel??O.label,R.append(I,Y)},l=(S,O)=>{let R=S.button;if(!R)return;if(R.setAttribute("aria-label",O.label),O.pressed===void 0?R.removeAttribute("aria-pressed"):R.setAttribute("aria-pressed",O.pressed?"true":"false"),R.toggleAttribute(Iu,O.disableWhenStreaming===!0),S.mode==="menu"){S.tooltip?.destroy(),S.tooltip=void 0,i(S,O);return}R.removeAttribute("role"),R.removeAttribute("tabindex"),R.removeAttribute("title");let I=s(),Y=!!O.shortLabel;if(R.className=On("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Dn,co,Y&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),R.style.width=I&&!Y?I:"",R.style.height=I??"",R.style.minWidth=I&&!Y?I:"",R.style.minHeight=I??"",R.style.fontSize=Y?"":"18px",R.style.lineHeight="1",R.style.color=O.iconColor??"",R.style.backgroundColor=O.backgroundColor??"",R.replaceChildren(),O.iconName){let V=he(O.iconName,un,"currentColor",1.5);V&&R.appendChild(V)}if(Y){let V=k("span","persona-composer-action-button__label");V.textContent=O.shortLabel,R.appendChild(V)}else R.firstChild||(R.textContent=O.label);S.tooltip?.destroy(),S.tooltip=Yt({anchor:R,trigger:S.element,text:()=>O.tooltipText??O.label,enabled:!!O.tooltipText})},c=(S,O)=>{let R=S.action,I=Q("button",{attrs:{type:"button"}}),Y=I;if(O==="bar"){let ce=k("div","persona-send-button-wrapper");ce.appendChild(I),Y=ce}Y.setAttribute(mb,S.id);let V={resolved:S,element:Y,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:O},ae=ce=>{if(ce.preventDefault(),ce.stopPropagation(),V.busy||I.disabled)return;let me=V.resolved.action;V.mode==="menu"&&h?.close(!0);let we;try{we=me.onSelect(t.actionContext,ce)}catch(ue){t.reportError(ue,{actionId:V.resolved.id});return}!we||typeof we.then!="function"||(V.busy=!0,I.setAttribute("aria-busy","true"),we.catch(ue=>{t.reportError(ue,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",ae),V.detach=()=>I.removeEventListener("click",ae),l(V,R),V},p=S=>{let O=S.action,R;try{R=O.render({...t.actionContext,id:S.id,action:O})}catch(I){return t.reportError(I,{actionId:S.id}),null}return R?.element?(R.element.setAttribute(mb,S.id),R.element.toggleAttribute(Iu,O.disableWhenStreaming===!0),{resolved:S,element:R.element,owned:!0,managed:!0,destroy:R.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(S,O)=>{if(S.builtIn){let I=S.builtIn.element;return I?{resolved:S,element:I,owned:!1,managed:S.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let R=S.action;return R?Er(R)?p(S):c(S,O):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(O){t.reportError(O,{actionId:S.resolved.id})}S.element.remove()}},f=(S,O)=>{for(let R=0;R<O.length;R++){let I=O[R];if(!I.managed)continue;let Y=null;for(let V=R+1;V<O.length;V++){let ae=O[V];if(!ae.managed&&ae.element.parentElement===S){Y=ae.element;break}}Y?(I.element.parentElement!==S||I.element.nextSibling!==Y)&&S.insertBefore(I.element,Y):S.lastChild!==I.element&&S.appendChild(I.element)}},v=(S,O)=>{if(S.button){S.button.disabled=O;return}if(!S.owned)return;let R=S.element;R.toggleAttribute("data-disabled",O),R.setAttribute("aria-disabled",O?"true":"false");let I=R instanceof HTMLButtonElement||R instanceof HTMLSelectElement||R instanceof HTMLInputElement||R instanceof HTMLTextAreaElement?R:R.querySelector("button, select, input, textarea");I&&(I.disabled=O)},h=null,M=null,A=null,T=0,F=()=>{let S=t.getOverflow?.();return S?.enabled===!0?S:void 0},P=()=>(h?h.setLabel(t.getOverflowLabel?.()??"More actions"):h=gb({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),h),K=S=>{M!==S&&(A?.disconnect(),M=S,T=Lu(S),!(typeof ResizeObserver>"u")&&(A=new ResizeObserver(O=>{let I=O[O.length-1]?.contentRect?.width??Lu(S);I!==T&&(T=I,ie())}),A.observe(S)))},x=(S,O)=>{let R=LA(S.collapseAutoActionsBelow,O);if(R===null)return!1;let I=T||Lu(O);return I>0&&I<R},L=(S,O,R)=>{if(!O)return"bar";if(S.resolved.builtIn){let Y=IA(S.resolved.id);return Y&&O.includeBuiltIns?.includes(Y)?"menu":"bar"}let I=S.resolved.presentation;return I==="overflow"||I==="auto"&&R?"menu":"bar"},w=S=>{let O=S.menuSlot;if(!O)return;if(!OA(S.element)){S.menuLabel?.remove(),S.menuLabel=void 0;return}let R=WA(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!==O&&O.appendChild(S.menuLabel)},_=(S,O)=>{if(S.mode===O)return S;let R=S.resolved.action;if(R&&!Er(R)){g(S),e.delete(S.resolved.id);let I=c(S.resolved,O);return e.set(S.resolved.id,I),I}if(O==="menu"){let I=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Su]:""}});I.appendChild(S.element),rb(Hu(S.element)),S.menuSlot=I;let Y=V=>{let ae=Hu(S.element);if(ae.disabled)return;let ce=V.target===ae||ae.contains(V.target);h?.close(!0),ce||ae.click()};I.addEventListener("click",Y,!0),S.detachMenuSlot=()=>I.removeEventListener("click",Y,!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=O,S},G=(S,O)=>{let R=O.map(I=>I.menuSlot??I.element);for(R.forEach((I,Y)=>{let V=S.children[Y];V!==I&&(V?S.insertBefore(I,V):S.appendChild(I))});S.children.length>R.length;)S.lastElementChild?.remove()},ie=()=>{if(o)return;let S=t.getBindings();if(!S)return;let O=t.getState(),R=O.phase==="streaming",I=F();I&&K(S.footer);let Y=I?x(I,S.footer):!1,V={start:[],end:[]},ae=[];for(let ce of n){let me=e.get(ce.id);if(!me)continue;let we=ce.action,ue=we?yb(we.visible,O,!0):!0;if(me.visible!==ue&&(me.visible=ue,!ue&&me.managed&&(me.menuSlot??me.element).remove()),!!ue){if(me=_(me,L(me,I,Y)),we){let _e=yb(we.disabled,O,!1)||we.disableWhenStreaming===!0&&R;v(me,_e),!Er(we)&&we.pressed!==void 0&&me.button?.setAttribute("aria-pressed",we.pressed?"true":"false")}me.mode==="menu"?(w(me),ae.push(me)):V[ce.placement].push(me)}}if(ae.length>0){let ce=P();G(ce.panel,ae),ce.setItems(ae.map(_e=>_e.menuSlot??_e.element)),ce.applyButtonSize();let me=Number.isFinite(I?.order)?I?.order:ko.overflow,we=V.start.findIndex(_e=>_e.resolved.order>me),ue={resolved:{id:PA,placement:"start",presentation:"bar",order:me,sequence:-1,source:"core"},element:ce.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(we<0?V.start.length:we,0,ue)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));f(S.actionsStart,V.start),f(S.actionsEnd,V.end)};return{resolve:()=>{if(o)return;let S=RA(t.collect()),O=new Set(S.map(R=>R.id));for(let[R,I]of e)O.has(R)||(g(I),e.delete(R));for(let R of S){let I=e.get(R.id);if(!I){let ce=u(R,"bar");ce&&e.set(R.id,ce);continue}let Y=I.resolved.action,V=R.action;if(!!Y!=!!V||Y&&V&&Er(Y)!==Er(V)||Y&&V&&Er(Y)&&Er(V)&&Y.render!==V.render){g(I),e.delete(R.id);let ce=u(R,I.mode);ce&&e.set(R.id,ce);continue}I.resolved=R,R.builtIn?(I.managed=R.builtIn.managed===!0||I.mode==="menu",R.builtIn.element&&I.mode==="bar"&&(I.element=R.builtIn.element)):V&&!Er(V)?l(I,V):V&&I.element.toggleAttribute(Iu,V.disableWhenStreaming===!0)}n=S,ie()},sync:ie,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,A?.disconnect(),A=null,M=null;for(let S of e.values())g(S);e.clear(),h?.destroy(),h=null,n=[]}}}}var DA="core:model",NA=700,vb=16,FA=["--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"],UA=(t,e)=>{let n=t.ownerDocument?.defaultView;if(!n)return;let o=n.getComputedStyle(t);for(let s of FA){let i=o.getPropertyValue(s).trim();i&&e.style.setProperty(s,i)}},Cb=()=>{let t=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function wb(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=p=>{let u=t.getSelectedModelId();return p.find(g=>g.id===u)??p[0]},i=()=>{let p=Q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),u="",g=()=>{let A=t.getModels(),T=A.map(F=>`${F.id}:${F.label}`).join("|");T!==u&&(u=T,p.replaceChildren(...A.map(F=>{let P=Q("option",{attrs:{value:F.id}});return P.textContent=F.label,P}))),p.value=s(A)?.id??""};g(),o=g;let f=()=>{p.value&&t.onSelect(p.value)};p.addEventListener("change",f);let v=A=>A.stopPropagation();p.addEventListener("click",v);let{wrapper:h,chevron:M}=Cb();return h.append(p,M),{element:h,destroy:()=>{o===g&&(o=null),p.removeEventListener("change",f),p.removeEventListener("click",v)}}},l=()=>{let p=Q("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),u=k("span","persona-composer-model-picker-label"),g=k("span","persona-composer-model-picker-suffix");p.append(u,g);let f=Q("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),v=new Map,h="",M=null,A=()=>M?.isOpen===!0,T=(O=!1)=>{A()&&(M?.close(),p.setAttribute("aria-expanded","false"),O&&p.focus())},F=O=>{let R=[...v.values()];if(R.length===0)return;let I=(O%R.length+R.length)%R.length;R[I].focus()},P=O=>{if(A())return;M||(M=mc({anchor:p,content:f,placement:"top-start",offset:6,onDismiss:()=>p.setAttribute("aria-expanded","false")})),UA(p,f),M.open(),p.setAttribute("aria-expanded","true");let I=[...v.keys()].indexOf(s(t.getModels())?.id??"");F(O??(I>=0?I:0))},K=O=>{T(!0),t.onSelect(O)},x=O=>{O.preventDefault(),O.stopPropagation();let R=O.currentTarget.getAttribute("data-persona-model-option");R&&K(R)},L=O=>{let R=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":O.id}});if(O.icon){let ce=he(O.icon,vb,"currentColor",1.5);if(ce){let me=k("span","persona-composer-model-option-icon");me.appendChild(ce),R.appendChild(me)}}let I=k("span","persona-composer-model-option-body"),Y=k("span","persona-composer-model-option-label");if(Y.textContent=O.label,I.appendChild(Y),O.description){let ce=k("span","persona-composer-model-option-description");ce.textContent=O.description,I.appendChild(ce)}R.appendChild(I);let V=k("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let ae=he("check",vb,"currentColor",2);return ae&&V.appendChild(ae),R.appendChild(V),R.addEventListener("click",x),R},w=()=>{let O=t.getModels(),R=O.map(V=>`${V.id}:${V.label}:${V.icon??""}:${V.description??""}`).join("|");if(R!==h){h=R;for(let V of v.values())V.removeEventListener("click",x);v.clear(),f.replaceChildren(...O.map(V=>{let ae=L(V);return v.set(V.id,ae),ae}))}let I=s(O);for(let[V,ae]of v)ae.setAttribute("aria-selected",String(V===I?.id));u.textContent=I?.label??"";let Y=t.getSuffix?.()??"";g.textContent=Y,p.setAttribute("aria-label",[e,[I?.label,Y].filter(Boolean).join(" ")].filter(Boolean).join(": "))};w(),o=w;let _=O=>{O.preventDefault(),O.stopPropagation(),A()?T(!0):P()},G=O=>{if(O.key==="ArrowDown"){O.preventDefault(),A()?F(0):P(0);return}O.key==="ArrowUp"&&(O.preventDefault(),A()?F(-1):P(-1))},ie=O=>{let R=[...v.values()],I=R.indexOf(O.target?.closest?.(".persona-composer-model-option"));switch(O.key){case"ArrowDown":O.preventDefault(),F(I+1);return;case"ArrowUp":O.preventDefault(),F(I-1);return;case"Home":O.preventDefault(),F(0);return;case"End":O.preventDefault(),F(R.length-1);return;case"Escape":O.preventDefault(),O.stopPropagation(),T(!0);return;case"Tab":T(!0);return;default:}};p.addEventListener("click",_),p.addEventListener("keydown",G),f.addEventListener("keydown",ie);let{wrapper:oe,chevron:S}=Cb();return oe.append(p,S),{element:oe,destroy:()=>{o===w&&(o=null),p.removeEventListener("click",_),p.removeEventListener("keydown",G),f.removeEventListener("keydown",ie);for(let O of v.values())O.removeEventListener("click",x);v.clear(),M?.destroy(),M=null,f.remove()}}};return{action:{id:DA,kind:"custom",placement:"end",order:NA,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var $A=":scope > [data-persona-composer-mode]";function Sb(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=u=>{let g=Q("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let M=k("span","persona-mention-chip-icon"),A=he(u.iconName,12,"currentColor",1.5);A&&M.appendChild(A),g.appendChild(M)}let f=k("span","persona-mention-chip-label");f.textContent=u.shortLabel??u.label,g.appendChild(f);let v=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),h=he("x",12,"currentColor",2);return h?v.appendChild(h):v.textContent="\xD7",v.addEventListener("click",M=>{M.preventDefault(),M.stopPropagation(),t.onRemove(u.id)}),g.appendChild(v),g},l=()=>Array.from(e.querySelectorAll($A)),c=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let g=()=>{u.remove(),fc(e)},f=e.ownerDocument.defaultView,v=typeof f?.getComputedStyle=="function"?f.getComputedStyle(u).animationName:"";if(!v||v==="none"){g();return}u.addEventListener("animationend",g,{once:!0}),u.addEventListener("animationcancel",g,{once:!0})},p=()=>{for(let u of l())u.remove()};return{element:e,render:(u,g)=>{if(o)return;let f=g.filter(A=>u.includes(A.id)),v=f.map(A=>`${A.id}:${A.shortLabel??A.label}`).join("|");if(v===n)return;n=v;let h=new Map;for(let A of l()){let T=A.getAttribute("data-persona-composer-mode");T&&f.some(P=>P.id===T)&&!A.hasAttribute("data-persona-chip-exit")?h.set(T,A):A.hasAttribute("data-persona-chip-exit")||c(A)}let M=e.firstChild;for(let A of f){let T=h.get(A.id);T||(T=i(A),s.has(A.id)||(T.setAttribute("data-persona-chip-enter",""),T.addEventListener("animationend",()=>T?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(A.id),T!==M&&e.insertBefore(T,M),M=T.nextSibling}fc(e)},destroy:()=>{o=!0,p(),fc(e)}}}var xb=t=>`core:mode:${t}`;var Ru=t=>Math.min(300+t,499),Ab=t=>`core:mode-group:${t}`;function $c(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function Mb(t,e){return t?.length?t.filter(n=>!$c(n.groupId,e)):[]}var qA=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Eb(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(qA(s,o)==="single"){let c=n.filter(p=>p.groupId===s.groupId).map(p=>p.id);l=new Set([...l].filter(p=>!c.includes(p)))}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 Tb(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function kb(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var zA=16;function Pb(t){let e=null;return{action:{id:Ab(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=Q("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=u=>{u.preventDefault(),u.stopPropagation();let f=u.currentTarget.getAttribute("data-persona-composer-mode");!f||t.getActiveIds().includes(f)&&t.getGroup()?.selection==="single"||t.onSelect(f)},c=u=>{let g=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let v=he(u.iconName,zA,"currentColor",1.5);v&&g.appendChild(v)}let f=k("span","persona-composer-segmented-label");return f.textContent=u.shortLabel??u.label,g.appendChild(f),g.addEventListener("click",l),g},p=()=>{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(),f=g.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(f!==i){i=f;for(let M of s.values())M.removeEventListener("click",l);s.clear();let h=g.map(M=>{let A=c(M);return s.set(M.id,A),A});o.replaceChildren(...h)}let v=t.getActiveIds();for(let[h,M]of s)M.setAttribute("aria-pressed",String(v.includes(h)))};return p(),e=p,{element:o,destroy:()=>{e===p&&(e=null);for(let u of s.values())u.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function Ib(t){let e=Q("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 f=k("div","persona-composer-quote-source");f.textContent=i.sourceLabel,c.appendChild(f)}let p=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});p.textContent=Tc(i.text),c.appendChild(p);let u=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),g=he("x",12,"currentColor",2);g?u.appendChild(g):u.textContent="\xD7",u.addEventListener("click",f=>{f.preventDefault(),f.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 Lb(t){let e=Q("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,p,u)=>{let g=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[p]:""}}),f=he(l,12,"currentColor",2);return f?g.appendChild(f):g.textContent=c,g.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),u()}),g},i=l=>{let c=Tc(l.text??"",90);if(c)return c;let p=l.contentParts?.length??0;return p>0?p===1?"1 attachment":`${p} 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 p=Q("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});p.textContent=i(l),e.replaceChildren(c,p,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 Hb(t){let e=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=Q("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,p,u,g)=>{let f=Q("button",{className:`persona-message-edit-button ${p}`,attrs:{type:"button",[u]:""},text:c});return f.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),g()}),f},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 Rb(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 Wb(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(p=>n.has(p.sourceId)),s=o.length===(t.mentionRefs?.length??0)&&o.length>0,i=new Set(e.modes.map(p=>p.id)),l=(t.activeModeIds??[]).filter(p=>i.has(p)),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 Bb(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 _b(t){return t.wrapped||t.text.includes(`
|
|
17
|
-
`)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function
|
|
18
|
-
`).some(
|
|
19
|
-
`)[0]).startsWith(L.trigger):!1),i=(x,L)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${x}`,{detail:L}))}catch{}},l=!t.chipRow,c=t.chipRow??Q("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),p=null,u=null,g=t.textarea,f=null,v=null,h=null,M=null,A=()=>{if(p)return Promise.resolve(p);if(u)return u;let x=Bu().then(L=>(L.setMentionIconRenderer(he),p=L.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:f??void 0,anchor:t.anchor,contextRow:c,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:K,emit:i}),p)).catch(L=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",L),u===x&&(u=null),null));return u=x,x},T=()=>{qb().then(x=>{let L=x.mountInlineComposer({textarea:t.textarea,renderToken:_=>Ia(_,{render:e.renderMentionToken}),onMentionRemoved:_=>p?.untrackMention(_)});f=L.input,v=L.destroy;let w=g;w.replaceWith(L.element),g=L.element,M={next:L.element,prev:w},h?.(L.element,w),p?p.rebindComposer(L.input):u&&u.then(_=>_?.rebindComposer(L.input))}).catch(x=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",x)})};e.display==="inline"&&T();let F=[],P=new Map;for(let x of n){if(!x.showButton)continue;let L=$b({config:{...e,buttonIconName:x.buttonIconName,buttonTooltipText:x.buttonTooltipText},onOpen:()=>{A().then(w=>w?.openMenu(x.trigger))}});F.push(L),P.set(x.trigger,L.button)}let K=(x,L,w)=>{let _=P.get(L);_&&(_.setAttribute("aria-expanded",x?"true":"false"),x?_.setAttribute("aria-controls",w):_.removeAttribute("aria-controls"))};return{affordanceButtons:F.map(x=>x.wrapper),contextRow:c,handleInput:x=>{if(p){p.handleInput();return}if(!_h(x))return;let L=g,w=L.selectionStart??0;Bh(L.value,w,n)&&A().then(_=>_?.handleInput())},handleKeydown:x=>{if(p?.isMenuOpen())return p.handleKeydown(x);if(x.key==="Backspace"&&p?.hasMentions()&&!M){let L=g,w=L.selectionStart===0&&L.selectionEnd===0;if((L.value.length===0||w)&&p.removeLastChip())return x.preventDefault(),!0}return!1},isMenuOpen:()=>p?.isMenuOpen()??!1,hasMentions:()=>p?.hasMentions()??!1,getMentionRefs:()=>p?.getMentionRefs()??[],collectForSubmit:()=>p?.collectForSubmit()??null,takeInlineCommand:async x=>s(x)?(p??await A())?.dispatchInlineCommand(x)??null:null,clear:()=>p?.clear(),prefetch:()=>{Bu().catch(()=>{})},onComposerSwap:x=>{h=x,M&&x(M.next,M.prev)},destroy:()=>{p?.destroy(),v?.();for(let x of F)x.wrapper.remove();l&&c.remove()}}}var zc="16px",jc="transparent",GA=(()=>{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})(),QA={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:GA,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"}},YA={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"}},XA={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:Yo,maxWidth:lb,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"}},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 gn(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."))?gn(t,o):o}function Vb(t){let e={};function n(o,s){for(let[i,l]of Object.entries(o)){let c=`${s}.${i}`;if(typeof l=="string"){let p=gn(t,l);p!==void 0&&(e[c]={path:c,value:p,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 JA(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 Kb(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]=Kb(i,s):n[o]=s}return n}function ZA(t,e){return e?Kb(t,e):t}function ci(t,e={}){let n={palette:QA,semantic:YA,components:XA},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:ZA(n.components,t?.components)};if(e.validate!==!1){let s=JA(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 _u=t=>t.trim()==="0"?"0px":t,jb="--persona-",eM=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(p=>{let u=p.endsWith("%"),g=parseFloat(u?p.slice(0,-1):p);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},tM=.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[jb+i],s!==void 0)break;s!==void 0&&(t[jb+n]=s)}};function Gb(t){let e=Vb(t),n={};for(let[$,Pe]of Object.entries(e)){let Ne=$.replace(/\./g,"-");n[`--persona-${Ne}`]=Pe.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 p=n["--persona-components-history-railHeader-background"];p&&(n["--persona-history-rail-header-bg"]=p);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[$,Pe]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ne=n[`--persona-components-history-overlay-${$}`];Ne&&(n[`--persona-history-overlay-${Pe}`]=Ne)}for(let[$,Pe]of[["background","bg"],["borderRadius","radius"]]){let Ne=n[`--persona-components-history-menu-${$}`];Ne&&(n[`--persona-history-menu-${Pe}`]=Ne)}let f=t.components?.history?.motion;if(f){let $=xe=>{if(xe===void 0)return;let Oe=String(xe).trim();return/^\d+(\.\d+)?$/.test(Oe)?`${Oe}ms`:Oe},Pe=$(f.enterDurationMs);Pe!==void 0&&(n["--persona-history-enter-ms"]=Pe);let Ne=$(f.exitDurationMs);Ne!==void 0&&(n["--persona-history-exit-ms"]=Ne),f.enterEasing&&(n["--persona-history-enter-easing"]=f.enterEasing),f.exitEasing&&(n["--persona-history-exit-easing"]=f.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 $ of["scrim","shadow"]){let Pe=n[`--persona-components-history-confirm-${$}`];Pe&&(n[`--persona-history-confirm-${$}`]=Pe)}for(let[$,Pe]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ne=n[`--persona-components-tooltip-${$}`];Ne&&(n[`--persona-tooltip-${Pe}`]=Ne)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[$,Pe]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ne=n[`--persona-components-messageActions-${$}`];Ne&&(n[`--persona-message-action-${Pe}`]=Ne)}Xt(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],M=n["--persona-components-introCard-shadow"],A=(!h||h==="transparent"||h==="none")&&(!M||M==="none"),T=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=A&&T==="1.5rem"?"1.5rem 0":T,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"],["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 F=n["--persona-components-markdown-heading-h1-fontSize"];F&&(n["--persona-md-h1-size"]=F);let P=n["--persona-components-markdown-heading-h1-fontWeight"];P&&(n["--persona-md-h1-weight"]=P);let K=n["--persona-components-markdown-heading-h2-fontSize"];K&&(n["--persona-md-h2-size"]=K);let x=n["--persona-components-markdown-heading-h2-fontWeight"];x&&(n["--persona-md-h2-weight"]=x);let L=n["--persona-components-markdown-prose-fontFamily"];L&&L!=="inherit"&&(n["--persona-md-prose-font-family"]=L),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,_=w?.iconButton;_&&(_.background&&(n["--persona-icon-btn-bg"]=_.background),_.border&&(n["--persona-icon-btn-border"]=_.border),_.color&&(n["--persona-icon-btn-color"]=_.color),_.padding&&(n["--persona-icon-btn-padding"]=_.padding),_.borderRadius&&(n["--persona-icon-btn-radius"]=_.borderRadius),_.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=_.hoverBackground),_.hoverColor&&(n["--persona-icon-btn-hover-color"]=_.hoverColor),_.activeBackground&&(n["--persona-icon-btn-active-bg"]=_.activeBackground),_.activeBorder&&(n["--persona-icon-btn-active-border"]=_.activeBorder));let G=w?.labelButton;G&&(G.background&&(n["--persona-label-btn-bg"]=G.background),G.border&&(n["--persona-label-btn-border"]=G.border),G.color&&(n["--persona-label-btn-color"]=G.color),G.padding&&(n["--persona-label-btn-padding"]=G.padding),G.borderRadius&&(n["--persona-label-btn-radius"]=G.borderRadius),G.hoverBackground&&(n["--persona-label-btn-hover-bg"]=G.hoverBackground),G.fontSize&&(n["--persona-label-btn-font-size"]=G.fontSize),G.gap&&(n["--persona-label-btn-gap"]=G.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 oe=w?.artifact;if(oe?.toolbar){let $=oe.toolbar;$.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=$.iconHoverColor),$.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=$.iconHoverBackground),$.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=$.iconPadding),$.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=$.iconBorderRadius),$.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=$.iconBorder),$.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=_u($.toggleGroupGap)),$.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=_u($.toggleGroupPadding)),$.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=$.toggleGroupBorder),$.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=$.toggleGroupBorderRadius),$.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=gn(t,$.toggleGroupBackground)??$.toggleGroupBackground),$.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=$.copyBackground),$.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=$.copyBorder),$.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=$.copyColor),$.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=_u($.copyBorderRadius)),$.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=$.copyPadding),$.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=$.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??$.copyMenuBackground),$.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=$.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??$.copyMenuBorder),$.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=$.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??$.copyMenuShadow),$.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=$.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??$.copyMenuBorderRadius),$.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=$.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??$.copyMenuItemHoverBackground),$.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=$.iconBackground),$.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=$.toolbarBorder)}if(oe?.tab){let $=oe.tab;$.background&&(n["--persona-artifact-tab-bg"]=$.background),$.activeBackground&&(n["--persona-artifact-tab-active-bg"]=$.activeBackground),$.activeBorder&&(n["--persona-artifact-tab-active-border"]=$.activeBorder),$.borderRadius&&(n["--persona-artifact-tab-radius"]=$.borderRadius),$.textColor&&(n["--persona-artifact-tab-color"]=$.textColor),$.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=$.hoverBackground),$.listBackground&&(n["--persona-artifact-tab-list-bg"]=$.listBackground),$.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=$.listBorderColor),$.listPadding&&(n["--persona-artifact-tab-list-padding"]=$.listPadding)}if(oe?.pane){let $=oe.pane;if($.toolbarBackground){let Pe=gn(t,$.toolbarBackground)??$.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Pe}}if(oe?.card){let $=oe.card;$.background&&(n["--persona-artifact-card-bg"]=$.background),$.border&&(n["--persona-artifact-card-border"]=$.border),$.borderRadius&&(n["--persona-artifact-card-radius"]=$.borderRadius),$.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=$.hoverBackground),$.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=$.hoverBorderColor)}if(oe?.inline){let $=oe.inline;$.background&&(n["--persona-artifact-inline-bg"]=gn(t,$.background)??$.background),$.border&&(n["--persona-artifact-inline-border"]=$.border),$.borderRadius&&(n["--persona-artifact-inline-radius"]=$.borderRadius),$.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=gn(t,$.chromeBackground)??$.chromeBackground),$.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=gn(t,$.chromeBorder)??$.chromeBorder),$.titleColor&&(n["--persona-artifact-inline-title-color"]=gn(t,$.titleColor)??$.titleColor),$.mutedColor&&(n["--persona-artifact-inline-muted-color"]=gn(t,$.mutedColor)??$.mutedColor),$.frameHeight&&(n["--persona-artifact-inline-frame-height"]=$.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"]=gn(t,S.background)??S.background));let O=n["--persona-surface"],R=n["--persona-container"],I=n["--persona-palette-colors-gray-100"]??"#f3f4f6",Y=n["--persona-palette-colors-gray-200"]??"#e5e7eb",V=n["--persona-palette-colors-gray-300"]??"#d1d5db",ae=!R||R===O,ce=eM(O??n["--persona-background"]),me=ae&&ce!==void 0&&ce<tM,we=me?"rgba(255, 255, 255, 0.08)":I,ue=me?"rgba(255, 255, 255, 0.12)":Y,_e=me?"rgba(255, 255, 255, 0.16)":V,ct=ae?we:R,Ce=ae?ue:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??ct,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Ce,ae&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??_e),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??ct,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??ct,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??ct,n}var nM={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"}}},oM={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},Qb=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Ou=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",rM=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Ou()},Yb=t=>rM(t),sM=t=>ci(t),iM=t=>{let e=ai(oM,t??{})??{};return ci({...e,palette:{...e.palette,colors:{...nM.colors,...e.palette?.colors}}},{validate:!1})},di=t=>{let e=Yb(t),n=Qb(t?.theme),o=Qb(t?.darkTheme);return e==="dark"?iM(ai(n??{},o??{})):sM(n)},aM=t=>Gb(t),La=(t,e)=>{let n=di(e),o=aM(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",Yb(e))},Vc=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Ou())});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(Ou());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 yC,Check as bC,Copy as vC}from"lucide";var Tr=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Kc="24px",Du=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",Ha=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},Xb=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var Jb=null;var Nu=()=>{if(Jb!==null)return Jb;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},lM="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)},cM=t=>lM.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),Zb=(t,e)=>{let n=Qc(t);if(!n)return"";let o=Nu(),s=cM(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("+")},Yc=t=>Zb(t,!1),Ra=t=>Zb(t,!0),dM=(t,e)=>e.key?.toLowerCase()===t.key&&(Nu()?e.metaKey:e.ctrlKey)===t.mod&&!(Nu()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,pM=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},ev=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(dM(c.parsed,i)&&c.when?.()!==!1&&o(c,i)&&!(!c.allowInInput&&pM(l))){i.preventDefault();try{c.run(i)}catch(p){Gc(`${c.id} threw on`,c.combo),console.warn(p)}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}`,p=e.get(c);return p?(Gc(`${p.id} already owns`,i.combo),()=>{}):(e.set(c,{...i,parsed:l}),i.element?.setAttribute("aria-keyshortcuts",Ra(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 uM}from"idiomorph";var Xc=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;uM.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 tv=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Fu={index:-1,draft:""};function nv(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 ov(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 rv(){return new Map}function sv(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function iv(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function av(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:U0,load:gM}=Pt({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var lv=gM;function Uu(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 Wa=0,kr=null;function $u(t=document){if(Wa++,Wa===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;kr={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,Wa=Math.max(0,Wa-1),Wa===0&&kr)){let n=t.body,o=t.defaultView??window;n.style.overflow=kr.originalOverflow,n.style.position=kr.originalPosition,n.style.top=kr.originalTop,n.style.width=kr.originalWidth,o.scrollTo(0,kr.scrollY),kr=null}}}var Ba={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Rt=t=>(t?.launcher?.mountMode??"floating")==="docked",_a=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Jn=t=>{let e=t?.launcher?.dock;return{side:e?.side??Ba.side,width:e?.width??Ba.width,animate:e?.animate??Ba.animate,reveal:e?.reveal??Ba.reveal,maxHeight:e?.maxHeight??Ba.maxHeight}};import{ArrowRight as mM}from"lucide";var qu=t=>t==="followUp"?"follow-up":t,zu=(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"}},fM=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'}},cv=new WeakSet,hM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,yM=t=>{hM()||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"})})},ju=t=>{var K,x,L;let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:p,chipsConfig:u,session:g,getTextarea:f,eventTarget:v,submitPrompt:h}=t,M=o==="followUp",A=e.behavior,T=()=>{if(g.isStreaming())return;let w={suggestion:{...e},surface:o,source:s,behavior:A},_=v.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:w,bubbles:!0,composed:!0,cancelable:!0}));if(M&&v.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!_)return;for(let ie of p)if(ie.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let G=f();if(A==="fill"){G.value=e.prompt,G.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),G.focus();return}if(h){h(e.prompt);return}G.value="",g.sendMessage(e.prompt)},F=()=>{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=A,i==="chip"&&(u?.fontFamily&&(w.style.fontFamily=fM(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 G=he(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);G&&(G.classList.add("persona-suggestion__icon"),e.iconColor&&(G.style.color=e.iconColor),w.appendChild(G))}let _=k("span","persona-suggestion__copy");if(_.appendChild(Q("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&_.appendChild(Q("span",{className:"persona-suggestion__description",text:e.description})),w.appendChild(_),i!=="chip"){let G=en(mM,16,"currentColor",1.8);G&&(G.classList.add("persona-suggestion__arrow"),w.appendChild(G))}return w.addEventListener("click",T),w},P=null;for(let w of p)if(w.renderSuggestion&&(P=w.renderSuggestion({suggestion:{...e},index:n,surface:o,source:s,variant:i,streaming:l,config:c,defaultRenderer:F,select:T}),P))break;return P??(P=F()),(K=P.dataset).suggestionId||(K.suggestionId=e.id),(x=P.dataset).behavior||(x.behavior=A),(L=P.dataset).emphasis||(L.emphasis=e.emphasis),P instanceof HTMLButtonElement||P.setAttribute("aria-disabled",l?"true":"false"),P},Oa=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 f=getComputedStyle(t).direction==="rtl",v=Math.min(g,Math.max(0,Math.abs(t.scrollLeft))),h=4,M=v<=h,A=v>=g-h,T=f?!A:!M,F=f?!M:!A;t.toggleAttribute("data-scroll-left",T),t.toggleAttribute("data-scroll-right",F)},c=()=>{if(s!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&l();return}s=requestAnimationFrame(l)};t.addEventListener("scroll",c,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(c):null;return p?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",c),p?.disconnect(),s!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(s),s=null},render:(g,f,v,h,M,A)=>{t.replaceChildren(),e.length=0,n.length=0;let T=A?.source??"config",F=A?.surface??(T==="config"?"starter":"followUp"),P=F==="followUp",K=A?.variant??"chip",x=A?.behavior??"send",L=A?.overflow??"wrap",w=A?.config??{},_=A?.plugins??[],G=typeof A?.maxItems=="number"?Math.max(0,Math.floor(A.maxItems)):void 0,ie=P?"followUps":"starters";!cv.has(w)&&w.debug===!0&&K!=="chip"&&w.suggestions?.[ie]?.overflow!==void 0&&(cv.add(w),console.info(`[persona] suggestions.${ie}.overflow applies to the "chip" variant only; the "${K}" variant manages its own stacking.`));let oe=V=>V.map(zu).filter(ae=>ae!==null).map(ae=>({...ae,behavior:ae.behavior??x})),S=oe(g??[]);_.forEach(V=>{V.transformSuggestions&&(S=oe(V.transformSuggestions({suggestions:S.map(ae=>({...ae})),surface:F,source:T,config:w})))});let O=G===void 0?S:S.slice(0,G);if(!O.length){t.hidden=!0,o=null,i();return}if(!P&&(h??f.getMessages()).some(ae=>ae.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=qu(F),t.dataset.variant=K,t.dataset.overflow=L;let R=document.createDocumentFragment(),I=f.isStreaming();O.forEach((V,ae)=>{let ce=ju({item:V,index:ae,surface:F,source:T,variant:K,streaming:I,config:w,plugins:_,chipsConfig:M,session:f,getTextarea:()=>v,eventTarget:t,submitPrompt:A?.submitPrompt});R.appendChild(ce),n.push(ce),[...ce instanceof HTMLButtonElement?[ce]:[],...Array.from(ce.querySelectorAll("button"))].forEach(we=>{e.includes(we)||(we.disabled=I,e.push(we))})}),t.appendChild(R),l(),c();let Y=JSON.stringify({normalized:O,surface:F,variant:K,source:T});Y!==o&&(o=Y,yM(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:O.map(V=>({...V})),surface:F,source:T,variant:K},bubbles:!0,composed:!0})),P&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:O.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var Nn={"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 bM="persona-header-control",vM="persona-header-control--glyph",CM="persona-header-control--sparse",wM=20,SM={x:[1.4,1.05]},dv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",xM="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Jc=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=SM[e]??[1,1.5],c=!o;t.classList.toggle(vM,c),t.classList.toggle(CM,c&&i!==1);let p=parseFloat(o??"")||wM,u=he(e,`${Math.round(p*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)},hs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=dv,size:c,iconSize:p,color:u,backgroundColor:g,borderWidth:f,borderColor:v,borderRadius:h,paddingX:M,paddingY:A,hidden:T,extraClassName:F,attrs:P}=t,K=k("div",l),x=!!(f||v),L=Q("button",{className:On(bM,"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",F),attrs:{type:"button","aria-label":e,...P},style:{width:c,height:c,minWidth:c,minHeight:c,display:T?"none":void 0,color:u||mn.actionIconColor,backgroundColor:g,border:x?`${f||"0px"} solid ${v||"transparent"}`:void 0,borderRadius:h,paddingLeft:M,paddingRight:M,paddingTop:A,paddingBottom:A}});return s?Jc(L,s,{iconSize:p,iconText:i}):i&&(L.textContent=i),K.appendChild(L),Yt({anchor:L,trigger:K,text:()=>L.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:L,wrapper:K}},pi=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=dv,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",p=l.closeButtonShowTooltip??!0,{button:u,wrapper:g}=hs({ariaLabel:c,tooltip:p,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=xM,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",p=l.showTooltip??!0,{button:u,wrapper:g}=hs({ariaLabel:c,tooltip:p,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 mn={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)"},Vu={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)"},AM={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)"},ys=t=>{let{config:e,showClose:n=!0}=t,o=Q("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:mn.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,p=s.headerIconName,u=Q("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(p){let L=parseFloat(i)||24,w=he(p,L*.6,"currentColor",1);w?u.replaceChildren(w):u.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let L=k("img");L.src=e.launcher.iconUrl,L.alt="",L.className="persona-rounded-xl persona-object-cover",L.style.height=i,L.style.width=i,u.replaceChildren(L)}else u.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let g=k("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Q("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:mn.titleColor,...Vu}}),v=Q("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:mn.subtitleColor,...AM}});g.append(f,v),c?o.append(g):o.append(u,g);let h=s.clearChat??{},M=h.enabled??!0,A=h.placement??"inline",T=null,F=null;if(M){let w=ui(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=w.button,F=w.wrapper,A==="top-right"&&(F.style.right="48px"),A==="inline"&&o.appendChild(F)}let P=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":M&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:K,wrapper:x}=pi(e,{showClose:n,wrapperClassName:P});return l!=="top-right"&&o.appendChild(x),{header:o,iconHolder:u,headerTitle:f,headerSubtitle:v,closeButton:K,closeButtonWrapper:x,clearChatButton:T,clearChatButtonWrapper:F}},Da=(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 MM=t=>{let e=ys({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 EM(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=hs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Yc(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=Ra(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=Vh({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 TM=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=mn.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 p=s?.titleMenu,u,g;if(p){let x=Gh({label:l.title??"Chat Assistant",menuItems:p.menuItems,onSelect:L=>{let w=G=>{G===!1&&x.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:L}}))},_=p.onSelect(L);_ instanceof Promise?_.then(w,()=>{}):w(_)},hover:p.hover,className:""});u=x.element,u.style.color=mn.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=mn.titleColor,Object.assign(g.style,Vu),g.textContent=l.title??"Chat Assistant",u.appendChild(g),s?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let L=s.onTitleClick;u.addEventListener("click",w=>{w.target.closest("button")||L()}),u.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),L())})}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 f="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:v,wrapper:h}=pi(e,{showClose:n,wrapperClassName:f});o&&v.addEventListener("click",o);let M=k("div","persona-flex persona-items-center persona-gap-1");p||EM(M,s?.trailingActions,s?.onAction??i);let A=l.clearChat??{},T=null,F=null;if(A.enabled??!0){let x=A.placement??"inline",L=ui(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":f});T=L.button,F=L.wrapper,x==="top-right"?F.style.right="48px":M.appendChild(F)}M.appendChild(h),c.appendChild(M);let P=k("div");P.style.display="none";let K=k("span");return K.style.display="none",{header:c,iconHolder:P,headerTitle:g,headerSubtitle:K,closeButton:v,closeButtonWrapper:h,clearChatButton:T,clearChatButtonWrapper:F}},pv={default:MM,minimal:TM},kM=t=>pv[t]??pv.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 p=k("span"),u=k("span"),g=k("button");g.style.display="none";let f=k("div");return f.style.display="none",{header:l,iconHolder:c,headerTitle:p,headerSubtitle:u,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=kM(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 Na=t=>{let{config:e}=t,n=Q("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Uc(),s=Q("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:i,attachAutoResize:l}=Oc(e);l();let c=Dc(e),p=li(e),u=Nc(e),g=Fc(e),f=Q("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(f),u&&(u.previewsContainer.style.gap="8px",f.append(u.previewsContainer),s.append(u.input)),s.append(i);let v=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),M=Q("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),p&&M.append(p.wrapper),M.append(c.wrapper),v.append(h,M),s.append(v),s.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&i.focus()}),n.append(o,s,g),{footer:n,suggestions:o,composerForm:s,header:f,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:p?.button??null,micButtonWrapper:p?.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:M,setSendButtonMode:c.setMode}};import{ChevronUp as PM,MessageSquare as IM}from"lucide";var uv=()=>{let t=Q("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(IM,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(PM,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=Q("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=Dc(e),p=li(e),u=Nc(e);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let g=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&f.append(u.wrapper);let v=Q("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});p&&v.append(p.wrapper),v.append(c.wrapper),g.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&i.focus()}),u&&g.append(u.input),g.append(f,i,v);let h=Q("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 M=g;return{footer:n,suggestions:o,composerForm:g,header:h,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:s,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:M,leftActions:f,rightActions:v,setSendButtonMode:c.setMode}};var LM=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}},HM=(t,e)=>{if(!t)return null;let n=LM(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},RM=(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},WM=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Gu=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(":"))},Qu=320,yv=320,BM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),_M=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),OM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),DM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),NM=t=>{if(!t||t.length===0)return null;let e=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=k("span","persona-mention-chip-icon"),i=he(n.iconName??"at-sign",13,"currentColor",2);i&&s.appendChild(i),o.appendChild(s),o.appendChild(Q("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},FM=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Ia(o.ref,{readonly:!0,render:e}))}return n},gv="\uE000",mv="\uE001",UM=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=v=>`${gv}${s}:${v}${mv}`,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(FM(e,o));return}t.innerHTML=c;let u=new RegExp(`${gv}${s}:(\\d+)${mv}`),g=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),f=[];for(let v=g.nextNode();v;v=g.nextNode())f.push(v);for(let v of f){let h=v;for(let M=u.exec(h.data);M;M=u.exec(h.data)){let A=e[Number(M[1])],T=h.splitText(M.index);T.data=T.data.slice(M[0].length),A?.kind==="mention"&&T.parentNode?.insertBefore(Ia(A.ref,{readonly:!0,render:o}),T),h=T}}},$M=(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,p)=>{let u=k("img");u.alt=c.alt?.trim()||`Attached image ${p+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${Qu}px`,u.style.maxHeight=`${yv}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}),WM(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}},qM=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(!Gu(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=`${Qu}px`,e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},zM=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(!Gu(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=`${Qu}px`,s.style.maxHeight=`${yv}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}},jM=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(!Gu(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}},Fa=()=>{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},VM=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Fa};if(e){let s=e(o);if(s!==null)return s}return Fa()},KM=(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},fv=(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},Ua=(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},hv={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"}},GM=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=hv[n??"bubble"]??hv.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:",QM=t=>`${td}${t}`,bv=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),YM=(t,e,n,o)=>{let s=e.showCopy??!0,i=e.showUpvote??!0,l=e.showDownvote??!0,c=e.showReadAloud??!1,p=(e.showRegenerate??!1)&&o?.canRegenerate===!0,u=(e.showEdit??!1)&&o?.canEdit===!0,g=(e.showQuote??!1)&&o?.canQuote!==!1,f=bv(e,t.role);if(!s&&!i&&!l&&!c&&!p&&!u&&!g&&f.length===0){let K=k("div");return K.style.display="none",K.id=`actions-${t.id}`,K.setAttribute("data-actions-for",t.id),K}let v=e.visibility??"hover",h=e.align??"right",M=e.layout??"pill-inside",A={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],T={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[M],F=k("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${A} ${T} ${v==="hover"?"persona-message-actions-hover":""}`);F.id=`actions-${t.id}`,F.setAttribute("data-actions-for",t.id);let P=(K,x,L)=>{let w=Kh({icon:K,label:x,size:14,className:"persona-message-action-btn",chromeless:!0});return w.setAttribute("data-action",L),w};s&&F.appendChild(P("copy","Copy message","copy")),c&&F.appendChild(P("volume-2","Read aloud","read-aloud")),i&&F.appendChild(P("thumbs-up","Upvote","upvote")),l&&F.appendChild(P("thumbs-down","Downvote","downvote")),p&&F.appendChild(P("refresh-cw","Regenerate response","regenerate")),u&&F.appendChild(P("pencil","Edit message","edit")),g&&F.appendChild(P("quote","Quote message","quote"));for(let K of f)F.appendChild(P(K.iconName??"ellipsis",K.label,QM(K.id)));return F},Yu=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",p=l.avatar,u=l.timestamp,g=p?.show??!1,f=u?.show??!1,v=p?.position??"left",h=u?.position??"below",M=Ua(t.role,c),A=k("div",M.join(" "));A.id=`bubble-${t.id}`,A.setAttribute("data-message-id",t.id),A.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let T=i?.widgetConfig?.theme?.components?.message;GM(A,t.role,c,t.role==="user"?T?.user:T?.assistant),c==="flat"?(A.style.backgroundColor="transparent",A.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let F=BM(t),P=t.content?.trim()??"",x=F.length>0&&P===ii,L=hc(i?.widgetConfig?.features?.streamAnimation),w=i?.widgetConfig?.features?.streamAnimation?.plugins,_=t.role==="assistant"&&L.type!=="none"?ma(L.type,w):null,G=t.role==="assistant"&&_?.isAnimating?.(t)===!0,ie=t.role==="assistant"&&_!==null&&(!!t.streaming||G);ie&&_?.bubbleClass&&A.classList.add(_.bubbleClass);let oe=document.createElement("div");oe.classList.add("persona-message-content"),t.streaming&&oe.classList.add("persona-content-streaming"),ie&&_&&(_.containerClass&&oe.classList.add(_.containerClass),oe.style.setProperty("--persona-stream-step",`${L.speed}ms`),oe.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let S=ie?yc(t.content??"",L.buffer,_,t,!!t.streaming):t.content??"",O=()=>{let Ce=e({text:S,message:t,streaming:!!t.streaming,raw:t.rawContent});return ie&&_?.wrap==="char"?fa(Ce,"char",t.id,{skipTags:_.skipTags}):ie&&_?.wrap==="word"?fa(Ce,"word",t.id,{skipTags:_.skipTags}):Ce},R=null;if(x?(R=document.createElement("div"),R.innerHTML=O(),R.style.display="none",oe.appendChild(R)):t.contentSegments?.length?UM(oe,t.contentSegments,Ce=>e({text:Ce,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):oe.innerHTML=O(),ie&&_?.useCaret&&!x&&P){let Ce=bc(),$=oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pe=$[$.length-1];if(Pe?.parentNode)Pe.parentNode.insertBefore(Ce,Pe.nextSibling);else{let Ne=oe.lastElementChild;Ne?Ne.appendChild(Ce):oe.appendChild(Ce)}}if(f&&h==="inline"&&t.createdAt){let Ce=fv(t,u,"span");Ce.classList.add("persona-timestamp-inline");let $=oe.lastElementChild;$?$.appendChild(Ce):oe.appendChild(Ce)}if(F.length>0){let Ce=$M(F,!x&&!!P,()=>{x&&R&&(R.style.display="")});Ce?A.appendChild(Ce):x&&R&&(R.style.display="")}let I=_M(t);if(I.length>0){let Ce=qM(I);Ce&&A.appendChild(Ce)}let Y=OM(t);if(Y.length>0){let Ce=zM(Y);Ce&&A.appendChild(Ce)}let V=DM(t);if(V.length>0){let Ce=jM(V);Ce&&A.appendChild(Ce)}let ae=t.contentSegments?.length?null:NM(t.contextMentions);if(ae&&A.appendChild(ae),A.appendChild(oe),f&&h==="below"&&t.createdAt){let Ce=fv(t,u);Ce.classList.add("persona-mt-1"),A.appendChild(Ce)}let ce=t.role==="assistant"?HM(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Ce=!!(S&&S.trim()),$=L.placeholder==="skeleton",Pe=$&&L.buffer==="line"&&Ce;if(Ce)Pe&&A.appendChild(ha());else if($)A.appendChild(ha());else{let Ne=VM("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);Ne&&A.appendChild(Ne)}}ce&&t.stopReason&&!t.streaming&&(P||(oe.style.display="none"),A.appendChild(RM(t.stopReason,ce)));let me=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,we=i?.actionEligibility,ue=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&we?.canEdit===!0||o?.showQuote===!0&&we?.canQuote===!0||bv(o,"user").length>0);if((me||ue)&&o){let Ce=YM(t,ue?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,we);A.appendChild(Ce)}if(!g||t.role==="system")return A;let _e=k("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ct=KM(p,t.role);return v==="right"||v==="left"&&t.role==="user"?_e.append(A,ct):_e.append(ct,A),_e};var XM=40,JM=(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=he(e.name,XM);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(Q("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},vv=(t,e,n={})=>{let o=Q("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=Q("div",{className:"persona-welcome-head-text"},s,i),p=Q("div",{className:"persona-welcome-title-row"},o,c);return{host:Q("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},p,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==="",JM(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")},ZM="data-persona-welcome-plugin",Cv="data-persona-welcome-overlay",nd="persona-welcome-overlay-active",Xu=new WeakMap,Ju=(t,e,n)=>{n.setAttribute(ZM,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(Cv,""),t.classList.contains(nd)||(Xu.set(t,t.scrollTop),t.classList.add(nd),t.scrollTop=0)},Zu=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(Cv),t.classList.contains(nd)&&(t.classList.remove(nd),t.scrollTop=Xu.get(t)??t.scrollTop,Xu.delete(t))},wv=()=>{let t=Q("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=Q("div",{className:Ua("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(Q("div",{className:"persona-flex"},s)),t.hidden=!1},Sv=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,xv=(t,e)=>{if(Sv()||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 M=getComputedStyle(o);s=parseFloat(M.rowGap)||0;let A=t.previousElementSibling,T=t.nextElementSibling,P=o.getBoundingClientRect().top+(parseFloat(M.borderTopWidth)||0)+(parseFloat(M.paddingTop)||0)-o.scrollTop;i=Math.max(0,A?n.top-A.getBoundingClientRect().bottom-s:n.top-P),l=Math.max(0,T?T.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let p=getComputedStyle(t),u=parseFloat(p.paddingTop)||0,g=parseFloat(p.paddingBottom)||0,f=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(f))};return f.finished.then(h).catch(h),f},Av=(t,e,n)=>{if(e<=1||Sv()||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 eE="Hello \u{1F44B}",tE="I can answer questions and help you get things done here.",Mv=new WeakSet,fn=(t,e)=>!!t&&t[e]!==void 0,nE=(t,e)=>{!t||t.debug!==!0||!e.length||Mv.has(t)||(Mv.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Xo=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=Ha(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".'),nE(t,i),{title:fn(e,"title")?e.title:n?.welcomeTitle??eE,kicker:e?.kicker??"",subtitle:fn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??tE,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}},Ev=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",mi=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var Tv="16px",tg="10px",ng="14px",kv=t=>{let e=t?.launcher?.enabled??!0,n=Rt(t);if(_a(t)){let g=t?.launcher?.composerBar??{},f=k("div","persona-widget-wrapper persona-fixed persona-transition");f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=g.expandedSize??"anchored",f.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%",f.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:f,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"),f=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(f),{wrapper:g,panel:f}}if(!e){let g=k("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),f=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,f.style.width="100%",g.appendChild(f),{wrapper:g,panel:f}}let s=t?.launcher??{},i=s.position&&Nn[s.position]?Nn[s.position]:Nn["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??Yo;return c.style.width=u,c.style.maxWidth=u,l.appendChild(c),{wrapper:l,panel:c}},og=t=>{let e=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":qu(t)}});return e.hidden=!0,e},Pv=(t,e)=>{let n=og("starter"),o=vv(t,n,{flatShadow:Rt(t)}),s=Xo(t);od(o,s),gi(e,o.host,mi(s,t?.initialMessages));let i=wv();return rd(i,s.message,t),{welcome:o,greetingHost:i}},oE=(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:Tv,iconSize:tg});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 _=ui(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Tv,iconSize:ng});l=_.button,c=_.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let p=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:g,greetingHost:f}=Pv(t,u),{host:v,title:h,subtitle:M}=g,A=g.starterSuggestions,T=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),F=og("followUp"),P=Tr(t,!0);P&&(T.style.maxWidth=P,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),u.append(v,f,T,F);let K=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),x=ed({config:t}),{root:L,textNode:w}=uv();return n.append(p,s,u,K),c&&n.appendChild(c),{container:n,body:u,messagesWrapper:T,starterSuggestions:A,transcriptSuggestions:F,composerOverlay:K,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:f,introKicker:g.kicker,introTitle:h,introSubtitle:M,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:k("span"),headerTitle:k("span"),headerSubtitle:k("span"),header:p,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:L,peekTextNode:w}},Iv=(t,e=!0)=>{if(_a(t))return oE(t,e);let n=Q("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,s=t?.layout?.showHeader!==!1,i=o?Zc(t,o,{showClose:e}):ys({config:t,showClose:e}),l=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:p}=Pv(t,l),{host:u,title:g,subtitle:f}=c,v=c.starterSuggestions,h=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),M=og("followUp"),A=Tr(t,!1);A&&(h.style.maxWidth=A,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),l.append(u,p,h,M);let T=Na({config:t}),F=t?.layout?.showFooter!==!1;s?Da(n,i,t):(i.header.style.display="none",Da(n,i,t)),n.append(l);let P=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return F||(T.footer.style.display="none"),n.append(T.footer),n.append(P),{container:n,body:l,messagesWrapper:h,starterSuggestions:v,transcriptSuggestions:M,composerOverlay:P,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:u,welcomeIconHolder:c.iconHolder,greetingHost:p,introKicker:c.kicker,introTitle:g,introSubtitle:f,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:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};var rg=(t,e)=>{let n=k("button");n.type="button",n.innerHTML=`
|
|
16
|
+
`),c=Array.isArray(e.contentParts)&&e.contentParts.length>0,p=s.contentParts.length>0;if(c){let u=[];i&&u.push(Eo(i)),u.push(...s.contentParts),u.push(...e.contentParts),e.contentParts=u}else if(p){let u=[];l&&u.push(Eo(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=vc(),l=ei();this.activeAssistantMessageId=null;let c=n?.contentParts&&Ac(n.contentParts)?ii:"",p={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(p),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,n?.mentions){let f=this.messages.find(v=>v.id===i)??p;if(await this.applyMentionBundle(f,o,n.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let f=this.messages.find(h=>h.id===i)??p,v=qy({quote:n.quote,text:f.llmContent??f.content,contentParts:f.contentParts});v.contentParts&&(f.contentParts=v.contentParts),v.llmContent!==void 0&&(f.llmContent=v.llmContent),(v.contentParts||v.llmContent!==void 0)&&(f.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(f){if(this.status==="resuming"||this.reconnecting)return;let v=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));if(!v){let h=bu(f,this.config.errorMessage);if(h){let M={id:l,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(f instanceof Error?this.callbacks.onError?.(f):this.callbacks.onError?.(new Error(String(f))))}}resubmitFrom(e,n){let o=zy(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,f=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]}:{},...f?.length?{contentSegments:[...f]}:{},...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=ei();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=bu(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 p=this.config.approval,u=p&&typeof p=="object"?p.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 f=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}`)}f=g.body}else g instanceof ReadableStream&&(f=g);f?await this.connectStream(f,{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 f=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||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,f=Array.isArray(g?.questions)?g.questions:[];if(f.length===1){let v=typeof f[0]?.question=="string"?f[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,p=e.toolCall?.args,u=Array.isArray(p?.questions)?p.questions:[];if(u.length===0){let g=typeof n=="string"?n:Object.entries(n).map(([f,v])=>`${f}: ${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((f,v)=>{let h=typeof f?.question=="string"?f.question:"";if(!h)return;let M=g[h],A=Array.isArray(M)?M.join(", "):typeof M=="string"?M:"";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:A||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let g=await this.client.resumeFlow(s,{[i]:n});if(!g.ok){let f=await g.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${g.status}`)}g.body?await this.connectStream(g.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(g){let f=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||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!==Ar?!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=await Promise.all(n.map(async c=>{let p=c.toolCall?.name,u=c.toolCall?.id;if(!p||!u)return null;let g=`${e}:${u}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(g),o.push(g);let f=this.markWebMcpToolRunning(c),v=c.agentMetadata?.webMcpToolCallId??p;if(p===Ar)return{dedupeKey:g,resumeKey:v,output:wy(),toolMessage:c,startedAt:f,completedAt:Date.now()};let h=this.client.executeWebMcpToolCall(p,c.toolCall?.args,s.signal),M;if(!h)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await h}catch(A){let T=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));return T||this.callbacks.onError?.(A instanceof Error?A:new Error(String(A))),this.markWebMcpToolComplete(c,vu(T?"Aborted by cancel()":iA(A)),f),this.webMcpInflightKeys.delete(g),null}return s.signal.aborted?(this.markWebMcpToolComplete(c,vu("Aborted by cancel()"),f),this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:v,output:M,toolMessage:c,startedAt:f,completedAt:Date.now()}})),l=[];try{if(l=i.filter(u=>u!==null),l.length===0)return;let c={};for(let u of l)c[u.resumeKey]=u.output;let p=await this.client.resumeFlow(e,c,{signal:s.signal});if(!p.ok){let u=await p.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${p.status}`)}for(let u of l)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===Ar?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,vu("Aborted by cancel()"),u.startedAt)}finally{for(let c of o)this.webMcpInflightKeys.delete(c);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 step_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 step_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});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=wr(this.config.features?.artifacts,e),s=ba(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=wr(this.config.features?.artifacts,n),i=ba(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=Qy().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=>bu(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=ei(),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=hu(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return mu(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=hu(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,f=n.approval;l.approval={...g,...f,executionId:f.executionId||g.executionId,toolName:f.toolName||g.toolName,description:f.description||g.description,toolType:f.toolType??g.toolType,reason:f.reason??g.reason,parameters:f.parameters??g.parameters}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,u=n.toolCall?.id;if(c&&Yy(c)&&p&&u&&n.agentMetadata?.awaitingLocalTool===!0){let g=`${p}:${u}`,f=this.webMcpInflightKeys.has(g),v=this.webMcpResolvedKeys.has(g),h=s.toolCall?.name,M=s.agentMetadata?.executionId===p&&s.toolCall?.id===u&&h!==void 0&&Yy(h)&&s.toolCall?.status==="complete";(f||v||M)&&(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 aA,FileCode as lA,FileSpreadsheet as cA,FileText as Cu,X as dA}from"lucide";var pA={add:t=>ky(t)},uA=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Ic={allowedTypes:Qo,maxFileSize:10*1024*1024,maxFiles:4};function gA(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function mA(t){return t==="application/pdf"?Cu:t.startsWith("text/")?Cu:t.includes("word")?Cu:t.includes("excel")||t.includes("spreadsheet")?cA:t==="application/json"?lA:aA}var Ea=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Ic.allowedTypes,maxFileSize:e.maxFileSize??Ic.maxFileSize,maxFiles:e.maxFiles??Ic.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:pA}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:Ic.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=Py(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:gA(),file:o,previewUrl:Mc(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=uA(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=Mc(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 f=mA(e.file.type),v=en(f,20,"var(--persona-muted, #6b7280)",1.5);v&&g.appendChild(v);let h=k("span");h.textContent=Iy(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=Q("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=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=he("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 p=k("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");p.type="button",p.setAttribute("aria-label","Remove attachment"),p.style.position="absolute",p.style.top="-4px",p.style.insetInlineEnd="-4px",p.style.width="18px",p.style.height="18px",p.style.borderRadius="50%",p.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",p.style.border="none",p.style.cursor="pointer",p.style.display="flex",p.style.alignItems="center",p.style.justifyContent="center",p.style.padding="0";let u=en(dA,10,"var(--persona-text-inverse, #ffffff)",2);u?p.appendChild(u):(p.textContent="\xD7",p.style.color="var(--persona-text-inverse, #ffffff)",p.style.fontSize="14px",p.style.lineHeight="1"),p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(p),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 Xy=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),fA=(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 Jy(){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(f=>Object.freeze({...f}))),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),p=()=>{if(o=!1,s||e.size===0)return;let g=c();for(let f of[...e])try{f(g)}catch(v){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",v)}},u=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(p))};return{getState:c,subscribe:g=>(e.add(g),()=>e.delete(g)),setText:g=>{t.text!==g&&(t.text=g,u())},setAttachments:g=>{fA(t.attachments,g)||(t.attachments=[...g],u())},setMentionRefs:g=>{Xy(t.mentionRefs,g)||(t.mentionRefs=[...g],u())},setSelectedModelId:g=>{t.selectedModelId!==g&&(t.selectedModelId=g,u())},setActiveModeIds:g=>{Xy(t.activeModeIds,g)||(t.activeModeIds=[...g],u())},setQuote:g=>{let f=t.quote;f?.text===g?.text&&f?.messageId===g?.messageId&&f?.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&&p()},destroy:()=>{s=!0,o=!1,e.clear()}}}var Mn=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},Zy=(t,e)=>{let n=k("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function eb(t,e={}){let n=Mn(t,"[data-persona-composer-form]"),o=Mn(t,"[data-persona-composer-input]");if(!n||!o){let F=`[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(F);return typeof console<"u"&&console.warn(F),null}let s={header:Mn(t,"[data-persona-composer-header]"),body:Mn(t,"[data-persona-composer-body]"),actionsStart:Mn(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Mn(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Mn(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Mn(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Mn(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=Zy("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,p=(T,F,P,K,x)=>{if(F)return F;i.add(T);let L=Zy(P,K);return x.appendChild(L),L},u=p("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),g=p("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),f=p("suggestions",s.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),v=p("status",s.status,"persona-widget-composer__status","data-persona-composer-status",t),h=[],M=(T,F)=>T.target===F.target&&T.type===F.type&&T.handler===F.handler,A=Mn(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:f,status:v,attachmentInput:A,attachmentPreviews:Mn(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Mn(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Mn(t,"[data-persona-composer-submit]")??void 0,micButton:Mn(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(T,F,P,K)=>{T.addEventListener(F,P,K),h.push({target:T,type:F,handler:P,options:K})},removeListener:(T,F,P,K)=>{T.removeEventListener(F,P,K),h=h.filter(x=>!M(x,{target:T,type:F,handler:P}))},destroy:()=>{for(let T of h)T.target.removeEventListener(T.type,T.handler,T.options);h=[]}}}var hA=8,yA=8,wu=10,tb=200,nb=300,ob=0,Hc=t=>Math.max(0,t);function rb(t){t.delayMs!==void 0&&(tb=Hc(t.delayMs)),t.skipDelayMs!==void 0&&(nb=Hc(t.skipDelayMs))}var bA=()=>Date.now()<ob,vA=t=>{ob=t>0?Date.now()+t:0},Lc=new WeakMap,xu="data-persona-tooltip-suppressed",CA=t=>typeof t.closest=="function"&&t.closest(`[${xu}]`)!==null;function sb(t){Lc.get(t)?.hide()}var ib=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,wA=t=>{let e=t.getRootNode?.();return ib(e)?e:t.ownerDocument.body},Su=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),SA=[...["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 Yt(t){Lc.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:s,enabled:i=!0,gap:l=hA,viewportPadding:c=yA}=t,p=()=>e.ownerDocument,u=()=>p().defaultView??window,g=null,f=null,v=null,h=null,M,A=!1,T=!1,F=!1,P=()=>(typeof o=="function"?o():o).trim(),K=()=>(typeof s=="function"?s():s??"").trim(),x=()=>Hc(t.delayMs??tb),L=()=>Hc(t.skipDelayMs??nb),w=()=>{M!==void 0&&(u().clearTimeout(M),M=void 0)},O=()=>{w();let me=g!==null;h?.(),h=null,g?.remove(),g=null,f=null,v=null,me&&vA(L())},G=()=>{if(!g)return;let me=p(),Ce=u(),ue=e.getBoundingClientRect(),_e=g.getBoundingClientRect(),ct=me.documentElement.clientWidth||Ce.innerWidth,we=me.documentElement.clientHeight||Ce.innerHeight,$=ct-c-_e.width,Pe=ue.left+ue.width/2-_e.width/2,Ne=Su(Pe,c,$),xe=ue.top-c,Oe=we-c-ue.bottom,ye=_e.height+l,gt=xe>=ye||xe>=Oe?"top":"bottom",Zn=gt==="top"?ue.top-l-_e.height:ue.bottom+l,Cs=we-c-_e.height,Jt=Su(Zn,c,Cs),Fn=ue.left+ue.width/2,Io=Math.max(wu,_e.width-wu),It=Su(Fn-Ne,wu,Io);g.dataset.placement=gt,g.style.left=`${Ne}px`,g.style.top=`${Jt}px`,g.style.setProperty("--persona-tooltip-arrow-x",`${It}px`)},ie=()=>{if(F||!i||g||!e.isConnected||CA(e))return;let me=P(),Ce=wA(e);if(!me||!Ce)return;let ue=p(),_e=u();g=ue.createElement("div"),g.className="persona-control-tooltip",g.setAttribute("role","tooltip"),g.dataset.state="measuring",g.style.zIndex=String(gc);let ct=_e.getComputedStyle?.(e);if(ct){for(let ye of SA){let gt=ct.getPropertyValue(ye).trim();gt&&g.style.setProperty(ye,gt)}ct.fontFamily&&(g.style.fontFamily=ct.fontFamily)}f=ue.createElement("span"),f.className="persona-control-tooltip__label",f.textContent=me,g.appendChild(f);let we=K();we&&(v=ue.createElement("span"),v.className="persona-control-tooltip__hint",v.textContent=we,g.appendChild(v));let $=ue.createElement("span");$.className="persona-control-tooltip__arrow",g.appendChild($),Ce.appendChild(g),G(),g.dataset.state="open";let Pe=()=>{if(!e.isConnected){O();return}f&&(f.textContent=P()),v&&(v.textContent=K()),G()};_e.addEventListener("scroll",Pe,!0),_e.addEventListener("resize",Pe);let Ne=e.getRootNode(),xe=ib(Ne)?Ne:ue.documentElement,Oe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||O()});Oe?.observe(xe,{childList:!0,subtree:!0}),h=()=>{_e.removeEventListener("scroll",Pe,!0),_e.removeEventListener("resize",Pe),Oe?.disconnect()}},oe=me=>{if(!(F||g)){if(w(),me||x()<=0||bA()){ie();return}M=u().setTimeout(()=>{M=void 0,ie()},x())}},S=()=>{A||T?oe(T):O()},_=()=>{let me=u();(!me.matchMedia||!me.matchMedia("(hover: none)").matches)&&(A=!0,S())},R=()=>{A=!1,S()},I=()=>{try{T=e.matches(":focus-visible")}catch{T=!0}S()},Y=()=>{T=!1,S()},V=()=>{A=!1,T=!1,O()},ae=me=>{me.key==="Escape"&&V()};n.addEventListener("mouseenter",_),n.addEventListener("mouseleave",R),e.addEventListener("focus",I),e.addEventListener("blur",Y),e.addEventListener("keydown",ae),e.addEventListener("click",V);let ce={get isOpen(){return g!==null},show:ie,hide:O,reposition:G,destroy:()=>{F||(F=!0,O(),n.removeEventListener("mouseenter",_),n.removeEventListener("mouseleave",R),e.removeEventListener("focus",I),e.removeEventListener("blur",Y),e.removeEventListener("keydown",ae),e.removeEventListener("click",V),Lc.delete(e))}};return Lc.set(e,ce),ce}var ab=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];ab(i)&&ab(s)?n[o]=ai(i,s):n[o]=s}return n}var Yo="min(440px, calc(100vw - 24px))",cb="440px",Au="How can I help...",xA={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:Yo,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:xA,copy:{inputPlaceholder:Au,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 lb(t,e){if(!(!t&&!e))return t?e?ai(t,e):t:e}function Rc(t){return t?{...nt,...t,theme:lb(nt.theme,t.theme),darkTheme:lb(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,p=t.features?.streamAnimation,u=nt.features?.askUserQuestion,g=t.features?.askUserQuestion,f=nt.features?.history,v=t.features?.history,h=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},M=o===void 0&&s===void 0?void 0:{...o,...s},A=i===void 0&&l===void 0?void 0:{...i,...l},T=c===void 0&&p===void 0?void 0:{...c,...p},F=u===void 0&&g===void 0?void 0:{...u,...g,styles:{...u?.styles,...g?.styles}},P=f===void 0&&v===void 0?void 0:{...f,...v,copy:{...f?.copy,...v?.copy}};return{...nt.features,...t.features,...M!==void 0?{scrollToBottom:M}:{},...A!==void 0?{scrollBehavior:A}:{},...h!==void 0?{artifacts:h}:{},...T!==void 0?{streamAnimation:T}:{},...F!==void 0?{askUserQuestion:F}:{},...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 Mu(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 Wc(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function db(t,e){t.style.maxHeight=`${e*Mu(t)}px`,t.style.overflowY="auto"}function Pa(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 pb(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function ub(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||!pb(e)}function AA(t){return(t.submitKey??"enter")!=="enter"||pb(t)?"enter":"send"}function Bc(t,e){t.setAttribute("enterkeyhint",AA(e))}function _c(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 Eu(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 Dn="persona-composer-control",co="persona-composer-control--glyph",ku=40,un=24,Oc=(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)}},Dc=(t,e)=>{let n=k("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??Au,n.dir="auto",Bc(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:Pa(n)}),_c(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=Wc(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 p=o*Mu(n);return s=`${p}px`,n.style.maxHeight=s,p},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}},EA="[data-persona-glyph-stack]",Pu=(t,e,n="send")=>{let o=Q("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},Nc=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",p=t?.copy?.sendButtonLabel??"Send",u=t?.copy?.stopButtonLabel??"Stop",g=e.showTooltip??!1,f=e.size,v=parseFloat(f??"")||ku,h=e.backgroundColor,M=e.textColor,A=k("div","persona-send-button-wrapper"),T=Q("button",{className:On("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Dn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!M&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?M||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":M||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}}),F=null,P=null,K=null;if(n){let w=parseFloat(e.iconSize??"")||Math.round(v*.5),O=e.iconStrokeWidth??2,G=M?.trim()||"currentColor";s&&(F=he(s,w,G,O)),P=he(i,w,G,O),F&&P?(K=Pu(F,P),T.appendChild(K)):F?T.appendChild(F):(T.textContent=o,P=null)}else T.textContent=p;T.setAttribute("aria-label",l),A.appendChild(T),Yt({anchor:T,trigger:A,text:()=>T.getAttribute("aria-label")??"",enabled:g});let x="send";return{button:T,wrapper:A,setMode:w=>{if(w===x)return;x=w;let O=w==="stop"?c:l;T.setAttribute("aria-label",O),T.setAttribute("data-persona-send-mode",w),n?(T.querySelector(EA)??K)?.setAttribute("data-mode",w):T.textContent=w==="stop"?u:p},glyphStack:K}},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",p=e.iconSize,u=parseFloat(p??"")||un,g=e.backgroundColor??t?.sendButton?.backgroundColor,f=e.iconColor??t?.sendButton?.textColor,v=k("div","persona-send-button-wrapper"),h=Q("button",{className:On("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Dn,!p&&co),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:f||"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}}),A=he(c,u,f||"currentColor",1.5);A?h.appendChild(A):h.textContent="\u{1F3A4}",v.appendChild(h);let T=e.tooltipText??"Start voice recognition",F=e.showTooltip??!1;return Yt({anchor:h,trigger:v,text:()=>h.getAttribute("aria-label")??T,enabled:F}),{button:h,wrapper:v}},Fc=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??Qo).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=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Dn} ${co}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),c=he(s,un,"currentColor",1.5);c?l.appendChild(c):l.textContent="\u{1F4CE}",l.addEventListener("click",u=>{u.preventDefault(),o.click()}),i.appendChild(l);let p=e.buttonTooltipText??"Attach file";return Yt({anchor:l,trigger:i,text:()=>l.getAttribute("aria-label")??p}),{button:l,wrapper:i,input:o,previewsContainer:n}},Uc=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},$c=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var TA='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',kA=["--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"],Iu="data-persona-menu-focus",PA=new Set(["ArrowDown","ArrowUp","Home","End"]);function gb(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(TA)??t}var IA=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function mb(t){let e=t.label,n=!1,o=k("div","persona-send-button-wrapper"),s=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Dn} ${co}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=Q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),l=()=>{let I=t.getButtonSize?.()??"";s.style.width=I,s.style.height=I,s.style.minWidth=I,s.style.minHeight=I,s.style.lineHeight="1",s.replaceChildren();let Y=he("plus",un,"currentColor",1.5);Y?s.appendChild(Y):s.textContent="+"},c=()=>{s.setAttribute("aria-label",e),s.setAttribute("title",e),i.setAttribute("aria-label",e)};c(),l();let p=[],u=-1,g=!1,f=()=>{let Y=i.getRootNode().activeElement;return Y instanceof HTMLElement?Y:null},v=()=>{let I=f();for(let Y of p){let V=!!I&&gb(Y)===I;Y.toggleAttribute(Iu,V&&g)}},h=()=>p.filter(I=>I.isConnected||i.contains(I)).map(gb).filter(I=>!IA(I)),M=(I,Y)=>{I.forEach((V,ae)=>{V.setAttribute("tabindex",ae===Y?"0":"-1")})},A=I=>{let Y=h();if(Y.length===0)return;let V=(I%Y.length+Y.length)%Y.length;u=V,M(Y,V),Y[V].focus(),v()},T=()=>o.ownerDocument??document,F=null,P=null,K=null,x=()=>{F&&(T().removeEventListener("focusin",F,!0),F=null)},L=()=>{P&&(i.removeEventListener("focusin",P),P=null),K&&(i.removeEventListener("pointerdown",K,!0),K=null)},w=null,O=()=>(w||(w=mc({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),x()}})),w),G=()=>w?.isOpen===!0,ie=(I=!1)=>{if(G()){w?.close(),s.setAttribute("aria-expanded","false"),x(),L(),u=-1,g=!1;for(let Y of p)Y.removeAttribute(Iu);I&&s.focus()}},oe=(I=0,Y=!1)=>{if(n||G())return;g=Y,Oc(s,i,kA),O().open(),s.setAttribute("aria-expanded","true");let V=h();M(V,-1),A(I<0?V.length-1:I),F=ae=>{let ce=typeof ae.composedPath=="function"?ae.composedPath():[];ce.includes(i)||ce.includes(o)||ie()},T().addEventListener("focusin",F,!0),P=()=>v(),i.addEventListener("focusin",P),K=()=>{g=!1},i.addEventListener("pointerdown",K,!0)},S=I=>{I.preventDefault(),I.stopPropagation(),G()?ie(!0):oe(0)},_=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),g=!0,G()?A(0):oe(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),g=!0,G()?A(-1):oe(-1,!0))},R=I=>{switch(PA.has(I.key)&&(g=!0),I.key){case"ArrowDown":I.preventDefault(),A(u+1);return;case"ArrowUp":I.preventDefault(),A(u-1);return;case"Home":I.preventDefault(),A(0);return;case"End":I.preventDefault(),A(h().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),ie(!0);return;case"Tab":ie(!0);return;default:}};return s.addEventListener("click",S),s.addEventListener("keydown",_),i.addEventListener("keydown",R),{trigger:o,triggerButton:s,panel:i,setItems:I=>{for(let V of p)I.includes(V)||V.removeAttribute(Iu);if(p=[...I],!G())return;let Y=h();M(Y,Math.min(u,Y.length-1)),v()},isOpen:G,open:()=>oe(0),close:ie,setLabel:I=>{I!==e&&(e=I,c())},applyButtonSize:l,destroy:()=>{n=!0,x(),L(),s.removeEventListener("click",S),s.removeEventListener("keydown",_),i.removeEventListener("keydown",R),w?.destroy(),w=null,o.remove(),i.remove(),p=[]}}}var ko={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},fb="data-persona-composer-action",Lu="data-persona-composer-disable-when-streaming",LA="core:overflow",HA=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function RA(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 Hu(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 hb=(t,e)=>{!t||typeof console>"u"||console.warn(e)},WA=(t,e)=>e.includes(":")?e:`${t}:${e}`;function BA(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let p=o.get(c.id);if(p){hb(e,`[Persona] composer action "${c.id}" is already contributed by ${yb(p)}; the ${yb(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,p,u)=>{let g=u?WA(u,c.id):c.id,f=c.order??ko.custom;c.placement==="end"&&f>=ko.send&&(hb(e,`[Persona] composer action "${g}" ordered at ${f} would render after send; clamped to ${ko.send-1}.`),f=ko.send-1),i({id:g,placement:c.placement,presentation:c.presentation??"bar",order:f,sequence:s++,source:p,pluginId:u,action:c})};for(let c of t.configActions??[])l(c,"config");for(let c of t.plugins){if(!c.contributeComposerActions)continue;let p;try{p=c.contributeComposerActions(t.contributionContext)}catch(u){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,u);continue}for(let u of p??[])l(u,"plugin",c.id)}return n.sort((c,p)=>c.order===p.order?c.sequence-p.sequence:c.order-p.order)}var yb=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",bb=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,_A=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function OA(t,e){if(!t||t==="always")return!0;let n=_A(e);return t==="when-text"?n:!n}var Er=t=>t.kind==="custom",Ru=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,DA=t=>{let e=Ru(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},NA='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function FA(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(NA)||o.childNodes.forEach(n)};return n(t),e.trim()}var UA=t=>FA(t).length===0;function vb(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(S,_)=>{let R=S.button;if(!R)return;R.setAttribute("role","menuitem"),R.setAttribute("tabindex","-1"),R.className="persona-composer-overflow-menu__item";for(let V of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])R.style[V]="";R.style.lineHeight="1",_.tooltipText?R.setAttribute("title",_.tooltipText):R.removeAttribute("title"),R.replaceChildren();let I=k("span","persona-composer-overflow-menu__icon");if(_.iconName){let V=he(_.iconName,16,"currentColor",1.5);V&&I.appendChild(V)}let Y=k("span","persona-composer-overflow-menu__label");Y.textContent=_.shortLabel??_.label,R.append(I,Y)},l=(S,_)=>{let R=S.button;if(!R)return;if(R.setAttribute("aria-label",_.label),_.pressed===void 0?R.removeAttribute("aria-pressed"):R.setAttribute("aria-pressed",_.pressed?"true":"false"),R.toggleAttribute(Lu,_.disableWhenStreaming===!0),S.mode==="menu"){S.tooltip?.destroy(),S.tooltip=void 0,i(S,_);return}R.removeAttribute("role"),R.removeAttribute("tabindex"),R.removeAttribute("title");let I=s(),Y=!!_.shortLabel;if(R.className=On("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Dn,co,Y&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),R.style.width=I&&!Y?I:"",R.style.height=I??"",R.style.minWidth=I&&!Y?I:"",R.style.minHeight=I??"",R.style.fontSize=Y?"":"18px",R.style.lineHeight="1",R.style.color=_.iconColor??"",R.style.backgroundColor=_.backgroundColor??"",R.replaceChildren(),_.iconName){let V=he(_.iconName,un,"currentColor",1.5);V&&R.appendChild(V)}if(Y){let V=k("span","persona-composer-action-button__label");V.textContent=_.shortLabel,R.appendChild(V)}else R.firstChild||(R.textContent=_.label);S.tooltip?.destroy(),S.tooltip=Yt({anchor:R,trigger:S.element,text:()=>_.tooltipText??_.label,enabled:!!_.tooltipText})},c=(S,_)=>{let R=S.action,I=Q("button",{attrs:{type:"button"}}),Y=I;if(_==="bar"){let ce=k("div","persona-send-button-wrapper");ce.appendChild(I),Y=ce}Y.setAttribute(fb,S.id);let V={resolved:S,element:Y,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:_},ae=ce=>{if(ce.preventDefault(),ce.stopPropagation(),V.busy||I.disabled)return;let me=V.resolved.action;V.mode==="menu"&&h?.close(!0);let Ce;try{Ce=me.onSelect(t.actionContext,ce)}catch(ue){t.reportError(ue,{actionId:V.resolved.id});return}!Ce||typeof Ce.then!="function"||(V.busy=!0,I.setAttribute("aria-busy","true"),Ce.catch(ue=>{t.reportError(ue,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",ae),V.detach=()=>I.removeEventListener("click",ae),l(V,R),V},p=S=>{let _=S.action,R;try{R=_.render({...t.actionContext,id:S.id,action:_})}catch(I){return t.reportError(I,{actionId:S.id}),null}return R?.element?(R.element.setAttribute(fb,S.id),R.element.toggleAttribute(Lu,_.disableWhenStreaming===!0),{resolved:S,element:R.element,owned:!0,managed:!0,destroy:R.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(S,_)=>{if(S.builtIn){let I=S.builtIn.element;return I?{resolved:S,element:I,owned:!1,managed:S.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let R=S.action;return R?Er(R)?p(S):c(S,_):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(_){t.reportError(_,{actionId:S.resolved.id})}S.element.remove()}},f=(S,_)=>{for(let R=0;R<_.length;R++){let I=_[R];if(!I.managed)continue;let Y=null;for(let V=R+1;V<_.length;V++){let ae=_[V];if(!ae.managed&&ae.element.parentElement===S){Y=ae.element;break}}Y?(I.element.parentElement!==S||I.element.nextSibling!==Y)&&S.insertBefore(I.element,Y):S.lastChild!==I.element&&S.appendChild(I.element)}},v=(S,_)=>{if(S.button){S.button.disabled=_;return}if(!S.owned)return;let R=S.element;R.toggleAttribute("data-disabled",_),R.setAttribute("aria-disabled",_?"true":"false");let I=R instanceof HTMLButtonElement||R instanceof HTMLSelectElement||R instanceof HTMLInputElement||R instanceof HTMLTextAreaElement?R:R.querySelector("button, select, input, textarea");I&&(I.disabled=_)},h=null,M=null,A=null,T=0,F=()=>{let S=t.getOverflow?.();return S?.enabled===!0?S:void 0},P=()=>(h?h.setLabel(t.getOverflowLabel?.()??"More actions"):h=mb({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),h),K=S=>{M!==S&&(A?.disconnect(),M=S,T=Hu(S),!(typeof ResizeObserver>"u")&&(A=new ResizeObserver(_=>{let I=_[_.length-1]?.contentRect?.width??Hu(S);I!==T&&(T=I,ie())}),A.observe(S)))},x=(S,_)=>{let R=RA(S.collapseAutoActionsBelow,_);if(R===null)return!1;let I=T||Hu(_);return I>0&&I<R},L=(S,_,R)=>{if(!_)return"bar";if(S.resolved.builtIn){let Y=HA(S.resolved.id);return Y&&_.includeBuiltIns?.includes(Y)?"menu":"bar"}let I=S.resolved.presentation;return I==="overflow"||I==="auto"&&R?"menu":"bar"},w=S=>{let _=S.menuSlot;if(!_)return;if(!UA(S.element)){S.menuLabel?.remove(),S.menuLabel=void 0;return}let R=DA(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!==_&&_.appendChild(S.menuLabel)},O=(S,_)=>{if(S.mode===_)return S;let R=S.resolved.action;if(R&&!Er(R)){g(S),e.delete(S.resolved.id);let I=c(S.resolved,_);return e.set(S.resolved.id,I),I}if(_==="menu"){let I=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[xu]:""}});I.appendChild(S.element),sb(Ru(S.element)),S.menuSlot=I;let Y=V=>{let ae=Ru(S.element);if(ae.disabled)return;let ce=V.target===ae||ae.contains(V.target);h?.close(!0),ce||ae.click()};I.addEventListener("click",Y,!0),S.detachMenuSlot=()=>I.removeEventListener("click",Y,!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=_,S},G=(S,_)=>{let R=_.map(I=>I.menuSlot??I.element);for(R.forEach((I,Y)=>{let V=S.children[Y];V!==I&&(V?S.insertBefore(I,V):S.appendChild(I))});S.children.length>R.length;)S.lastElementChild?.remove()},ie=()=>{if(o)return;let S=t.getBindings();if(!S)return;let _=t.getState(),R=_.phase==="streaming",I=F();I&&K(S.footer);let Y=I?x(I,S.footer):!1,V={start:[],end:[]},ae=[];for(let ce of n){let me=e.get(ce.id);if(!me)continue;let Ce=ce.action,ue=Ce?bb(Ce.visible,_,!0)&&OA(Ce.visibility,_):!0;if(me.visible!==ue&&(me.visible=ue,!ue&&me.managed&&(me.menuSlot??me.element).remove()),!!ue){if(me=O(me,L(me,I,Y)),Ce){let _e=bb(Ce.disabled,_,!1)||Ce.disableWhenStreaming===!0&&R;v(me,_e),!Er(Ce)&&Ce.pressed!==void 0&&me.button?.setAttribute("aria-pressed",Ce.pressed?"true":"false")}me.mode==="menu"?(w(me),ae.push(me)):V[ce.placement].push(me)}}if(ae.length>0){let ce=P();G(ce.panel,ae),ce.setItems(ae.map(_e=>_e.menuSlot??_e.element)),ce.applyButtonSize();let me=Number.isFinite(I?.order)?I?.order:ko.overflow,Ce=V.start.findIndex(_e=>_e.resolved.order>me),ue={resolved:{id:LA,placement:"start",presentation:"bar",order:me,sequence:-1,source:"core"},element:ce.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(Ce<0?V.start.length:Ce,0,ue)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));f(S.actionsStart,V.start),f(S.actionsEnd,V.end)};return{resolve:()=>{if(o)return;let S=BA(t.collect()),_=new Set(S.map(R=>R.id));for(let[R,I]of e)_.has(R)||(g(I),e.delete(R));for(let R of S){let I=e.get(R.id);if(!I){let ce=u(R,"bar");ce&&e.set(R.id,ce);continue}let Y=I.resolved.action,V=R.action;if(!!Y!=!!V||Y&&V&&Er(Y)!==Er(V)||Y&&V&&Er(Y)&&Er(V)&&Y.render!==V.render){g(I),e.delete(R.id);let ce=u(R,I.mode);ce&&e.set(R.id,ce);continue}I.resolved=R,R.builtIn?(I.managed=R.builtIn.managed===!0||I.mode==="menu",R.builtIn.element&&I.mode==="bar"&&(I.element=R.builtIn.element)):V&&!Er(V)?l(I,V):V&&I.element.toggleAttribute(Lu,V.disableWhenStreaming===!0)}n=S,ie()},sync:ie,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,A?.disconnect(),A=null,M=null;for(let S of e.values())g(S);e.clear(),h?.destroy(),h=null,n=[]}}}}var $A="core:model",qA=700,Cb=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"],wb=()=>{let t=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Sb(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=p=>{let u=t.getSelectedModelId();return p.find(g=>g.id===u)??p[0]},i=()=>{let p=Q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),u="",g=()=>{let A=t.getModels(),T=A.map(F=>`${F.id}:${F.label}`).join("|");T!==u&&(u=T,p.replaceChildren(...A.map(F=>{let P=Q("option",{attrs:{value:F.id}});return P.textContent=F.label,P}))),p.value=s(A)?.id??""};g(),o=g;let f=()=>{p.value&&t.onSelect(p.value)};p.addEventListener("change",f);let v=A=>A.stopPropagation();p.addEventListener("click",v);let{wrapper:h,chevron:M}=wb();return h.append(p,M),{element:h,destroy:()=>{o===g&&(o=null),p.removeEventListener("change",f),p.removeEventListener("click",v)}}},l=()=>{let p=Q("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),u=k("span","persona-composer-model-picker-label"),g=k("span","persona-composer-model-picker-suffix");p.append(u,g);let f=Q("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),v=new Map,h="",M=null,A=()=>M?.isOpen===!0,T=(_=!1)=>{A()&&(M?.close(),p.setAttribute("aria-expanded","false"),_&&p.focus())},F=_=>{let R=[...v.values()];if(R.length===0)return;let I=(_%R.length+R.length)%R.length;R[I].focus()},P=_=>{if(A())return;M||(M=mc({anchor:p,content:f,placement:"top-start",offset:6,onDismiss:()=>p.setAttribute("aria-expanded","false")})),Oc(p,f,zA),M.open(),p.setAttribute("aria-expanded","true");let I=[...v.keys()].indexOf(s(t.getModels())?.id??"");F(_??(I>=0?I:0))},K=_=>{T(!0),t.onSelect(_)},x=_=>{_.preventDefault(),_.stopPropagation();let R=_.currentTarget.getAttribute("data-persona-model-option");R&&K(R)},L=_=>{let R=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":_.id}});if(_.icon){let ce=he(_.icon,Cb,"currentColor",1.5);if(ce){let me=k("span","persona-composer-model-option-icon");me.appendChild(ce),R.appendChild(me)}}let I=k("span","persona-composer-model-option-body"),Y=k("span","persona-composer-model-option-label");if(Y.textContent=_.label,I.appendChild(Y),_.description){let ce=k("span","persona-composer-model-option-description");ce.textContent=_.description,I.appendChild(ce)}R.appendChild(I);let V=k("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let ae=he("check",Cb,"currentColor",2);return ae&&V.appendChild(ae),R.appendChild(V),R.addEventListener("click",x),R},w=()=>{let _=t.getModels(),R=_.map(V=>`${V.id}:${V.label}:${V.icon??""}:${V.description??""}`).join("|");if(R!==h){h=R;for(let V of v.values())V.removeEventListener("click",x);v.clear(),f.replaceChildren(..._.map(V=>{let ae=L(V);return v.set(V.id,ae),ae}))}let I=s(_);for(let[V,ae]of v)ae.setAttribute("aria-selected",String(V===I?.id));u.textContent=I?.label??"";let Y=t.getSuffix?.()??"";g.textContent=Y,p.setAttribute("aria-label",[e,[I?.label,Y].filter(Boolean).join(" ")].filter(Boolean).join(": "))};w(),o=w;let O=_=>{_.preventDefault(),_.stopPropagation(),A()?T(!0):P()},G=_=>{if(_.key==="ArrowDown"){_.preventDefault(),A()?F(0):P(0);return}_.key==="ArrowUp"&&(_.preventDefault(),A()?F(-1):P(-1))},ie=_=>{let R=[...v.values()],I=R.indexOf(_.target?.closest?.(".persona-composer-model-option"));switch(_.key){case"ArrowDown":_.preventDefault(),F(I+1);return;case"ArrowUp":_.preventDefault(),F(I-1);return;case"Home":_.preventDefault(),F(0);return;case"End":_.preventDefault(),F(R.length-1);return;case"Escape":_.preventDefault(),_.stopPropagation(),T(!0);return;case"Tab":T(!0);return;default:}};p.addEventListener("click",O),p.addEventListener("keydown",G),f.addEventListener("keydown",ie);let{wrapper:oe,chevron:S}=wb();return oe.append(p,S),{element:oe,destroy:()=>{o===w&&(o=null),p.removeEventListener("click",O),p.removeEventListener("keydown",G),f.removeEventListener("keydown",ie);for(let _ of v.values())_.removeEventListener("click",x);v.clear(),M?.destroy(),M=null,f.remove()}}};return{action:{id:$A,kind:"custom",placement:"end",order:qA,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var jA=":scope > [data-persona-composer-mode]";function xb(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=u=>{let g=Q("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let M=k("span","persona-mention-chip-icon"),A=he(u.iconName,12,"currentColor",1.5);A&&M.appendChild(A),g.appendChild(M)}let f=k("span","persona-mention-chip-label");f.textContent=u.shortLabel??u.label,g.appendChild(f);let v=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),h=he("x",12,"currentColor",2);return h?v.appendChild(h):v.textContent="\xD7",v.addEventListener("click",M=>{M.preventDefault(),M.stopPropagation(),t.onRemove(u.id)}),g.appendChild(v),g},l=()=>Array.from(e.querySelectorAll(jA)),c=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let g=()=>{u.remove(),fc(e)},f=e.ownerDocument.defaultView,v=typeof f?.getComputedStyle=="function"?f.getComputedStyle(u).animationName:"";if(!v||v==="none"){g();return}u.addEventListener("animationend",g,{once:!0}),u.addEventListener("animationcancel",g,{once:!0})},p=()=>{for(let u of l())u.remove()};return{element:e,render:(u,g)=>{if(o)return;let f=g.filter(A=>u.includes(A.id)),v=f.map(A=>`${A.id}:${A.shortLabel??A.label}`).join("|");if(v===n)return;n=v;let h=new Map;for(let A of l()){let T=A.getAttribute("data-persona-composer-mode");T&&f.some(P=>P.id===T)&&!A.hasAttribute("data-persona-chip-exit")?h.set(T,A):A.hasAttribute("data-persona-chip-exit")||c(A)}let M=e.firstChild;for(let A of f){let T=h.get(A.id);T||(T=i(A),s.has(A.id)||(T.setAttribute("data-persona-chip-enter",""),T.addEventListener("animationend",()=>T?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(A.id),T!==M&&e.insertBefore(T,M),M=T.nextSibling}fc(e)},destroy:()=>{o=!0,p(),fc(e)}}}var Ab=t=>`core:mode:${t}`;var Wu=t=>Math.min(300+t,499),Mb=t=>`core:mode-group:${t}`;function qc(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function VA(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Eb(t,e){return t?.length?t.filter(n=>!qc(n.groupId,e)&&!VA(n.groupId,e)):[]}var KA=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Tb(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(KA(s,o)==="single"){let c=n.filter(p=>p.groupId===s.groupId).map(p=>p.id);l=new Set([...l].filter(p=>!c.includes(p)))}l.add(e)}return n.filter(c=>l.has(c.id)).map(c=>c.id)}function zc(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function kb(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Pb(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var GA=16;function Ib(t){let e=null;return{action:{id:Mb(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=Q("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=u=>{u.preventDefault(),u.stopPropagation();let f=u.currentTarget.getAttribute("data-persona-composer-mode");!f||t.getActiveIds().includes(f)&&t.getGroup()?.selection==="single"||t.onSelect(f)},c=u=>{let g=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let v=he(u.iconName,GA,"currentColor",1.5);v&&g.appendChild(v)}let f=k("span","persona-composer-segmented-label");return f.textContent=u.shortLabel??u.label,g.appendChild(f),g.addEventListener("click",l),g},p=()=>{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(),f=g.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(f!==i){i=f;for(let M of s.values())M.removeEventListener("click",l);s.clear();let h=g.map(M=>{let A=c(M);return s.set(M.id,A),A});o.replaceChildren(...h)}let v=t.getActiveIds();for(let[h,M]of s)M.setAttribute("aria-pressed",String(v.includes(h)))};return p(),e=p,{element:o,destroy:()=>{e===p&&(e=null);for(let u of s.values())u.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function Lb(t){let e=Q("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 f=k("div","persona-composer-quote-source");f.textContent=i.sourceLabel,c.appendChild(f)}let p=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});p.textContent=Tc(i.text),c.appendChild(p);let u=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),g=he("x",12,"currentColor",2);g?u.appendChild(g):u.textContent="\xD7",u.addEventListener("click",f=>{f.preventDefault(),f.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 Hb(t){let e=Q("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,p,u)=>{let g=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[p]:""}}),f=he(l,12,"currentColor",2);return f?g.appendChild(f):g.textContent=c,g.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),u()}),g},i=l=>{let c=Tc(l.text??"",90);if(c)return c;let p=l.contentParts?.length??0;return p>0?p===1?"1 attachment":`${p} 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 p=Q("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});p.textContent=i(l),e.replaceChildren(c,p,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 Rb(t){let e=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=Q("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,p,u,g)=>{let f=Q("button",{className:`persona-message-edit-button ${p}`,attrs:{type:"button",[u]:""},text:c});return f.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),g()}),f},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 Wb(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 Bb(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(p=>n.has(p.sourceId)),s=o.length===(t.mentionRefs?.length??0)&&o.length>0,i=new Set(e.modes.map(p=>p.id)),l=(t.activeModeIds??[]).filter(p=>i.has(p)),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 _b(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 Ob(t){return t.wrapped||t.text.includes(`
|
|
17
|
+
`)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function Db(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function Nb(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 Bu(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 Ub(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var QA=t=>typeof t?.then=="function";function Fb(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 $b(t,e,n){let o;try{o=t(Bu(e),{signal:n})}catch(s){return{status:"error",error:s}}return QA(o)?Promise.resolve(o).then(s=>n.aborted?{status:"aborted"}:Fb(e,s),s=>n.aborted?{status:"aborted"}:{status:"error",error:s}):Fb(e,o)}function qb(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",s=e.buttonTooltipText??"Add context",i=k("div","persona-send-button-wrapper"),l=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Dn} ${co}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":s,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),c=he(o,un,"currentColor",1.5);return c?l.appendChild(c):l.textContent="+",l.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),n()}),i.appendChild(l),Yt({anchor:l,trigger:i,text:()=>l.getAttribute("aria-label")??s}),{button:l,wrapper:i}}var{setLoader:f0,load:YA}=Pt({fallbackImport:()=>import("./context-mentions-45MODWOY.js")});var _u=YA;var{setLoader:b0,load:XA}=Pt({fallbackImport:()=>import("./context-mentions-inline-I2RDEBAK.js"),resetOnSetLoader:!0});var zb=XA;function Ia(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=Q("span",{className:On("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=he(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(Q("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=Dh(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(L=>typeof L.matchCommand=="function")),s=x=>o.some(L=>L.trigger?L.position==="line-start"?x.split(`
|
|
18
|
+
`).some(O=>O.startsWith(L.trigger)):(L.position==="anywhere"?x:x.split(`
|
|
19
|
+
`)[0]).startsWith(L.trigger):!1),i=(x,L)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${x}`,{detail:L}))}catch{}},l=!t.chipRow,c=t.chipRow??Q("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),p=null,u=null,g=t.textarea,f=null,v=null,h=null,M=null,A=()=>{if(p)return Promise.resolve(p);if(u)return u;let x=_u().then(L=>(L.setMentionIconRenderer(he),p=L.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:f??void 0,anchor:t.anchor,contextRow:c,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:K,emit:i}),p)).catch(L=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",L),u===x&&(u=null),null));return u=x,x},T=()=>{zb().then(x=>{let L=x.mountInlineComposer({textarea:t.textarea,renderToken:O=>Ia(O,{render:e.renderMentionToken}),onMentionRemoved:O=>p?.untrackMention(O)});f=L.input,v=L.destroy;let w=g;w.replaceWith(L.element),g=L.element,M={next:L.element,prev:w},h?.(L.element,w),p?p.rebindComposer(L.input):u&&u.then(O=>O?.rebindComposer(L.input))}).catch(x=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",x)})};e.display==="inline"&&T();let F=[],P=new Map;for(let x of n){if(!x.showButton)continue;let L=qb({config:{...e,buttonIconName:x.buttonIconName,buttonTooltipText:x.buttonTooltipText},onOpen:()=>{A().then(w=>w?.openMenu(x.trigger))}});F.push(L),P.set(x.trigger,L.button)}let K=(x,L,w)=>{let O=P.get(L);O&&(O.setAttribute("aria-expanded",x?"true":"false"),x?O.setAttribute("aria-controls",w):O.removeAttribute("aria-controls"))};return{affordanceButtons:F.map(x=>x.wrapper),contextRow:c,handleInput:x=>{if(p){p.handleInput();return}if(!Oh(x))return;let L=g,w=L.selectionStart??0;_h(L.value,w,n)&&A().then(O=>O?.handleInput())},handleKeydown:x=>{if(p?.isMenuOpen())return p.handleKeydown(x);if(x.key==="Backspace"&&p?.hasMentions()&&!M){let L=g,w=L.selectionStart===0&&L.selectionEnd===0;if((L.value.length===0||w)&&p.removeLastChip())return x.preventDefault(),!0}return!1},isMenuOpen:()=>p?.isMenuOpen()??!1,hasMentions:()=>p?.hasMentions()??!1,getMentionRefs:()=>p?.getMentionRefs()??[],collectForSubmit:()=>p?.collectForSubmit()??null,takeInlineCommand:async x=>s(x)?(p??await A())?.dispatchInlineCommand(x)??null:null,clear:()=>p?.clear(),prefetch:()=>{_u().catch(()=>{})},onComposerSwap:x=>{h=x,M&&x(M.next,M.prev)},destroy:()=>{p?.destroy(),v?.();for(let x of F)x.wrapper.remove();l&&c.remove()}}}var jc="16px",Vc="transparent",JA=(()=>{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})(),ZA={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:JA,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"}},eM={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"}},tM={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:Yo,maxWidth:cb,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:jc,canvasBackground:Vc},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"}},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 gn(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."))?gn(t,o):o}function Kb(t){let e={};function n(o,s){for(let[i,l]of Object.entries(o)){let c=`${s}.${i}`;if(typeof l=="string"){let p=gn(t,l);p!==void 0&&(e[c]={path:c,value:p,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 nM(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 Gb(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]=Gb(i,s):n[o]=s}return n}function oM(t,e){return e?Gb(t,e):t}function ci(t,e={}){let n={palette:ZA,semantic:eM,components:tM},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:oM(n.components,t?.components)};if(e.validate!==!1){let s=nM(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 Ou=t=>t.trim()==="0"?"0px":t,Vb="--persona-",rM=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(p=>{let u=p.endsWith("%"),g=parseFloat(u?p.slice(0,-1):p);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},sM=.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[Vb+i],s!==void 0)break;s!==void 0&&(t[Vb+n]=s)}};function Qb(t){let e=Kb(t),n={};for(let[$,Pe]of Object.entries(e)){let Ne=$.replace(/\./g,"-");n[`--persona-${Ne}`]=Pe.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"]??jc,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Vc,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 p=n["--persona-components-history-railHeader-background"];p&&(n["--persona-history-rail-header-bg"]=p);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[$,Pe]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ne=n[`--persona-components-history-overlay-${$}`];Ne&&(n[`--persona-history-overlay-${Pe}`]=Ne)}for(let[$,Pe]of[["background","bg"],["borderRadius","radius"]]){let Ne=n[`--persona-components-history-menu-${$}`];Ne&&(n[`--persona-history-menu-${Pe}`]=Ne)}let f=t.components?.history?.motion;if(f){let $=xe=>{if(xe===void 0)return;let Oe=String(xe).trim();return/^\d+(\.\d+)?$/.test(Oe)?`${Oe}ms`:Oe},Pe=$(f.enterDurationMs);Pe!==void 0&&(n["--persona-history-enter-ms"]=Pe);let Ne=$(f.exitDurationMs);Ne!==void 0&&(n["--persona-history-exit-ms"]=Ne),f.enterEasing&&(n["--persona-history-enter-easing"]=f.enterEasing),f.exitEasing&&(n["--persona-history-exit-easing"]=f.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 $ of["scrim","shadow"]){let Pe=n[`--persona-components-history-confirm-${$}`];Pe&&(n[`--persona-history-confirm-${$}`]=Pe)}for(let[$,Pe]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ne=n[`--persona-components-tooltip-${$}`];Ne&&(n[`--persona-tooltip-${Pe}`]=Ne)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[$,Pe]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ne=n[`--persona-components-messageActions-${$}`];Ne&&(n[`--persona-message-action-${Pe}`]=Ne)}Xt(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],M=n["--persona-components-introCard-shadow"],A=(!h||h==="transparent"||h==="none")&&(!M||M==="none"),T=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=A&&T==="1.5rem"?"1.5rem 0":T,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"],["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 F=n["--persona-components-markdown-heading-h1-fontSize"];F&&(n["--persona-md-h1-size"]=F);let P=n["--persona-components-markdown-heading-h1-fontWeight"];P&&(n["--persona-md-h1-weight"]=P);let K=n["--persona-components-markdown-heading-h2-fontSize"];K&&(n["--persona-md-h2-size"]=K);let x=n["--persona-components-markdown-heading-h2-fontWeight"];x&&(n["--persona-md-h2-weight"]=x);let L=n["--persona-components-markdown-prose-fontFamily"];L&&L!=="inherit"&&(n["--persona-md-prose-font-family"]=L),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 G=w?.labelButton;G&&(G.background&&(n["--persona-label-btn-bg"]=G.background),G.border&&(n["--persona-label-btn-border"]=G.border),G.color&&(n["--persona-label-btn-color"]=G.color),G.padding&&(n["--persona-label-btn-padding"]=G.padding),G.borderRadius&&(n["--persona-label-btn-radius"]=G.borderRadius),G.hoverBackground&&(n["--persona-label-btn-hover-bg"]=G.hoverBackground),G.fontSize&&(n["--persona-label-btn-font-size"]=G.fontSize),G.gap&&(n["--persona-label-btn-gap"]=G.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 oe=w?.artifact;if(oe?.toolbar){let $=oe.toolbar;$.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=$.iconHoverColor),$.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=$.iconHoverBackground),$.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=$.iconPadding),$.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=$.iconBorderRadius),$.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=$.iconBorder),$.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ou($.toggleGroupGap)),$.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Ou($.toggleGroupPadding)),$.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=$.toggleGroupBorder),$.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=$.toggleGroupBorderRadius),$.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=gn(t,$.toggleGroupBackground)??$.toggleGroupBackground),$.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=$.copyBackground),$.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=$.copyBorder),$.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=$.copyColor),$.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ou($.copyBorderRadius)),$.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=$.copyPadding),$.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=$.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??$.copyMenuBackground),$.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=$.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??$.copyMenuBorder),$.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=$.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??$.copyMenuShadow),$.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=$.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??$.copyMenuBorderRadius),$.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=$.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??$.copyMenuItemHoverBackground),$.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=$.iconBackground),$.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=$.toolbarBorder)}if(oe?.tab){let $=oe.tab;$.background&&(n["--persona-artifact-tab-bg"]=$.background),$.activeBackground&&(n["--persona-artifact-tab-active-bg"]=$.activeBackground),$.activeBorder&&(n["--persona-artifact-tab-active-border"]=$.activeBorder),$.borderRadius&&(n["--persona-artifact-tab-radius"]=$.borderRadius),$.textColor&&(n["--persona-artifact-tab-color"]=$.textColor),$.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=$.hoverBackground),$.listBackground&&(n["--persona-artifact-tab-list-bg"]=$.listBackground),$.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=$.listBorderColor),$.listPadding&&(n["--persona-artifact-tab-list-padding"]=$.listPadding)}if(oe?.pane){let $=oe.pane;if($.toolbarBackground){let Pe=gn(t,$.toolbarBackground)??$.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Pe}}if(oe?.card){let $=oe.card;$.background&&(n["--persona-artifact-card-bg"]=$.background),$.border&&(n["--persona-artifact-card-border"]=$.border),$.borderRadius&&(n["--persona-artifact-card-radius"]=$.borderRadius),$.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=$.hoverBackground),$.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=$.hoverBorderColor)}if(oe?.inline){let $=oe.inline;$.background&&(n["--persona-artifact-inline-bg"]=gn(t,$.background)??$.background),$.border&&(n["--persona-artifact-inline-border"]=$.border),$.borderRadius&&(n["--persona-artifact-inline-radius"]=$.borderRadius),$.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=gn(t,$.chromeBackground)??$.chromeBackground),$.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=gn(t,$.chromeBorder)??$.chromeBorder),$.titleColor&&(n["--persona-artifact-inline-title-color"]=gn(t,$.titleColor)??$.titleColor),$.mutedColor&&(n["--persona-artifact-inline-muted-color"]=gn(t,$.mutedColor)??$.mutedColor),$.frameHeight&&(n["--persona-artifact-inline-frame-height"]=$.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"]=gn(t,S.background)??S.background));let _=n["--persona-surface"],R=n["--persona-container"],I=n["--persona-palette-colors-gray-100"]??"#f3f4f6",Y=n["--persona-palette-colors-gray-200"]??"#e5e7eb",V=n["--persona-palette-colors-gray-300"]??"#d1d5db",ae=!R||R===_,ce=rM(_??n["--persona-background"]),me=ae&&ce!==void 0&&ce<sM,Ce=me?"rgba(255, 255, 255, 0.08)":I,ue=me?"rgba(255, 255, 255, 0.12)":Y,_e=me?"rgba(255, 255, 255, 0.16)":V,ct=ae?Ce:R,we=ae?ue:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??ct,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??we,ae&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??_e),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??ct,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??ct,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??ct,n}var iM={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"}}},aM={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},Yb=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Du=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",lM=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Du()},Xb=t=>lM(t),cM=t=>ci(t),dM=t=>{let e=ai(aM,t??{})??{};return ci({...e,palette:{...e.palette,colors:{...iM.colors,...e.palette?.colors}}},{validate:!1})},di=t=>{let e=Xb(t),n=Yb(t?.theme),o=Yb(t?.darkTheme);return e==="dark"?dM(ai(n??{},o??{})):cM(n)},pM=t=>Qb(t),La=(t,e)=>{let n=di(e),o=pM(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",Xb(e))},Kc=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Du())});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(Du());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 bC,Check as vC,Copy as CC}from"lucide";var Tr=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Gc="24px",Nu=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",Ha=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},Jb=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var Zb=null;var Fu=()=>{if(Zb!==null)return Zb;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},uM="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Qc=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},Yc=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 Qc("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Qc("unsupported",t),null):(n==="space"&&(o.key=" "),o)},gM=t=>uM.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),ev=(t,e)=>{let n=Yc(t);if(!n)return"";let o=Fu(),s=gM(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=>ev(t,!1),Ra=t=>ev(t,!0),mM=(t,e)=>e.key?.toLowerCase()===t.key&&(Fu()?e.metaKey:e.ctrlKey)===t.mod&&!(Fu()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,fM=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},tv=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(mM(c.parsed,i)&&c.when?.()!==!1&&o(c,i)&&!(!c.allowInInput&&fM(l))){i.preventDefault();try{c.run(i)}catch(p){Qc(`${c.id} threw on`,c.combo),console.warn(p)}return}};return n?.addEventListener("keydown",s),{register(i){let l=Yc(i.combo);if(!l)return()=>{};let c=`${l.mod?"m":""}${l.shift?"s":""}${l.alt?"a":""}${l.key}`,p=e.get(c);return p?(Qc(`${p.id} already owns`,i.combo),()=>{}):(e.set(c,{...i,parsed:l}),i.element?.setAttribute("aria-keyshortcuts",Ra(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 hM}from"idiomorph";var Jc=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;hM.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 nv=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Uu={index:-1,draft:""};function ov(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 rv(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 sv(){return new Map}function iv(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function av(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function lv(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:V0,load:yM}=Pt({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var cv=yM;function $u(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 Wa=0,kr=null;function qu(t=document){if(Wa++,Wa===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;kr={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,Wa=Math.max(0,Wa-1),Wa===0&&kr)){let n=t.body,o=t.defaultView??window;n.style.overflow=kr.originalOverflow,n.style.position=kr.originalPosition,n.style.top=kr.originalTop,n.style.width=kr.originalWidth,o.scrollTo(0,kr.scrollY),kr=null}}}var Ba={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Rt=t=>(t?.launcher?.mountMode??"floating")==="docked",_a=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Jn=t=>{let e=t?.launcher?.dock;return{side:e?.side??Ba.side,width:e?.width??Ba.width,animate:e?.animate??Ba.animate,reveal:e?.reveal??Ba.reveal,maxHeight:e?.maxHeight??Ba.maxHeight}};import{ArrowRight as bM}from"lucide";var zu=t=>t==="followUp"?"follow-up":t,ju=(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"}},vM=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'}},dv=new WeakSet,CM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,wM=t=>{CM()||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"})})},Vu=t=>{var K,x,L;let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:p,chipsConfig:u,session:g,getTextarea:f,eventTarget:v,submitPrompt:h}=t,M=o==="followUp",A=e.behavior,T=()=>{if(g.isStreaming())return;let w={suggestion:{...e},surface:o,source:s,behavior:A},O=v.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:w,bubbles:!0,composed:!0,cancelable:!0}));if(M&&v.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!O)return;for(let ie of p)if(ie.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let G=f();if(A==="fill"){G.value=e.prompt,G.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),G.focus();return}if(h){h(e.prompt);return}G.value="",g.sendMessage(e.prompt)},F=()=>{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=A,i==="chip"&&(u?.fontFamily&&(w.style.fontFamily=vM(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 G=he(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);G&&(G.classList.add("persona-suggestion__icon"),e.iconColor&&(G.style.color=e.iconColor),w.appendChild(G))}let O=k("span","persona-suggestion__copy");if(O.appendChild(Q("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&O.appendChild(Q("span",{className:"persona-suggestion__description",text:e.description})),w.appendChild(O),i!=="chip"){let G=en(bM,16,"currentColor",1.8);G&&(G.classList.add("persona-suggestion__arrow"),w.appendChild(G))}return w.addEventListener("click",T),w},P=null;for(let w of p)if(w.renderSuggestion&&(P=w.renderSuggestion({suggestion:{...e},index:n,surface:o,source:s,variant:i,streaming:l,config:c,defaultRenderer:F,select:T}),P))break;return P??(P=F()),(K=P.dataset).suggestionId||(K.suggestionId=e.id),(x=P.dataset).behavior||(x.behavior=A),(L=P.dataset).emphasis||(L.emphasis=e.emphasis),P instanceof HTMLButtonElement||P.setAttribute("aria-disabled",l?"true":"false"),P},Oa=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 f=getComputedStyle(t).direction==="rtl",v=Math.min(g,Math.max(0,Math.abs(t.scrollLeft))),h=4,M=v<=h,A=v>=g-h,T=f?!A:!M,F=f?!M:!A;t.toggleAttribute("data-scroll-left",T),t.toggleAttribute("data-scroll-right",F)},c=()=>{if(s!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&l();return}s=requestAnimationFrame(l)};t.addEventListener("scroll",c,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(c):null;return p?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",c),p?.disconnect(),s!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(s),s=null},render:(g,f,v,h,M,A)=>{t.replaceChildren(),e.length=0,n.length=0;let T=A?.source??"config",F=A?.surface??(T==="config"?"starter":"followUp"),P=F==="followUp",K=A?.variant??"chip",x=A?.behavior??"send",L=A?.overflow??"wrap",w=A?.config??{},O=A?.plugins??[],G=typeof A?.maxItems=="number"?Math.max(0,Math.floor(A.maxItems)):void 0,ie=P?"followUps":"starters";!dv.has(w)&&w.debug===!0&&K!=="chip"&&w.suggestions?.[ie]?.overflow!==void 0&&(dv.add(w),console.info(`[persona] suggestions.${ie}.overflow applies to the "chip" variant only; the "${K}" variant manages its own stacking.`));let oe=V=>V.map(ju).filter(ae=>ae!==null).map(ae=>({...ae,behavior:ae.behavior??x})),S=oe(g??[]);O.forEach(V=>{V.transformSuggestions&&(S=oe(V.transformSuggestions({suggestions:S.map(ae=>({...ae})),surface:F,source:T,config:w})))});let _=G===void 0?S:S.slice(0,G);if(!_.length){t.hidden=!0,o=null,i();return}if(!P&&(h??f.getMessages()).some(ae=>ae.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=zu(F),t.dataset.variant=K,t.dataset.overflow=L;let R=document.createDocumentFragment(),I=f.isStreaming();_.forEach((V,ae)=>{let ce=Vu({item:V,index:ae,surface:F,source:T,variant:K,streaming:I,config:w,plugins:O,chipsConfig:M,session:f,getTextarea:()=>v,eventTarget:t,submitPrompt:A?.submitPrompt});R.appendChild(ce),n.push(ce),[...ce instanceof HTMLButtonElement?[ce]:[],...Array.from(ce.querySelectorAll("button"))].forEach(Ce=>{e.includes(Ce)||(Ce.disabled=I,e.push(Ce))})}),t.appendChild(R),l(),c();let Y=JSON.stringify({normalized:_,surface:F,variant:K,source:T});Y!==o&&(o=Y,wM(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:_.map(V=>({...V})),surface:F,source:T,variant:K},bubbles:!0,composed:!0})),P&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:_.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var Nn={"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 SM="persona-header-control",xM="persona-header-control--glyph",AM="persona-header-control--sparse",MM=20,EM={x:[1.4,1.05]},pv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",TM="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Zc=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=EM[e]??[1,1.5],c=!o;t.classList.toggle(xM,c),t.classList.toggle(AM,c&&i!==1);let p=parseFloat(o??"")||MM,u=he(e,`${Math.round(p*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)},hs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=pv,size:c,iconSize:p,color:u,backgroundColor:g,borderWidth:f,borderColor:v,borderRadius:h,paddingX:M,paddingY:A,hidden:T,extraClassName:F,attrs:P}=t,K=k("div",l),x=!!(f||v),L=Q("button",{className:On(SM,"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",F),attrs:{type:"button","aria-label":e,...P},style:{width:c,height:c,minWidth:c,minHeight:c,display:T?"none":void 0,color:u||mn.actionIconColor,backgroundColor:g,border:x?`${f||"0px"} solid ${v||"transparent"}`:void 0,borderRadius:h,paddingLeft:M,paddingRight:M,paddingTop:A,paddingBottom:A}});return s?Zc(L,s,{iconSize:p,iconText:i}):i&&(L.textContent=i),K.appendChild(L),Yt({anchor:L,trigger:K,text:()=>L.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:L,wrapper:K}},pi=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=pv,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",p=l.closeButtonShowTooltip??!0,{button:u,wrapper:g}=hs({ariaLabel:c,tooltip:p,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=TM,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",p=l.showTooltip??!0,{button:u,wrapper:g}=hs({ariaLabel:c,tooltip:p,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 mn={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)"},Ku={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)"},kM={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)"},ys=t=>{let{config:e,showClose:n=!0}=t,o=Q("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:mn.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,p=s.headerIconName,u=Q("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(p){let L=parseFloat(i)||24,w=he(p,L*.6,"currentColor",1);w?u.replaceChildren(w):u.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let L=k("img");L.src=e.launcher.iconUrl,L.alt="",L.className="persona-rounded-xl persona-object-cover",L.style.height=i,L.style.width=i,u.replaceChildren(L)}else u.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let g=k("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Q("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:mn.titleColor,...Ku}}),v=Q("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:mn.subtitleColor,...kM}});g.append(f,v),c?o.append(g):o.append(u,g);let h=s.clearChat??{},M=h.enabled??!0,A=h.placement??"inline",T=null,F=null;if(M){let w=ui(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=w.button,F=w.wrapper,A==="top-right"&&(F.style.right="48px"),A==="inline"&&o.appendChild(F)}let P=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":M&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:K,wrapper:x}=pi(e,{showClose:n,wrapperClassName:P});return l!=="top-right"&&o.appendChild(x),{header:o,iconHolder:u,headerTitle:f,headerSubtitle:v,closeButton:K,closeButtonWrapper:x,clearChatButton:T,clearChatButtonWrapper:F}},Da=(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 PM=t=>{let e=ys({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 IM(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=hs({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=Ra(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=Kh({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 LM=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=mn.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 p=s?.titleMenu,u,g;if(p){let x=Qh({label:l.title??"Chat Assistant",menuItems:p.menuItems,onSelect:L=>{let w=G=>{G===!1&&x.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:L}}))},O=p.onSelect(L);O instanceof Promise?O.then(w,()=>{}):w(O)},hover:p.hover,className:""});u=x.element,u.style.color=mn.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=mn.titleColor,Object.assign(g.style,Ku),g.textContent=l.title??"Chat Assistant",u.appendChild(g),s?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let L=s.onTitleClick;u.addEventListener("click",w=>{w.target.closest("button")||L()}),u.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),L())})}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 f="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:v,wrapper:h}=pi(e,{showClose:n,wrapperClassName:f});o&&v.addEventListener("click",o);let M=k("div","persona-flex persona-items-center persona-gap-1");p||IM(M,s?.trailingActions,s?.onAction??i);let A=l.clearChat??{},T=null,F=null;if(A.enabled??!0){let x=A.placement??"inline",L=ui(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":f});T=L.button,F=L.wrapper,x==="top-right"?F.style.right="48px":M.appendChild(F)}M.appendChild(h),c.appendChild(M);let P=k("div");P.style.display="none";let K=k("span");return K.style.display="none",{header:c,iconHolder:P,headerTitle:g,headerSubtitle:K,closeButton:v,closeButtonWrapper:h,clearChatButton:T,clearChatButtonWrapper:F}},uv={default:PM,minimal:LM},HM=t=>uv[t]??uv.default,ed=(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 p=k("span"),u=k("span"),g=k("button");g.style.display="none";let f=k("div");return f.style.display="none",{header:l,iconHolder:c,headerTitle:p,headerSubtitle:u,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=HM(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 Na=t=>{let{config:e}=t,n=Q("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=$c(),s=Q("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:i,attachAutoResize:l}=Dc(e);l();let c=Nc(e),p=li(e),u=Fc(e),g=Uc(e),f=Q("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(f),u&&(u.previewsContainer.style.gap="8px",f.append(u.previewsContainer),s.append(u.input)),s.append(i);let v=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),M=Q("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),p&&M.append(p.wrapper),M.append(c.wrapper),v.append(h,M),s.append(v),s.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&i.focus()}),n.append(o,s,g),{footer:n,suggestions:o,composerForm:s,header:f,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:p?.button??null,micButtonWrapper:p?.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:M,setSendButtonMode:c.setMode}};import{ChevronUp as RM,MessageSquare as WM}from"lucide";var gv=()=>{let t=Q("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(WM,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(RM,16,"currentColor",1.5);return i&&s.appendChild(i),t.append(e,o,s),{root:t,textNode:o}},td=t=>{let{config:e}=t,n=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=$c(),s=Uc(e);s.style.display="none";let{textarea:i,attachAutoResize:l}=Dc(e,{defaultMaxLines:5});l();let c=Nc(e),p=li(e),u=Fc(e);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let g=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&f.append(u.wrapper);let v=Q("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});p&&v.append(p.wrapper),v.append(c.wrapper),g.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&i.focus()}),u&&g.append(u.input),g.append(f,i,v);let h=Q("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 M=g;return{footer:n,suggestions:o,composerForm:g,header:h,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:s,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:M,leftActions:f,rightActions:v,setSendButtonMode:c.setMode}};var BM=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}},_M=(t,e)=>{if(!t)return null;let n=BM(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},OM=(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},DM=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Qu=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(":"))},Yu=320,bv=320,NM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),FM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),UM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),$M=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),qM=t=>{if(!t||t.length===0)return null;let e=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=k("span","persona-mention-chip-icon"),i=he(n.iconName??"at-sign",13,"currentColor",2);i&&s.appendChild(i),o.appendChild(s),o.appendChild(Q("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(Ia(o.ref,{readonly:!0,render:e}))}return n},mv="\uE000",fv="\uE001",jM=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=v=>`${mv}${s}:${v}${fv}`,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(`${mv}${s}:(\\d+)${fv}`),g=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),f=[];for(let v=g.nextNode();v;v=g.nextNode())f.push(v);for(let v of f){let h=v;for(let M=u.exec(h.data);M;M=u.exec(h.data)){let A=e[Number(M[1])],T=h.splitText(M.index);T.data=T.data.slice(M[0].length),A?.kind==="mention"&&T.parentNode?.insertBefore(Ia(A.ref,{readonly:!0,render:o}),T),h=T}}},VM=(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,p)=>{let u=k("img");u.alt=c.alt?.trim()||`Attached image ${p+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${Yu}px`,u.style.maxHeight=`${bv}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}),DM(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}},KM=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(!Qu(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=`${Yu}px`,e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},GM=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(!Qu(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=`${Yu}px`,s.style.maxHeight=`${bv}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}},QM=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(!Qu(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}},Fa=()=>{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},YM=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Fa};if(e){let s=e(o);if(s!==null)return s}return Fa()},XM=(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},hv=(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},Ua=(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},yv={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"}},JM=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=yv[n??"bubble"]??yv.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)`)},nd="custom:",ZM=t=>`${nd}${t}`,vv=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),eE=(t,e,n,o)=>{let s=e.showCopy??!0,i=e.showUpvote??!0,l=e.showDownvote??!0,c=e.showReadAloud??!1,p=(e.showRegenerate??!1)&&o?.canRegenerate===!0,u=(e.showEdit??!1)&&o?.canEdit===!0,g=(e.showQuote??!1)&&o?.canQuote!==!1,f=vv(e,t.role);if(!s&&!i&&!l&&!c&&!p&&!u&&!g&&f.length===0){let K=k("div");return K.style.display="none",K.id=`actions-${t.id}`,K.setAttribute("data-actions-for",t.id),K}let v=e.visibility??"hover",h=e.align??"right",M=e.layout??"pill-inside",A={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],T={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[M],F=k("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${A} ${T} ${v==="hover"?"persona-message-actions-hover":""}`);F.id=`actions-${t.id}`,F.setAttribute("data-actions-for",t.id);let P=(K,x,L)=>{let w=Gh({icon:K,label:x,size:14,className:"persona-message-action-btn",chromeless:!0});return w.setAttribute("data-action",L),w};s&&F.appendChild(P("copy","Copy message","copy")),c&&F.appendChild(P("volume-2","Read aloud","read-aloud")),i&&F.appendChild(P("thumbs-up","Upvote","upvote")),l&&F.appendChild(P("thumbs-down","Downvote","downvote")),p&&F.appendChild(P("refresh-cw","Regenerate response","regenerate")),u&&F.appendChild(P("pencil","Edit message","edit")),g&&F.appendChild(P("quote","Quote message","quote"));for(let K of f)F.appendChild(P(K.iconName??"ellipsis",K.label,ZM(K.id)));return F},Xu=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",p=l.avatar,u=l.timestamp,g=p?.show??!1,f=u?.show??!1,v=p?.position??"left",h=u?.position??"below",M=Ua(t.role,c),A=k("div",M.join(" "));A.id=`bubble-${t.id}`,A.setAttribute("data-message-id",t.id),A.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let T=i?.widgetConfig?.theme?.components?.message;JM(A,t.role,c,t.role==="user"?T?.user:T?.assistant),c==="flat"?(A.style.backgroundColor="transparent",A.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let F=NM(t),P=t.content?.trim()??"",x=F.length>0&&P===ii,L=hc(i?.widgetConfig?.features?.streamAnimation),w=i?.widgetConfig?.features?.streamAnimation?.plugins,O=t.role==="assistant"&&L.type!=="none"?ma(L.type,w):null,G=t.role==="assistant"&&O?.isAnimating?.(t)===!0,ie=t.role==="assistant"&&O!==null&&(!!t.streaming||G);ie&&O?.bubbleClass&&A.classList.add(O.bubbleClass);let oe=document.createElement("div");oe.classList.add("persona-message-content"),t.streaming&&oe.classList.add("persona-content-streaming"),ie&&O&&(O.containerClass&&oe.classList.add(O.containerClass),oe.style.setProperty("--persona-stream-step",`${L.speed}ms`),oe.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let S=ie?yc(t.content??"",L.buffer,O,t,!!t.streaming):t.content??"",_=()=>{let we=e({text:S,message:t,streaming:!!t.streaming,raw:t.rawContent});return ie&&O?.wrap==="char"?fa(we,"char",t.id,{skipTags:O.skipTags}):ie&&O?.wrap==="word"?fa(we,"word",t.id,{skipTags:O.skipTags}):we},R=null;if(x?(R=document.createElement("div"),R.innerHTML=_(),R.style.display="none",oe.appendChild(R)):t.contentSegments?.length?jM(oe,t.contentSegments,we=>e({text:we,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):oe.innerHTML=_(),ie&&O?.useCaret&&!x&&P){let we=bc(),$=oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pe=$[$.length-1];if(Pe?.parentNode)Pe.parentNode.insertBefore(we,Pe.nextSibling);else{let Ne=oe.lastElementChild;Ne?Ne.appendChild(we):oe.appendChild(we)}}if(f&&h==="inline"&&t.createdAt){let we=hv(t,u,"span");we.classList.add("persona-timestamp-inline");let $=oe.lastElementChild;$?$.appendChild(we):oe.appendChild(we)}if(F.length>0){let we=VM(F,!x&&!!P,()=>{x&&R&&(R.style.display="")});we?A.appendChild(we):x&&R&&(R.style.display="")}let I=FM(t);if(I.length>0){let we=KM(I);we&&A.appendChild(we)}let Y=UM(t);if(Y.length>0){let we=GM(Y);we&&A.appendChild(we)}let V=$M(t);if(V.length>0){let we=QM(V);we&&A.appendChild(we)}let ae=t.contentSegments?.length?null:qM(t.contextMentions);if(ae&&A.appendChild(ae),A.appendChild(oe),f&&h==="below"&&t.createdAt){let we=hv(t,u);we.classList.add("persona-mt-1"),A.appendChild(we)}let ce=t.role==="assistant"?_M(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let we=!!(S&&S.trim()),$=L.placeholder==="skeleton",Pe=$&&L.buffer==="line"&&we;if(we)Pe&&A.appendChild(ha());else if($)A.appendChild(ha());else{let Ne=YM("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);Ne&&A.appendChild(Ne)}}ce&&t.stopReason&&!t.streaming&&(P||(oe.style.display="none"),A.appendChild(OM(t.stopReason,ce)));let me=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,Ce=i?.actionEligibility,ue=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ce?.canEdit===!0||o?.showQuote===!0&&Ce?.canQuote===!0||vv(o,"user").length>0);if((me||ue)&&o){let we=eE(t,ue?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,Ce);A.appendChild(we)}if(!g||t.role==="system")return A;let _e=k("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ct=XM(p,t.role);return v==="right"||v==="left"&&t.role==="user"?_e.append(A,ct):_e.append(ct,A),_e};var tE=40,nE=(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=he(e.name,tE);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(Q("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},Cv=(t,e,n={})=>{let o=Q("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=Q("div",{className:"persona-welcome-head-text"},s,i),p=Q("div",{className:"persona-welcome-title-row"},o,c);return{host:Q("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},p,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)},rd=(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==="",nE(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")},oE="data-persona-welcome-plugin",wv="data-persona-welcome-overlay",od="persona-welcome-overlay-active",Ju=new WeakMap,Zu=(t,e,n)=>{n.setAttribute(oE,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(wv,""),t.classList.contains(od)||(Ju.set(t,t.scrollTop),t.classList.add(od),t.scrollTop=0)},eg=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(wv),t.classList.contains(od)&&(t.classList.remove(od),t.scrollTop=Ju.get(t)??t.scrollTop,Ju.delete(t))},Sv=()=>{let t=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},sd=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",s=Q("div",{className:Ua("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(Q("div",{className:"persona-flex"},s)),t.hidden=!1},xv=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Av=(t,e)=>{if(xv()||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 M=getComputedStyle(o);s=parseFloat(M.rowGap)||0;let A=t.previousElementSibling,T=t.nextElementSibling,P=o.getBoundingClientRect().top+(parseFloat(M.borderTopWidth)||0)+(parseFloat(M.paddingTop)||0)-o.scrollTop;i=Math.max(0,A?n.top-A.getBoundingClientRect().bottom-s:n.top-P),l=Math.max(0,T?T.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let p=getComputedStyle(t),u=parseFloat(p.paddingTop)||0,g=parseFloat(p.paddingBottom)||0,f=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(f))};return f.finished.then(h).catch(h),f},Mv=(t,e,n)=>{if(e<=1||xv()||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 rE="Hello \u{1F44B}",sE="I can answer questions and help you get things done here.",Ev=new WeakSet,fn=(t,e)=>!!t&&t[e]!==void 0,iE=(t,e)=>{!t||t.debug!==!0||!e.length||Ev.has(t)||(Ev.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Xo=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=Ha(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".'),iE(t,i),{title:fn(e,"title")?e.title:n?.welcomeTitle??rE,kicker:e?.kicker??"",subtitle:fn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??sE,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()||Gc}},Tv=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",mi=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var kv="16px",ng="10px",og="14px",Pv=t=>{let e=t?.launcher?.enabled??!0,n=Rt(t);if(_a(t)){let g=t?.launcher?.composerBar??{},f=k("div","persona-widget-wrapper persona-fixed persona-transition");f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=g.expandedSize??"anchored",f.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%",f.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:f,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"),f=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(f),{wrapper:g,panel:f}}if(!e){let g=k("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),f=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,f.style.width="100%",g.appendChild(f),{wrapper:g,panel:f}}let s=t?.launcher??{},i=s.position&&Nn[s.position]?Nn[s.position]:Nn["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??Yo;return c.style.width=u,c.style.maxWidth=u,l.appendChild(c),{wrapper:l,panel:c}},rg=t=>{let e=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":zu(t)}});return e.hidden=!0,e},Iv=(t,e)=>{let n=rg("starter"),o=Cv(t,n,{flatShadow:Rt(t)}),s=Xo(t);rd(o,s),gi(e,o.host,mi(s,t?.initialMessages));let i=Sv();return sd(i,s.message,t),{welcome:o,greetingHost:i}},aE=(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:kv,iconSize:ng});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:kv,iconSize:og});l=O.button,c=O.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let p=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:g,greetingHost:f}=Iv(t,u),{host:v,title:h,subtitle:M}=g,A=g.starterSuggestions,T=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),F=rg("followUp"),P=Tr(t,!0);P&&(T.style.maxWidth=P,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),u.append(v,f,T,F);let K=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),x=td({config:t}),{root:L,textNode:w}=gv();return n.append(p,s,u,K),c&&n.appendChild(c),{container:n,body:u,messagesWrapper:T,starterSuggestions:A,transcriptSuggestions:F,composerOverlay:K,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:f,introKicker:g.kicker,introTitle:h,introSubtitle:M,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:k("span"),headerTitle:k("span"),headerSubtitle:k("span"),header:p,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:L,peekTextNode:w}},Lv=(t,e=!0)=>{if(_a(t))return aE(t,e);let n=Q("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,s=t?.layout?.showHeader!==!1,i=o?ed(t,o,{showClose:e}):ys({config:t,showClose:e}),l=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:p}=Iv(t,l),{host:u,title:g,subtitle:f}=c,v=c.starterSuggestions,h=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),M=rg("followUp"),A=Tr(t,!1);A&&(h.style.maxWidth=A,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),l.append(u,p,h,M);let T=Na({config:t}),F=t?.layout?.showFooter!==!1;s?Da(n,i,t):(i.header.style.display="none",Da(n,i,t)),n.append(l);let P=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return F||(T.footer.style.display="none"),n.append(T.footer),n.append(P),{container:n,body:l,messagesWrapper:h,starterSuggestions:v,transcriptSuggestions:M,composerOverlay:P,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:u,welcomeIconHolder:c.iconHolder,greetingHost:p,introKicker:c.kicker,introTitle:g,introSubtitle:f,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:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};var sg=(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 bu=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=Rt(i),p=n.querySelector("[data-role='launcher-title']");if(p){let K=l.title??"Chat Assistant";p.textContent=K,p.setAttribute("title",K)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let K=l.subtitle??"Here to help you get answers fast";u.textContent=K,u.setAttribute("title",K)}let g=n.querySelector(".persona-flex-col");g&&(l.textHidden||c?g.style.display="none":g.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(l.agentIconHidden)f.style.display="none";else{let K=l.agentIconSize??"40px";if(f.style.height=K,f.style.width=K,l.agentIconBackgroundColor?(f.style.backgroundColor=l.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",l.agentIconName){let x=parseFloat(K)||24,L=he(l.agentIconName,x*.6,"var(--persona-text-inverse, #ffffff)",1.5);L?(f.appendChild(L),f.style.display=""):(f.textContent=l.agentIconText??"\u{1F4AC}",f.style.display="")}else l.iconUrl?f.style.display="none":(f.textContent=l.agentIconText??"\u{1F4AC}",f.style.display="")}let v=n.querySelector("[data-role='launcher-image']");if(v){let K=l.agentIconSize??"40px";v.style.height=K,v.style.width=K,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 K=l.callToActionIconSize??"32px";h.style.height=K,h.style.width=K,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 L=parseFloat(K)||24,w=Math.max(L-x,8),_=he(l.callToActionIconName,w,"currentColor",1.5);_?h.appendChild(_):h.textContent=l.callToActionIconText??"\u2197"}else h.textContent=l.callToActionIconText??"\u2197"}let M=l.position&&Nn[l.position]?Nn[l.position]:Nn["bottom-right"],A="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="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?T:`${A} ${M}`,c||(n.style.zIndex=String(l.zIndex??an));let F="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??F,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}},rE="teaser-dismissed",Hv=new Set,Lv=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${rE}`},sE=(t,e)=>{if(Hv.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},iE=(t,e)=>{if(Hv.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},aE=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,lE=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||Rt(t??{})?null:e},Rv=(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,p=null,u=!1,g=!1,f=!1,v=!1,h=()=>(s?.frequency??"once")==="once"&&o.persistState!==!1,M=()=>{p!==null&&(clearTimeout(p),p=null)},A=()=>{!i||!u||(u=!1,i.hidden=!0)},T=Y=>{M(),f=!0,A(),iE(Lv(o),Y&&h())},F=Y=>{!s||f||T(Y==="user"&&u)},P=()=>{p=null,!(!i||f||v)&&(g=!0,u=!0,i.hidden=!1,!(aE()||typeof i.animate!="function")&&i.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},K=()=>{!s||!i||f||g||v||sE(Lv(o),h())||(M(),p=setTimeout(P,Math.max(0,s.delayMs??0)))},x=()=>{T(h()),e()},L=Y=>{Y.stopPropagation(),T(h())},_=rg(t,()=>{F("user"),e()}),G=()=>{M(),c?.removeEventListener("click",x),l?.removeEventListener("click",L),i?.remove(),i=null,c=null,l=null,u=!1},ie=()=>{c=Q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),c.addEventListener("click",x),l=Q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),l.addEventListener("click",L),i=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},c,l),n.insertBefore(i,_.element)},oe=()=>{let Y=o.launcher?.position??"bottom-right",V=Nn[Y]??Nn["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",_.element.style.position="";return}n.className=On("persona-launcher-surface",V),n.setAttribute("data-teaser",Y),n.style.zIndex=String(o.launcher?.zIndex??an),_.element.style.position="static"},S=Y=>{let V=lE(Y);if(s=V,!V){G();return}i||ie(),c.textContent=V.text,l.hidden=V.dismissible===!1,l.setAttribute("aria-label",V.dismissLabel??"Dismiss message"),K()},O=Y=>{o=Y,_.update(Y),S(Y),oe()},R=(Y,V="user")=>{v=Y,Y&&F(V)},I=()=>{G(),_.destroy(),n.remove()};return n.appendChild(_.element),t&&(S(t),oe()),{element:n,launcher:_,get teaser(){return i?{element:i,show:P,dismiss:T}:null},setPanelOpen:R,update:O,destroy:I}};var Wv=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:s}=kv(t),i=Iv(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},p={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:p,composer:u,replaceHeader:v=>(p.element.replaceWith(v.header),p.element=v.header,p.iconHolder=v.iconHolder,p.headerTitle=v.headerTitle,p.headerSubtitle=v.headerSubtitle,p.closeButton=v.closeButton,p.closeButtonWrapper=v.closeButtonWrapper,p.clearChatButton=v.clearChatButton,p.clearChatButtonWrapper=v.clearChatButtonWrapper,v),replaceComposer:v=>{u.footer.replaceWith(v),u.footer=v}}},sg=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>rg(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let s=Rv(t,n);return{instance:s,element:s.element}};var cE=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},dE=(t,e,n)=>`${cE(t)}plugin:${e}:${n}`,Bv=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=>dE(t(),s,l);return{get:l=>{let c=i(l),p=o();if(p)try{return p.getItem(c)}catch{n=!0}return e.get(c)??null},set:(l,c)=>{let p=i(l),u=o();if(u)try{u.setItem(p,c);return}catch{n=!0}e.set(p,c)},remove:l=>{let c=i(l);e.delete(c);let p=o();if(p)try{p.removeItem(c)}catch{n=!0}}}}};import{ChevronDown as pE,ChevronUp as uE}from"lucide";var gE=["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"],mE="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",fE="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",hE=(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,...gE].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},id=t=>{let e=k("button",t.expandable?mE:fE);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},ig=(t,e,n)=>{t.innerHTML="";let o=en(e?uE:pE,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");ig(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?.();hE(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&&ig(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 p=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");p&&ig(p,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};var fi=new Set,yE=(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
|
-
`):""},
|
|
27
|
+
`,n.addEventListener("click",e);let o=i=>{let l=i.launcher??{},c=Rt(i),p=n.querySelector("[data-role='launcher-title']");if(p){let K=l.title??"Chat Assistant";p.textContent=K,p.setAttribute("title",K)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let K=l.subtitle??"Here to help you get answers fast";u.textContent=K,u.setAttribute("title",K)}let g=n.querySelector(".persona-flex-col");g&&(l.textHidden||c?g.style.display="none":g.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(l.agentIconHidden)f.style.display="none";else{let K=l.agentIconSize??"40px";if(f.style.height=K,f.style.width=K,l.agentIconBackgroundColor?(f.style.backgroundColor=l.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",l.agentIconName){let x=parseFloat(K)||24,L=he(l.agentIconName,x*.6,"var(--persona-text-inverse, #ffffff)",1.5);L?(f.appendChild(L),f.style.display=""):(f.textContent=l.agentIconText??"\u{1F4AC}",f.style.display="")}else l.iconUrl?f.style.display="none":(f.textContent=l.agentIconText??"\u{1F4AC}",f.style.display="")}let v=n.querySelector("[data-role='launcher-image']");if(v){let K=l.agentIconSize??"40px";v.style.height=K,v.style.width=K,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 K=l.callToActionIconSize??"32px";h.style.height=K,h.style.width=K,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 L=parseFloat(K)||24,w=Math.max(L-x,8),O=he(l.callToActionIconName,w,"currentColor",1.5);O?h.appendChild(O):h.textContent=l.callToActionIconText??"\u2197"}else h.textContent=l.callToActionIconText??"\u2197"}let M=l.position&&Nn[l.position]?Nn[l.position]:Nn["bottom-right"],A="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="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?T:`${A} ${M}`,c||(n.style.zIndex=String(l.zIndex??an));let F="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??F,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}},lE="teaser-dismissed",Rv=new Set,Hv=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${lE}`},cE=(t,e)=>{if(Rv.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},dE=(t,e)=>{if(Rv.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},pE=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,uE=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||Rt(t??{})?null:e},Wv=(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,p=null,u=!1,g=!1,f=!1,v=!1,h=()=>(s?.frequency??"once")==="once"&&o.persistState!==!1,M=()=>{p!==null&&(clearTimeout(p),p=null)},A=()=>{!i||!u||(u=!1,i.hidden=!0)},T=Y=>{M(),f=!0,A(),dE(Hv(o),Y&&h())},F=Y=>{!s||f||T(Y==="user"&&u)},P=()=>{p=null,!(!i||f||v)&&(g=!0,u=!0,i.hidden=!1,!(pE()||typeof i.animate!="function")&&i.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},K=()=>{!s||!i||f||g||v||cE(Hv(o),h())||(M(),p=setTimeout(P,Math.max(0,s.delayMs??0)))},x=()=>{T(h()),e()},L=Y=>{Y.stopPropagation(),T(h())},O=sg(t,()=>{F("user"),e()}),G=()=>{M(),c?.removeEventListener("click",x),l?.removeEventListener("click",L),i?.remove(),i=null,c=null,l=null,u=!1},ie=()=>{c=Q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),c.addEventListener("click",x),l=Q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),l.addEventListener("click",L),i=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},c,l),n.insertBefore(i,O.element)},oe=()=>{let Y=o.launcher?.position??"bottom-right",V=Nn[Y]??Nn["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",O.element.style.position="";return}n.className=On("persona-launcher-surface",V),n.setAttribute("data-teaser",Y),n.style.zIndex=String(o.launcher?.zIndex??an),O.element.style.position="static"},S=Y=>{let V=uE(Y);if(s=V,!V){G();return}i||ie(),c.textContent=V.text,l.hidden=V.dismissible===!1,l.setAttribute("aria-label",V.dismissLabel??"Dismiss message"),K()},_=Y=>{o=Y,O.update(Y),S(Y),oe()},R=(Y,V="user")=>{v=Y,Y&&F(V)},I=()=>{G(),O.destroy(),n.remove()};return n.appendChild(O.element),t&&(S(t),oe()),{element:n,launcher:O,get teaser(){return i?{element:i,show:P,dismiss:T}:null},setPanelOpen:R,update:_,destroy:I}};var Bv=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:s}=Pv(t),i=Lv(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},p={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:p,composer:u,replaceHeader:v=>(p.element.replaceWith(v.header),p.element=v.header,p.iconHolder=v.iconHolder,p.headerTitle=v.headerTitle,p.headerSubtitle=v.headerSubtitle,p.closeButton=v.closeButton,p.closeButtonWrapper=v.closeButtonWrapper,p.clearChatButton=v.clearChatButton,p.clearChatButtonWrapper=v.clearChatButtonWrapper,v),replaceComposer:v=>{u.footer.replaceWith(v),u.footer=v}}},ig=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>sg(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let s=Wv(t,n);return{instance:s,element:s.element}};var gE=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},mE=(t,e,n)=>`${gE(t)}plugin:${e}:${n}`,_v=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=>mE(t(),s,l);return{get:l=>{let c=i(l),p=o();if(p)try{return p.getItem(c)}catch{n=!0}return e.get(c)??null},set:(l,c)=>{let p=i(l),u=o();if(u)try{u.setItem(p,c);return}catch{n=!0}e.set(p,c)},remove:l=>{let c=i(l);e.delete(c);let p=o();if(p)try{p.removeItem(c)}catch{n=!0}}}}};import{ChevronDown as fE,ChevronUp as hE}from"lucide";var yE=["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"],bE="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",vE="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",CE=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),id=(t,e)=>{let n=k("div",["persona-message-bubble",t,...yE].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},ad=t=>{let e=k("button",t.expandable?bE:vE);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},ag=(t,e,n)=>{t.innerHTML="";let o=en(e?hE:fE,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},ld=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=k("div","persona-flex persona-items-center");ag(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},cd=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?.();CE(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},dd=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&ag(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"},pd=(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 p=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");p&&ag(p,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};var fi=new Set,wE=(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
|
+
`):""},Ov=(t,e)=>{pd(t,e,{stateSet:fi,previewKind:"reasoning",iconColor:"currentColor"})},lg=(t,e)=>{let n=t.reasoning,o=id("persona-reasoning-bubble",t.id);if(!n)return o;let s=e?.features?.reasoningDisplay??{},i=s.expandable!==!1,l=i&&fi.has(t.id),c=n.status!=="complete",p=wE(t,s.previewMaxLines??3),u=ad({expandable:i,expanded:l,bubbleType:"reasoning"}),g=k("div","persona-flex persona-flex-col persona-text-left"),f=k("span","persona-text-xs persona-text-persona-primary"),v="Thinking...",h=e?.reasoning??{},M=String(n.startedAt??Date.now()),A=()=>{let I=k("span","");return I.setAttribute("data-tool-elapsed",M),I.textContent=pc(n),I},T=h.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:v,previewText:p,isActive:c,config:e??{},elapsed:pc(n),createElapsedElement:A});typeof T=="string"&&T.trim()?(f.textContent=T,g.appendChild(f)):T instanceof HTMLElement?g.appendChild(T):(f.textContent=v,g.appendChild(f));let F=k("span","persona-text-xs persona-text-persona-primary");F.textContent=Ah(n),g.appendChild(F);let P=s.loadingAnimation??"none",K=h.activeTextTemplate,x=h.completeTextTemplate,L=c?K:x,w=T instanceof HTMLElement,O=(I,Y)=>{f.textContent="";let V=uc(I,""),ae=0;for(let ce of V){let me=ce.styles.length>0?(()=>{let Ce=k("span",ce.styles.map(ue=>`persona-tool-text-${ue}`).join(" "));return f.appendChild(Ce),Ce})():f;if(ce.isDuration&&c)me.appendChild(A());else{let Ce=ce.isDuration?pc(n):ce.text;Y?ae=Js(me,Ce,ae):me.appendChild(document.createTextNode(Ce))}}};if(!w&&L)if(F.style.display="none",f.style.display="",c&&P!=="none"){let I=h.loadingAnimationDuration??2e3;f.setAttribute("data-preserve-animation","true"),P==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${I}ms`),O(L,!1)):(f.classList.add(`persona-tool-loading-${P}`),f.style.setProperty("--persona-tool-anim-duration",`${I}ms`),P==="shimmer-color"&&(h.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor)),O(L,!0))}else O(L,!1);else if(!w&&c&&P!=="none"){f.style.display="";let I=h.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),P==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${I}ms`);else{f.classList.add(`persona-tool-loading-${P}`),f.style.setProperty("--persona-tool-anim-duration",`${I}ms`),P==="shimmer-color"&&(h.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor));let Y=f.textContent||v;f.textContent="",Js(f,Y,0)}n.status==="complete"&&(f.style.display="none")}else w||(n.status==="complete"?f.style.display="none":f.style.display="");if(s.iconName&&!w){let I=k("span","persona-reasoning-header-icon"),Y=he(s.iconName,16,"currentColor",2);Y&&(I.appendChild(Y),u.appendChild(I))}let G="currentColor",ie=ld(u,g,{expandable:i,expanded:l,iconColor:G,metaGap:!1}),oe=cd({bubble:o,previewKind:"reasoning",expanded:l,isActive:c,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:c,config:e??{}})});if(!i)return o.append(u,oe),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 _=n.chunks.join(""),R=k("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return R.textContent=_||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),S.appendChild(R),dd({expanded:l,header:u,toggleIcon:ie,content:S,collapsedPreview:oe,iconColor:G}),o.append(u,oe,S),o};var hi=new Set,Dv=t=>t.toggleTextColor||t.headerTextColor||"var(--persona-primary, #171717)",SE=(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=cc(n.args).trim();return s?s.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,e).join(`
|
|
30
|
-
`):""},lg=(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)"},vE=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??"tool-call",i=bE(t,o?.previewMaxLines??3),l=n?Ah(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",p=e?.toolCall??{},u=l;return s==="tool-name"?u=n.name?.trim()||l:s==="tool-preview"&&i&&(u=i),c&&p.activeTextTemplate?u=Yp(n,p.activeTextTemplate,u):!c&&p.completeTextTemplate&&(u=Yp(n,p.completeTextTemplate,u)),{summary:u,previewText:i,isActive:c}},Dv=(t,e,n)=>{dd(t,e,{stateSet:hi,previewKind:"tool",iconColor:Ov(n?.toolCall??{})})},cg=(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:p,previewText:u,isActive:g}=vE(t,e),f=id({expandable:l,expanded:c,bubbleType:"tool"});o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let 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 M=String(n.startedAt??Date.now()),A=()=>{let S=k("span","");return S.setAttribute("data-tool-elapsed",M),S.textContent=dc(n),S},T=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:u,collapsedMode:i.collapsedMode??"tool-call",isActive:g,config:e??{},elapsed:dc(n),createElapsedElement:A});typeof T=="string"&&T.trim()?(h.textContent=T,v.appendChild(h)):T instanceof HTMLElement?v.appendChild(T):(h.textContent=p,v.appendChild(h));let F=i.loadingAnimation??"none",P=o.activeTextTemplate,K=o.completeTextTemplate,x=g?P:K,L=T instanceof HTMLElement,w=(S,O)=>{h.textContent="";let R=n.name?.trim()||"tool",I=uc(S,R),Y=0;for(let V of I){let ae=V.styles.length>0?(()=>{let ce=k("span",V.styles.map(me=>`persona-tool-text-${me}`).join(" "));return h.appendChild(ce),ce})():h;if(V.isDuration&&g)ae.appendChild(A());else{let ce=V.isDuration?dc(n):V.text;O?Y=Js(ae,ce,Y):ae.appendChild(document.createTextNode(ce))}}};if(!L)if(g&&F!=="none"){let S=o.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),F==="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-${F}`),h.style.setProperty("--persona-tool-anim-duration",`${S}ms`),F==="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 O=h.textContent||p;h.textContent="",Js(h,O,0)}}else x&&w(x,!1);let _=Ov(o),G=ad(f,v,{expandable:l,expanded:c,iconColor:_,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(f,ie),s;let oe=k("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(oe.style.display=c?"":"none",o.contentBackgroundColor&&(oe.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(oe.style.color=o.contentTextColor),o.contentPaddingX&&(oe.style.paddingLeft=o.contentPaddingX,oe.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(oe.style.paddingTop=o.contentPaddingY,oe.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,oe.appendChild(S)}if(n.args!==void 0){let S=k("div","persona-space-y-1"),O=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(O.style.color=o.labelTextColor),O.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",lg(R,o),R.textContent=cc(n.args),S.append(O,R),oe.appendChild(S)}if(n.chunks&&n.chunks.length){let S=k("div","persona-space-y-1"),O=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(O.style.color=o.labelTextColor),O.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",lg(R,o),R.textContent=n.chunks.join(""),S.append(O,R),oe.appendChild(S)}if(n.status==="complete"&&n.result!==void 0){let S=k("div","persona-space-y-1"),O=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(O.style.color=o.labelTextColor),O.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",lg(R,o),R.textContent=cc(n.result),S.append(O,R),oe.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`,oe.appendChild(S)}return cd({expanded:c,header:f,toggleIcon:G,content:oe,collapsedPreview:ie,iconColor:_}),s.append(f,ie,oe),s};var{setLoader:LL,load:CE,provide:HL,getSync:wE}=Pt({fallbackImport:()=>import("./approval-ui-RNNBR5R3.js")});var Nv=CE;var Fv=wE;var{setLoader:BL,load:SE}=Pt({fallbackImport:()=>import("./event-stream-view-73NWKWVQ.js")});var dg=SE;var pg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:UL,load:xE,provide:$L,getSync:AE}=Pt({fallbackImport:()=>import("./artifacts-ui-J6AKUGTS.js")}),yi=null,pd=new Set,Uv=t=>{if(yi)return yi;yi=t,t.initArtifactsUi({componentRegistry:Go});for(let o of pg)Go.has(o)||Go.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Ys();e?t.__provideMarkdownParsers(e):ic(()=>{let o=Ys();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Lh());let n=[...pd];pd.clear();for(let o of n)try{o()}catch{}return t};var ud=()=>xE().then(Uv);var Jo=()=>{if(yi)return yi;let t=AE();return t?Uv(t):null},ug=t=>yi?()=>{}:(pd.add(t),()=>{pd.delete(t)});function hn(t){return t?.features?.artifacts?.enabled===!0}function $v(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"),!hn(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 ME(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 qv=["panel","seamless","detached"];function gg(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&qv.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function mg(t){return!t||!hn(t)?!1:gg(t)==="detached"}function $a(t,e){if(!hn(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"),ME(t),$v(t,e);return}let n=e.features?.artifacts?.layout,o=gg(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,p]of l){let u=c?.trim();u?t.style.setProperty(p,u):t.style.removeProperty(p)}$v(t,e)}function qa(t,e){for(let c of qv)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"),!hn(e))return;let n=e.features?.artifacts?.layout,o=gg(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 zv(t,e){return!e||!hn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var EE=new Set(["__proto__","prototype","constructor"]),TE=new Set(["collapsed","card","panel","inline"]),jv=new Set(["markdown","component"]),kE=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,bs=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),md=t=>!EE.has(t),fg=t=>typeof t=="string"&&TE.has(t),vs=t=>Object.keys(t).length>0;function Po(t,e,n,o){t.push({path:e,code:n,message:o})}var PE="Ignored because this key is not part of the persisted preference schema.",gd="Ignored an unsupported value.",IE="Expected collapsed, panel, or inline.",LE='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Vv={kind:"mode",message:gd},bi={kind:"string",message:"Expected a CSS length string."},Zo={kind:"boolean"},HE={paneWidth:bi,paneMaxWidth:bi,paneMinWidth:bi,expandedPanelWidth:bi,resizableMinWidth:bi,resizableMaxWidth:bi,expandLauncherPanelWhenOpen:Zo,resizable:Zo},RE={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Zo,showReasoning:Zo,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:Zo,grouped:Zo}},reasoningDisplay:{kind:"object",children:{expandable:Zo,activePreview:Zo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Vv,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Vv,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:jv,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:jv}}},filePreview:{kind:"object",children:{enabled:Zo}},layout:{kind:"object",children:HE}}}}};function Kv(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Po(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Po(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Po(o,n,"invalid_value",e.message);case"mode":return fg(t)?Yn(t):Po(o,n,"invalid_value",e.message);case"modeMap":{if(!bs(t))return Po(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 p=s?l:Zs(l);md(l)&&(s?s.has(l):kE.test(p))?fg(c)?i[p]=Yn(c):Po(o,`${n}.${l}`,"invalid_value",IE):Po(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":LE)}return vs(i)?i:void 0}case"object":{if(e.bareMode&&fg(t))return Yn(t);if(!bs(t))return Po(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))(!md(c)||!s.includes(c))&&Po(o,i(c),"unknown_key",PE);let l={};for(let c of s){let p=e.children[c],u=Kv(t[c],p,i(c),o);if(p.deprecated&&t[c]!==void 0&&Po(o,i(c),"deprecated_key",p.deprecated),u===void 0)continue;let g=p.alias??c,f=l[g];l[g]=bs(f)&&bs(u)?{...f,...u}:u}return vs(l)?l:void 0}}}function WE(t){let e=[];return{preferences:(t===null?void 0:Kv(t,RE,"",e))??{},issues:e}}function vi(t){if(Array.isArray(t))return t.map(vi);if(!bs(t))return t;let e={};for(let[n,o]of Object.entries(t))md(n)&&o!==void 0&&(e[n]=vi(o));return e}function Gv(t,e){let n=vi(t);for(let[o,s]of Object.entries(e)){if(!md(o)||s===void 0)continue;let i=n[o];n[o]=bs(i)&&bs(s)?Gv(i,s):vi(s)}return n}function BE(t){let e={},n;for(let s of t){let i=WE(s).preferences;n=Qv(n,i.artifacts?.display),e=Gv(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function _E(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}:{},...vs(s)?{byMediaType:s}:{}};return vs(i)?i:void 0}function Qv(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=_E(n.files,e.files),l={...o?{default:o}:{},...vs(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return vs(l)?l:void 0}function OE(t={},e){let n=BE(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=Qv(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 hg(t){let e=t.preferences;return!e||!vs(e)?t:{...t,features:OE(t.features??{},[e])}}function DE(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 NE(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 FE(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function UE(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function yg(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 Yv(t,e,n,o,s,i,l=200){let c=DE(s,200),p=UE(e,n,o,l);p=Math.max(c,p);let u=NE(i);return u!==null&&(p=Math.min(p,u)),FE(t,c,p)}var{setLoader:QL,load:$E,provide:YL,getSync:qE}=Pt({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var Xv=$E;var Jv=qE;var bg=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()}},vg=new bg;var Zv=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),zE=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),eC=(t,e,n)=>{if(!Zv(t)||!Zv(e)||zE.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]=eC(t[s],e[s],i)}return o};function tC(t,e){let n=eC(t,e,"");return Rc(n)}var nC=()=>{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 jE=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},VE=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},wg=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=jE(t),n=VE(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}},Cg=t=>typeof t=="string"?t:t==null?"":String(t),za={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Cg(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Cg(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:Cg(n.text)}}},oC=t=>Array.isArray(t)?t.map(e=>String(e)):[],Sg=t=>{let e=new Set(oC(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(oC(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 p={action:c,message:i.message};t.emit("action:detected",p);for(let u of t.handlers)if(u)try{let g=()=>{t.emit("action:resubmit",p)},f=u(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:g});if(!f)continue;if(f.handled){let v=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:v,resubmit:f.resubmit}}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:n}};var KE=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}},GE=t=>t.map(e=>({...e,streaming:!1})),QE=t=>t.map(e=>({...e,status:"complete"})),rC=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?KE(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?GE(n.messages):void 0,artifacts:n.artifacts?QE(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 YE=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")},sC=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 YE(t)},XE=async(t,e)=>{let n=await sC(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await sC(`${t}\0${e}`)}`}};var iC=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,p=0,u=null,g=null,f=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}},M=(w,_)=>{if(c||w===u)return;let G=u;u=w,p+=1;let ie={previousToken:G,token:w,source:_,revision:p};for(let oe of f)oe(ie)},A=w=>{c||w.key!==null&&w.key!==o||M(w.key===null?null:w.newValue??null,"external")},T=(async()=>{let w=await XE(t,e);o=w.storageKey,s=w.leaseKey,i=w.lockName,u=h(),!n&&typeof window<"u"&&window.addEventListener("storage",A)})(),F=w=>new Promise(_=>setTimeout(_,w)),P=()=>{let w=v();if(!w)return null;try{let _=w.getItem(s);if(!_)return null;let G=JSON.parse(_);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},K=w=>{let _=v();if(_)try{P()?.ownerNonce===w&&_.removeItem(s)}catch{}},x=w=>new Promise(_=>{let G=setTimeout(ie,w);function ie(){clearTimeout(G),window.removeEventListener("storage",oe),_()}function oe(S){(S.key===null||S.key===s)&&ie()}window.addEventListener("storage",oe)}),L=async w=>{let _=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;Date.now()<G;){let ie=v();if(!ie)break;let oe=Date.now(),S=P();if(S&&S.expiresAt>oe&&S.ownerNonce!==_){await x(Math.min(S.expiresAt-oe,500));continue}try{ie.setItem(s,JSON.stringify({ownerNonce:_,expiresAt:oe+1e4}))}catch{l=!0;break}if(await F(20+Math.random()*40),P()?.ownerNonce!==_){await x(500);continue}g=_;try{return await w()}finally{g=null,K(_)}}return w()};return{ready:T,async get(){return await T,M(h(),"external"),u},async set(w){await T;let _=v();if(_)try{_.setItem(o,w)}catch{l=!0}M(w,"local")},async clear(){await T;let w=v();if(w)try{w.removeItem(o)}catch{l=!0}M(null,"local")},revision(){return p},subscribe(w){return f.add(w),()=>{f.delete(w)}},async withFirstInitLock(w){await T;let _=globalThis.navigator?.locks;return _?.request?_.request(i,()=>w()):v()?L(w):w()},matches(w,_,G){return w===t&&_===e&&G===n},destroy(){c=!0,f.clear(),typeof window<"u"&&window.removeEventListener("storage",A),g&&K(g)}}};var{setLoader:iH,load:JE}=Pt({fallbackImport:()=>import("./history-view-BD6OXLNA.js")});var xg=JE;var Ag=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},er=t=>Object.freeze({...t}),aC=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),lC=t=>t?er(t):null;function cC(t){let{plugins:e,config:n}=t,o=!1,s=!1,i=!1,l=!1,c=null,p=[],u=()=>{for(let x of p.splice(0))try{x()}catch(L){Ag("renderHistoryView cleanup",L)}},g=(x,L)=>{for(let w of e){let _=w[x];if(_)try{let G=_(L);if(G)return G}catch(G){Ag(x,G)}}return null},f=()=>({presentation:t.getPresentation(),config:n}),v={header:x=>l?g("renderHistoryHeader",Object.freeze({...f(),returnSurface:t.getReturnSurface(),identityStatus:er(x.identityStatus),pendingAction:lC(x.pendingAction),copy:er(x.copy),actions:Object.freeze({close:A.close,startNewConversation:A.startNewConversation}),defaultRenderer:x.defaultRenderer})):null,conversation:x=>l?g("renderHistoryConversation",Object.freeze({...f(),conversation:aC(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({...f(),state:er(x.state),identityStatus:er(x.identityStatus),copy:er(x.copy),...x.retry?{retry:x.retry}:{},...x.startNewConversation?{startNewConversation:x.startNewConversation}:{},defaultRenderer:x.defaultRenderer})):null},h=e.flatMap(x=>(x.railSections??[]).map(L=>({...L,placement:L.placement??"above-conversations",items:[],render:w=>L.render(Object.freeze({collapsed:w,presentation:t.getPresentation(),actions:A}))}))),M=t.createView({slots:v,renderDom:!1,onModelChange:()=>K(),railSections:h}),A=Object.freeze({...M.operations,close:t.close}),T=()=>(l=!0,M.setDomRenderEnabled(!0),M.element),F=x=>Object.freeze({conversations:Object.freeze(x.conversations.map(aC)),activeConversationId:x.activeConversationId,state:er(x.state),pendingAction:lC(x.pendingAction),identityStatus:er(x.identityStatus),nextCursor:x.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:er(M.copy),actions:A,defaultRenderer:T,requestRender:()=>K(),onCleanup:L=>{p.push(L)}}),P=()=>{l=!1;let x=null;for(let w of e)if(w.renderHistoryView){try{x=w.renderHistoryView(F(M.getModel()))}catch(_){Ag("renderHistoryView",_),x=null}if(x)break}let L=!x||x.contains(M.element);return l=L,M.setDomRenderEnabled(L),x??M.element};function K(){if(!(!i||o||s)){s=!0;try{u();let x=P();if(x===c)return;let L=c;c=x,t.onElementChanged(x,L)}finally{s=!1}}}return i=!0,K(),{view:M,get element(){return c??M.element},requestRender:K,dispose:()=>{o=!0,u()}}}var ZE=null;function dC(){return ZE}var eT=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"]]),tT=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."]]),Mg=t=>tT.get(t)??"Conversation history is unavailable right now.";function nT(t){if(t instanceof us)return t;if(t instanceof $e){let e=eT.get(t.code)??"unavailable";return new us(e,Mg(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new us("unavailable",Mg("unavailable"))}function pC(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 us("unsupported_scope",Mg("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(u){throw nT(u)}},l=c=>{let p=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){p||(p=!0,c.commit(),await t.onActivationCommitted(c.session))},discard(){p||(p=!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 p=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:p.data,nextCursor:p.nextCursor}})},async getPage(c,p){return i(p.context.scope,async()=>{let u=await e().getConversation(c,{...p.cursor?{messageCursor:p.cursor}:{},scope:p.context.scope}),g=Ly(u.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:u.summary,messages:xa([],g),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(c,p){return i(p.context.scope,async()=>l(await e().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await e().prepareNewConversationSession()))},async delete(c,p){await i(p.context.scope,()=>e().deleteConversation(c,{scope:p.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 oT="button:not([disabled])";function fd(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=Q("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),l=Q("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),c=Q("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"}},Q("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Q("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:s},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Q("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},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 p=Q("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},c);return new Promise(u=>{let g=!1,f=h=>{g||(g=!0,p.removeEventListener("keydown",v,!0),p.remove(),e?.focus(),u(h))};function v(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),f(!1);return}if(h.key!=="Tab")return;let M=Array.from(c.querySelectorAll(oT));if(M.length===0)return;let A=M[0],T=M[M.length-1],F=document.activeElement;h.shiftKey&&(F===A||!c.contains(F))?(h.preventDefault(),T.focus()):!h.shiftKey&&F===T&&(h.preventDefault(),A.focus())}p.addEventListener("keydown",v,!0),p.addEventListener("pointerdown",h=>{h.target===p&&f(!1)}),i.addEventListener("click",()=>f(!1)),l.addEventListener("click",()=>f(!0)),t.host.appendChild(p),i.focus()})}import{parse as yH,STR as bH,OBJ as vH}from"partial-json";function uC(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=Go.get(t.component);if(!i){if(pg.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 gC(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 Eg(t){let e=gC(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 mC(t){let e=gC(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 rT=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function fC(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:p=!0,ratingLabels:u=rT}=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 f=null,v=document.createElement("div");v.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=o,h.appendChild(M);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,h.appendChild(A),v.appendChild(h);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let F=[];for(let w=1;w<=5;w++){let _=document.createElement("button");_.type="button",_.className="persona-feedback-rating-btn persona-feedback-star-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${u[w-1]}`),_.title=u[w-1],_.dataset.rating=String(w),_.innerHTML=`
|
|
30
|
+
`):""},cg=(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)"},xE=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??"tool-call",i=SE(t,o?.previewMaxLines??3),l=n?Mh(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",p=e?.toolCall??{},u=l;return s==="tool-name"?u=n.name?.trim()||l:s==="tool-preview"&&i&&(u=i),c&&p.activeTextTemplate?u=Xp(n,p.activeTextTemplate,u):!c&&p.completeTextTemplate&&(u=Xp(n,p.completeTextTemplate,u)),{summary:u,previewText:i,isActive:c}},Nv=(t,e,n)=>{pd(t,e,{stateSet:hi,previewKind:"tool",iconColor:Dv(n?.toolCall??{})})},dg=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},s=id("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:p,previewText:u,isActive:g}=xE(t,e),f=ad({expandable:l,expanded:c,bubbleType:"tool"});o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let 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 M=String(n.startedAt??Date.now()),A=()=>{let S=k("span","");return S.setAttribute("data-tool-elapsed",M),S.textContent=dc(n),S},T=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:u,collapsedMode:i.collapsedMode??"tool-call",isActive:g,config:e??{},elapsed:dc(n),createElapsedElement:A});typeof T=="string"&&T.trim()?(h.textContent=T,v.appendChild(h)):T instanceof HTMLElement?v.appendChild(T):(h.textContent=p,v.appendChild(h));let F=i.loadingAnimation??"none",P=o.activeTextTemplate,K=o.completeTextTemplate,x=g?P:K,L=T instanceof HTMLElement,w=(S,_)=>{h.textContent="";let R=n.name?.trim()||"tool",I=uc(S,R),Y=0;for(let V of I){let ae=V.styles.length>0?(()=>{let ce=k("span",V.styles.map(me=>`persona-tool-text-${me}`).join(" "));return h.appendChild(ce),ce})():h;if(V.isDuration&&g)ae.appendChild(A());else{let ce=V.isDuration?dc(n):V.text;_?Y=Js(ae,ce,Y):ae.appendChild(document.createTextNode(ce))}}};if(!L)if(g&&F!=="none"){let S=o.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),F==="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-${F}`),h.style.setProperty("--persona-tool-anim-duration",`${S}ms`),F==="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 _=h.textContent||p;h.textContent="",Js(h,_,0)}}else x&&w(x,!1);let O=Dv(o),G=ld(f,v,{expandable:l,expanded:c,iconColor:O,metaGap:!0}),ie=cd({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(f,ie),s;let oe=k("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(oe.style.display=c?"":"none",o.contentBackgroundColor&&(oe.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(oe.style.color=o.contentTextColor),o.contentPaddingX&&(oe.style.paddingLeft=o.contentPaddingX,oe.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(oe.style.paddingTop=o.contentPaddingY,oe.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,oe.appendChild(S)}if(n.args!==void 0){let S=k("div","persona-space-y-1"),_=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.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",cg(R,o),R.textContent=cc(n.args),S.append(_,R),oe.appendChild(S)}if(n.chunks&&n.chunks.length){let S=k("div","persona-space-y-1"),_=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.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",cg(R,o),R.textContent=n.chunks.join(""),S.append(_,R),oe.appendChild(S)}if(n.status==="complete"&&n.result!==void 0){let S=k("div","persona-space-y-1"),_=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.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",cg(R,o),R.textContent=cc(n.result),S.append(_,R),oe.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`,oe.appendChild(S)}return dd({expanded:c,header:f,toggleIcon:G,content:oe,collapsedPreview:ie,iconColor:O}),s.append(f,ie,oe),s};var{setLoader:_L,load:AE,provide:OL,getSync:ME}=Pt({fallbackImport:()=>import("./approval-ui-RNNBR5R3.js")});var Fv=AE;var Uv=ME;var{setLoader:FL,load:EE}=Pt({fallbackImport:()=>import("./event-stream-view-73NWKWVQ.js")});var pg=EE;var ug=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:VL,load:TE,provide:KL,getSync:kE}=Pt({fallbackImport:()=>import("./artifacts-ui-J6AKUGTS.js")}),yi=null,ud=new Set,$v=t=>{if(yi)return yi;yi=t,t.initArtifactsUi({componentRegistry:Go});for(let o of ug)Go.has(o)||Go.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Ys();e?t.__provideMarkdownParsers(e):ic(()=>{let o=Ys();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Hh());let n=[...ud];ud.clear();for(let o of n)try{o()}catch{}return t};var gd=()=>TE().then($v);var Jo=()=>{if(yi)return yi;let t=kE();return t?$v(t):null},gg=t=>yi?()=>{}:(ud.add(t),()=>{ud.delete(t)});function hn(t){return t?.features?.artifacts?.enabled===!0}function qv(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"),!hn(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 PE(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 zv=["panel","seamless","detached"];function mg(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&zv.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function fg(t){return!t||!hn(t)?!1:mg(t)==="detached"}function $a(t,e){if(!hn(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"),PE(t),qv(t,e);return}let n=e.features?.artifacts?.layout,o=mg(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,p]of l){let u=c?.trim();u?t.style.setProperty(p,u):t.style.removeProperty(p)}qv(t,e)}function qa(t,e){for(let c of zv)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"),!hn(e))return;let n=e.features?.artifacts?.layout,o=mg(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||!hn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var IE=new Set(["__proto__","prototype","constructor"]),LE=new Set(["collapsed","card","panel","inline"]),Vv=new Set(["markdown","component"]),HE=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,bs=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),fd=t=>!IE.has(t),hg=t=>typeof t=="string"&&LE.has(t),vs=t=>Object.keys(t).length>0;function Po(t,e,n,o){t.push({path:e,code:n,message:o})}var RE="Ignored because this key is not part of the persisted preference schema.",md="Ignored an unsupported value.",WE="Expected collapsed, panel, or inline.",BE='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Kv={kind:"mode",message:md},bi={kind:"string",message:"Expected a CSS length string."},Zo={kind:"boolean"},_E={paneWidth:bi,paneMaxWidth:bi,paneMinWidth:bi,expandedPanelWidth:bi,resizableMinWidth:bi,resizableMaxWidth:bi,expandLauncherPanelWhenOpen:Zo,resizable:Zo},OE={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Zo,showReasoning:Zo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:md},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:md},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:md},expandable:Zo,grouped:Zo}},reasoningDisplay:{kind:"object",children:{expandable:Zo,activePreview:Zo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Kv,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Kv,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Vv,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Vv}}},filePreview:{kind:"object",children:{enabled:Zo}},layout:{kind:"object",children:_E}}}}};function Gv(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Po(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Po(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Po(o,n,"invalid_value",e.message);case"mode":return hg(t)?Yn(t):Po(o,n,"invalid_value",e.message);case"modeMap":{if(!bs(t))return Po(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 p=s?l:Zs(l);fd(l)&&(s?s.has(l):HE.test(p))?hg(c)?i[p]=Yn(c):Po(o,`${n}.${l}`,"invalid_value",WE):Po(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":BE)}return vs(i)?i:void 0}case"object":{if(e.bareMode&&hg(t))return Yn(t);if(!bs(t))return Po(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))&&Po(o,i(c),"unknown_key",RE);let l={};for(let c of s){let p=e.children[c],u=Gv(t[c],p,i(c),o);if(p.deprecated&&t[c]!==void 0&&Po(o,i(c),"deprecated_key",p.deprecated),u===void 0)continue;let g=p.alias??c,f=l[g];l[g]=bs(f)&&bs(u)?{...f,...u}:u}return vs(l)?l:void 0}}}function DE(t){let e=[];return{preferences:(t===null?void 0:Gv(t,OE,"",e))??{},issues:e}}function vi(t){if(Array.isArray(t))return t.map(vi);if(!bs(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 Qv(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]=bs(i)&&bs(s)?Qv(i,s):vi(s)}return n}function NE(t){let e={},n;for(let s of t){let i=DE(s).preferences;n=Yv(n,i.artifacts?.display),e=Qv(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function FE(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}:{},...vs(s)?{byMediaType:s}:{}};return vs(i)?i:void 0}function Yv(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=FE(n.files,e.files),l={...o?{default:o}:{},...vs(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return vs(l)?l:void 0}function UE(t={},e){let n=NE(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=Yv(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 yg(t){let e=t.preferences;return!e||!vs(e)?t:{...t,features:UE(t.features??{},[e])}}function $E(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 qE(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 jE(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function bg(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 Xv(t,e,n,o,s,i,l=200){let c=$E(s,200),p=jE(e,n,o,l);p=Math.max(c,p);let u=qE(i);return u!==null&&(p=Math.min(p,u)),zE(t,c,p)}var{setLoader:eH,load:VE,provide:tH,getSync:KE}=Pt({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var Jv=VE;var Zv=KE;var vg=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()}},Cg=new vg;var eC=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),GE=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),tC=(t,e,n)=>{if(!eC(t)||!eC(e)||GE.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]=tC(t[s],e[s],i)}return o};function nC(t,e){let n=tC(t,e,"");return Rc(n)}var oC=()=>{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 QE=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},YE=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},Sg=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=QE(t),n=YE(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}},wg=t=>typeof t=="string"?t:t==null?"":String(t),za={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:wg(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=wg(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:wg(n.text)}}},rC=t=>Array.isArray(t)?t.map(e=>String(e)):[],xg=t=>{let e=new Set(rC(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(rC(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 p={action:c,message:i.message};t.emit("action:detected",p);for(let u of t.handlers)if(u)try{let g=()=>{t.emit("action:resubmit",p)},f=u(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:g});if(!f)continue;if(f.handled){let v=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:v,resubmit:f.resubmit}}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:n}};var XE=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}},JE=t=>t.map(e=>({...e,streaming:!1})),ZE=t=>t.map(e=>({...e,status:"complete"})),sC=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?XE(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?JE(n.messages):void 0,artifacts:n.artifacts?ZE(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 eT=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")},iC=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 eT(t)},tT=async(t,e)=>{let n=await iC(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await iC(`${t}\0${e}`)}`}};var aC=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,p=0,u=null,g=null,f=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}},M=(w,O)=>{if(c||w===u)return;let G=u;u=w,p+=1;let ie={previousToken:G,token:w,source:O,revision:p};for(let oe of f)oe(ie)},A=w=>{c||w.key!==null&&w.key!==o||M(w.key===null?null:w.newValue??null,"external")},T=(async()=>{let w=await tT(t,e);o=w.storageKey,s=w.leaseKey,i=w.lockName,u=h(),!n&&typeof window<"u"&&window.addEventListener("storage",A)})(),F=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 G=JSON.parse(O);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},K=w=>{let O=v();if(O)try{P()?.ownerNonce===w&&O.removeItem(s)}catch{}},x=w=>new Promise(O=>{let G=setTimeout(ie,w);function ie(){clearTimeout(G),window.removeEventListener("storage",oe),O()}function oe(S){(S.key===null||S.key===s)&&ie()}window.addEventListener("storage",oe)}),L=async w=>{let O=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;Date.now()<G;){let ie=v();if(!ie)break;let oe=Date.now(),S=P();if(S&&S.expiresAt>oe&&S.ownerNonce!==O){await x(Math.min(S.expiresAt-oe,500));continue}try{ie.setItem(s,JSON.stringify({ownerNonce:O,expiresAt:oe+1e4}))}catch{l=!0;break}if(await F(20+Math.random()*40),P()?.ownerNonce!==O){await x(500);continue}g=O;try{return await w()}finally{g=null,K(O)}}return w()};return{ready:T,async get(){return await T,M(h(),"external"),u},async set(w){await T;let O=v();if(O)try{O.setItem(o,w)}catch{l=!0}M(w,"local")},async clear(){await T;let w=v();if(w)try{w.removeItem(o)}catch{l=!0}M(null,"local")},revision(){return p},subscribe(w){return f.add(w),()=>{f.delete(w)}},async withFirstInitLock(w){await T;let O=globalThis.navigator?.locks;return O?.request?O.request(i,()=>w()):v()?L(w):w()},matches(w,O,G){return w===t&&O===e&&G===n},destroy(){c=!0,f.clear(),typeof window<"u"&&window.removeEventListener("storage",A),g&&K(g)}}};var{setLoader:pH,load:nT}=Pt({fallbackImport:()=>import("./history-view-BD6OXLNA.js")});var Ag=nT;var Mg=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},er=t=>Object.freeze({...t}),lC=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),cC=t=>t?er(t):null;function dC(t){let{plugins:e,config:n}=t,o=!1,s=!1,i=!1,l=!1,c=null,p=[],u=()=>{for(let x of p.splice(0))try{x()}catch(L){Mg("renderHistoryView cleanup",L)}},g=(x,L)=>{for(let w of e){let O=w[x];if(O)try{let G=O(L);if(G)return G}catch(G){Mg(x,G)}}return null},f=()=>({presentation:t.getPresentation(),config:n}),v={header:x=>l?g("renderHistoryHeader",Object.freeze({...f(),returnSurface:t.getReturnSurface(),identityStatus:er(x.identityStatus),pendingAction:cC(x.pendingAction),copy:er(x.copy),actions:Object.freeze({close:A.close,startNewConversation:A.startNewConversation}),defaultRenderer:x.defaultRenderer})):null,conversation:x=>l?g("renderHistoryConversation",Object.freeze({...f(),conversation:lC(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({...f(),state:er(x.state),identityStatus:er(x.identityStatus),copy:er(x.copy),...x.retry?{retry:x.retry}:{},...x.startNewConversation?{startNewConversation:x.startNewConversation}:{},defaultRenderer:x.defaultRenderer})):null},h=e.flatMap(x=>(x.railSections??[]).map(L=>({...L,placement:L.placement??"above-conversations",items:[],render:w=>L.render(Object.freeze({collapsed:w,presentation:t.getPresentation(),actions:A}))}))),M=t.createView({slots:v,renderDom:!1,onModelChange:()=>K(),railSections:h}),A=Object.freeze({...M.operations,close:t.close}),T=()=>(l=!0,M.setDomRenderEnabled(!0),M.element),F=x=>Object.freeze({conversations:Object.freeze(x.conversations.map(lC)),activeConversationId:x.activeConversationId,state:er(x.state),pendingAction:cC(x.pendingAction),identityStatus:er(x.identityStatus),nextCursor:x.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:er(M.copy),actions:A,defaultRenderer:T,requestRender:()=>K(),onCleanup:L=>{p.push(L)}}),P=()=>{l=!1;let x=null;for(let w of e)if(w.renderHistoryView){try{x=w.renderHistoryView(F(M.getModel()))}catch(O){Mg("renderHistoryView",O),x=null}if(x)break}let L=!x||x.contains(M.element);return l=L,M.setDomRenderEnabled(L),x??M.element};function K(){if(!(!i||o||s)){s=!0;try{u();let x=P();if(x===c)return;let L=c;c=x,t.onElementChanged(x,L)}finally{s=!1}}}return i=!0,K(),{view:M,get element(){return c??M.element},requestRender:K,dispose:()=>{o=!0,u()}}}var oT=null;function pC(){return oT}var rT=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"]]),sT=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."]]),Eg=t=>sT.get(t)??"Conversation history is unavailable right now.";function iT(t){if(t instanceof us)return t;if(t instanceof $e){let e=rT.get(t.code)??"unavailable";return new us(e,Eg(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new us("unavailable",Eg("unavailable"))}function uC(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 us("unsupported_scope",Eg("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(u){throw iT(u)}},l=c=>{let p=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){p||(p=!0,c.commit(),await t.onActivationCommitted(c.session))},discard(){p||(p=!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 p=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:p.data,nextCursor:p.nextCursor}})},async getPage(c,p){return i(p.context.scope,async()=>{let u=await e().getConversation(c,{...p.cursor?{messageCursor:p.cursor}:{},scope:p.context.scope}),g=Hy(u.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:u.summary,messages:xa([],g),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(c,p){return i(p.context.scope,async()=>l(await e().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await e().prepareNewConversationSession()))},async delete(c,p){await i(p.context.scope,()=>e().deleteConversation(c,{scope:p.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 aT="button:not([disabled])";function hd(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=Q("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),l=Q("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),c=Q("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"}},Q("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Q("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:s},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Q("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},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 p=Q("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},c);return new Promise(u=>{let g=!1,f=h=>{g||(g=!0,p.removeEventListener("keydown",v,!0),p.remove(),e?.focus(),u(h))};function v(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),f(!1);return}if(h.key!=="Tab")return;let M=Array.from(c.querySelectorAll(aT));if(M.length===0)return;let A=M[0],T=M[M.length-1],F=document.activeElement;h.shiftKey&&(F===A||!c.contains(F))?(h.preventDefault(),T.focus()):!h.shiftKey&&F===T&&(h.preventDefault(),A.focus())}p.addEventListener("keydown",v,!0),p.addEventListener("pointerdown",h=>{h.target===p&&f(!1)}),i.addEventListener("click",()=>f(!1)),l.addEventListener("click",()=>f(!0)),t.host.appendChild(p),i.focus()})}import{parse as SH,STR as xH,OBJ as AH}from"partial-json";function gC(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=Go.get(t.component);if(!i){if(ug.includes(t.component)){gd().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 mC(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 Tg(t){let e=mC(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 fC(t){let e=mC(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 lT=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hC(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:p=!0,ratingLabels:u=lT}=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 f=null,v=document.createElement("div");v.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=o,h.appendChild(M);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,h.appendChild(A),v.appendChild(h);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let F=[];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
|
-
`,_.addEventListener("click",()=>{f=w,F.forEach((G,ie)=>{let oe=ie<w;G.classList.toggle("selected",oe),G.setAttribute("aria-checked",ie===w-1?"true":"false")})}),F.push(_),T.appendChild(_)}v.appendChild(T);let P=null;if(p){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 K=document.createElement("div");K.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 L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=l,L.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let w=P?.value.trim()||void 0;await e(f,w),g.remove()}catch(w){L.disabled=!1,L.textContent=l,console.error("[CSAT Feedback] Failed to submit:",w)}}),K.appendChild(x),K.appendChild(L),v.appendChild(K),g.appendChild(v),g}function hC(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:p=!0,lowLabel:u="Not likely",highLabel:g="Very likely"}=t,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let v=null,h=document.createElement("div");h.className="persona-feedback-content";let M=document.createElement("div");M.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=o,M.appendChild(A);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,M.appendChild(T),h.appendChild(M);let F=document.createElement("div");F.className="persona-feedback-rating persona-feedback-rating-nps",F.setAttribute("role","radiogroup"),F.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let K=document.createElement("span");K.className="persona-feedback-label-low",K.textContent=u;let x=document.createElement("span");x.className="persona-feedback-label-high",x.textContent=g,P.appendChild(K),P.appendChild(x);let L=document.createElement("div");L.className="persona-feedback-numbers";let w=[];for(let S=0;S<=10;S++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${S} out of 10`),O.textContent=String(S),O.dataset.rating=String(S),S<=6?O.classList.add("persona-feedback-detractor"):S<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{v=S,w.forEach((R,I)=>{R.classList.toggle("selected",I===S),R.setAttribute("aria-checked",I===S?"true":"false")})}),w.push(O),L.appendChild(O)}F.appendChild(P),F.appendChild(L),h.appendChild(F);let _=null;if(p){let S=document.createElement("div");S.className="persona-feedback-comment-container",_=document.createElement("textarea"),_.className="persona-feedback-comment",_.placeholder=i,_.rows=3,_.setAttribute("aria-label","Additional comments"),S.appendChild(_),h.appendChild(S)}let G=document.createElement("div");G.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?.(),f.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="persona-feedback-btn persona-feedback-btn-submit",oe.textContent=l,oe.addEventListener("click",async()=>{if(v===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let S=_?.value.trim()||void 0;await e(v,S),f.remove()}catch(S){oe.disabled=!1,oe.textContent=l,console.error("[NPS Feedback] Failed to submit:",S)}}),G.appendChild(ie),G.appendChild(oe),h.appendChild(G),f.appendChild(h),f}var Ci="persona-chat-history",aT=30*1e3,lT=641,wi="data-persona-composer-reason",cT={"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 dT(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=cT[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 pT(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 uT(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Tg=t=>!t||typeof t!="object"?{}:{...t},CC=t=>t.map(e=>({...e,streaming:!1})),wC=(t,e,n)=>{let o=t?.markdown?bh(t.markdown):null,s=vh(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 p=c.text??"",u=c.message.rawContent??null;if(e){let v=e.process({text:p,raw:u??p,message:c.message,streaming:c.streaming});v!==null&&(p=v.text,v.persist||(c.message.__skipPersist=!0),v.resubmit&&!c.streaming&&n&&n())}let g=Ys()!==null,f;if(t?.postprocessMessage){let v=t.postprocessMessage({...c,text:p,raw:u??c.text??""});f=s?s(v):v}else if(o){let v=c.streaming?Jh(p):p,h=o(v);f=s&&g?s(h):h}else f=ac(p);return f};return c=>{try{return l(c)}catch(p){return i||(i=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",p)),ac(c.text??"")}}};function SC(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=he(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 gT=(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},mT=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:gT(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),xC=(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=Rc(e),s=()=>{ob({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};s();let i=o.features;o=hg(o);let l=vg.getForInstance(o.plugins),c=ev(t),p=[],u=!1,g=Bv(()=>o),f=null,v=null,h=null,M=!1,A=null,T=r=>{f=r,r.initApprovalUi({webMcpToolTitle:lc});let a=r.createBuiltInApprovalPlugin();v=a.plugin,h=a.teardown},F=()=>{if(f)return f;let r=Fv();return r?(T(r),r):(Nv().then(a=>{M||f||(T(a),A?.())}).catch(()=>{}),null)},P=!1,K=!1,x=null,L=(r,a,d,m)=>{if(!r.querySelector("[data-tv-form]"))return;let y=Jv();if(y){y.enhanceWithForms(r,a,d,m);return}Xv().then(()=>{P||K||!x||(K=!0,x())}).catch(()=>{})};o.components&&Go.registerAll(o.components);let w=nC(),G=o.persistState===!1?null:o.storageAdapter??rC(),ie={},oe=null,S,O=new Promise(r=>{S=r}),R,I=!1,Y=r=>{if(o.onStateLoaded)try{let a=o.onStateLoaded(r);if(a&&typeof a=="object"&&"state"in a){let{state:d,open:m}=a;return m&&(I=!0),d}return a}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}return r};if(G?.load)try{let r=G.load();if(r&&typeof r.then=="function")oe=r.then(a=>Y(a??{messages:[],metadata:{}}));else{let d=Y(r??{messages:[],metadata:{}});d.metadata&&(ie=Tg(d.metadata)),d.messages?.length&&(o={...o,initialMessages:d.messages}),d.artifacts?.length&&(o={...o,initialArtifacts:d.artifacts,initialSelectedArtifactId:d.selectedArtifactId??null}),R=d.draft}}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",r)}else if(o.onStateLoaded)try{let r=Y({messages:[],metadata:{}});r.messages?.length&&(o={...o,initialMessages:r.messages})}catch(r){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",r)}oe||S();let V=()=>ie,ae=r=>{ie=r({...ie})??{},Oi()},ce=o.actionParsers&&o.actionParsers.length?o.actionParsers:[wg],me=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[za.message,za.messageAndClick],we=Sg({parsers:ce,handlers:me,getSessionMetadata:V,updateSessionMetadata:ae,emit:w.emit,documentRef:typeof document<"u"?document:null});we.syncFromMetadata();let ue=o.launcher?.enabled??!0,_e=o.launcher?.autoExpand??!1,ct=o.autoFocusInput??!1,Ce=_e,$=ue,Pe=o.layout?.header?.layout,Ne=!1,xe=()=>_a(o),Oe=()=>ue||xe(),ye=xe()?!1:ue?_e:!0,gt=!1,Zn=null,Cs=()=>{gt=!0,Zn&&clearTimeout(Zn),Zn=setTimeout(()=>{gt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),gt=!1)},1e4)},Jt=wC(o,we,Cs),Fn=o.features?.showReasoning??!0,Io=o.features?.showToolCalls??!0,It=o.features?.showEventStreamToggle??!1,Pr=o.features?.scrollToBottom??{},yn=o.features?.scrollBehavior??{},po=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Ir=`${po()}event-stream`,ln=null,Ai=o.features?.eventStream?.maxEvents??2e3,xt=null,dt=null,eo=null,Va=!1,H=null,ee=!1,b=null,D=0,N=(r,a)=>{xt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:r,timestamp:Date.now(),payload:JSON.stringify(a)})},U=(r,a)=>{dt?.processEvent(r,a),xt?N(r,a):eo&&(eo.length>=Ai&&eo.shift(),eo.push({type:r,payload:a}))},Z=()=>{xt||!It||(eo??(eo=[]),dg().then(r=>{if(Va||xt||!It)return;ln=new r.EventStreamStore(Ir),xt=new r.EventStreamBuffer(Ai,ln),dt=dt??new r.ThroughputTracker,ln.open().then(()=>xt?.restore()).catch(d=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",d)});let a=eo??[];eo=null;for(let d of a)dt?.processEvent(d.type,d.payload),N(d.type,d.payload)}).catch(()=>{}))};It&&Z();let te=!1,le=null,Ae=()=>{},mt=()=>{},qe=()=>{},Lt=()=>{},Ct=()=>{},Lr=()=>ee||te&&le==="panel",En={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)}},Nt=o.statusIndicator??{},cn=r=>r==="idle"?Nt.idleText??Dt.idle:r==="connecting"?Nt.connectingText??Dt.connecting:r==="connected"?Nt.connectedText??Dt.connected:r==="error"?Nt.errorText??Dt.error:r==="paused"?Nt.pausedText??Dt.paused:r==="resuming"?Nt.resumingText??Dt.resuming:Dt[r];function tn(r,a,d,m){if(!r.hasAttribute(wi))if(m==="idle"&&d.idleLink){r.textContent="";let y=document.createElement("a");y.href=d.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 Tn=Wv({config:o,showClose:Oe()}),{wrapper:Ke,panel:Me,pillRoot:Vt}=Tn.shell,De=Tn.panelElements,{container:pe,body:ne,messagesWrapper:Ie,starterSuggestions:bd,transcriptSuggestions:Mi,suggestions:tr,textarea:de,sendButton:Ee,composerForm:to,statusText:ot,welcomeHost:bn,welcomeIconHolder:BC,greetingHost:kn,introKicker:_C,introTitle:OC,introSubtitle:DC,closeButton:Ue,iconHolder:At,headerTitle:nr,headerSubtitle:Hr,header:Te,footer:Le,actionsRow:NC}=De,vd=De.leftActions,Ka=De.rightActions,uo=De.sendButtonWrapper,Wg=De.setSendButtonMode,re=De.micButton,Pn=De.micButtonWrapper,wt=De.attachmentButton,vn=De.attachmentButtonWrapper,ft=De.attachmentInput,Cn=De.attachmentPreviewsContainer;pe.classList.add("persona-relative"),ne.classList.add("persona-relative");let FC=12,Ei=()=>Pr.label??"",UC=()=>Pr.iconName??"arrow-down",$C=()=>Pr.enabled!==!1,In=()=>yn.mode??"anchor-top",or=()=>In()==="follow"||In()==="anchor-top"&&_i,Ti=()=>yn.anchorTopOffset??16,qC=()=>yn.restorePosition??"bottom",Bg=()=>yn.pauseOnInteraction===!0,_g=()=>yn.showActivityWhilePinned!==!1,Og=()=>yn.announce===!0,Cd=()=>yn.scrollbar??"on-scroll",Wt=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");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let ki=k("span","persona-flex persona-items-center"),wd=k("span",""),Rr=k("span","");Rr.setAttribute("data-persona-scroll-to-bottom-count",""),Rr.style.display="none",Wt.append(ki,wd,Rr),pe.appendChild(Wt);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",ne.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"}),pe.appendChild(Lo);let Pi=null,Ga=null,Qa=r=>{!Og()||!r||(Ga=r,Pi===null&&(Pi=setTimeout(()=>{Pi=null,Ga&&Og()&&(Lo.textContent=Ga),Ga=null},400)))},Ya="empty",Xa=0,Sd=()=>Xa||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Wr=()=>{let a=Le.style.display==="none"?0:Le.offsetHeight;Wt.style.bottom=`${a+Sd()+FC}px`};Wr();let xd=()=>{Ms||(Le.style.marginBottom=Xa>0?`${Xa}px`:"")},Ja=()=>{let r=Du(o,xe()),a=Xo(o),m=Le.style.display==="none"?0:Le.offsetHeight,y=a.anchor==="center"&&Ya==="empty"?Ha(a.anchorComposerTop)??Ha("44%"):null,C=y===null||xe()?0:Xb({columnHeight:pe.clientHeight,footerHeight:m,fraction:y});t.style.setProperty("--persona-composer-overlay-height",`${m}px`),t.style.setProperty("--persona-composer-lift",`${r==="overlay"?C:0}px`),Xa=r==="block"?C:0,xd(),Wr()},Dg=()=>{let r=!!Ei();Wt.setAttribute("aria-label",Ei()||"Jump to latest"),Wt.title=Ei(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",r?"true":"false"),ki.innerHTML="";let a=he(UC(),"14px","currentColor",2);a?(ki.appendChild(a),ki.style.display=""):ki.style.display="none",wd.textContent=Ei(),wd.style.display=r?"":"none"};Dg();let Xe=null,Ht=null,Se=Xy(),zC=r=>{try{pe.dispatchEvent(new CustomEvent("persona:composer:state",{detail:r,bubbles:!0,composed:!0}))}catch{}};Se.subscribe(zC);let go=()=>{Se.setText(de?.value??"")},Br=()=>{Se.setMentionRefs(Ht?.getMentionRefs()??[])},jC=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}),Ng=r=>{let a=Object.freeze(r.map(jC));Se.setAttachments(a);try{o.attachments?.onChange?.(a)}catch(d){console.error("[AgentWidget] attachments.onChange failed:",d)}Qd()};Se.setSelectedModelId(o.composer?.selectedModelId);let Ii=()=>o.composer?.modes??[],ws=()=>Mb(Ii(),o.composer?.modeGroups);{let r=qc(o.composer?.defaultActiveModeIds??[],Ii());r.length&&Se.setActiveModeIds(r)}function Fg(r){if(Se.getState().selectedModelId!==r){Se.setSelectedModelId(r),rr?.repaint();try{o.composer?.onModelChange?.(r)}catch(a){console.error("[AgentWidget] composer.onModelChange failed:",a)}}}function Za(r){Se.setActiveModeIds(r),Ho?.render(r,ws()),Ss.forEach(a=>a.repaint()),fo?.resolve(),Al(),no()}function Ad(r){Za(Eb(Se.getState().activeModeIds,r,Ii(),o.composer?.modeGroups))}let rr=null,Md=null,Ho=null,Ss=new Map,sr=null;function mo(r){Se.setQuote(r),sr?.render(Se.getState().quote),no(),Hm()}let Ug=!1;function Ed(){let r=o.composer?.streamingSubmitBehavior??"block";return r!=="interrupt"?r:o.clientToken?"interrupt":(!Ug&&o.debug===!0&&(Ug=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ir=null;function xs(r){Se.setPendingSubmission(r),ir?.render(Se.getState().pendingSubmission),no()}let VC=r=>{let a=Ss.get(r);if(a)return a;let d=Pb({groupId:r,getGroup:()=>o.composer?.modeGroups?.find(m=>m.id===r),getModes:()=>Ii().filter(m=>m.groupId===r),getActiveIds:()=>Se.getState().activeModeIds,onSelect:m=>Ad(m)});return Ss.set(r,d),d},KC=()=>{let r=[],a=Se.getState().activeModeIds,d=new Set;if(Ii().forEach((m,y)=>{if($c(m.groupId,o.composer?.modeGroups)){let C=m.groupId;if(d.has(C))return;d.add(C);let B=VC(C);B.action.order=Ru(y),B.action.label=o.composer?.modeGroups?.find(z=>z.id===C)?.label??C,r.push(B.action);return}r.push({id:xb(m.id),kind:"button",placement:"start",order:Ru(y),presentation:m.presentation??"auto",label:m.label,shortLabel:m.shortLabel,iconName:m.iconName,pressed:a.includes(m.id),onSelect:()=>Ad(m.id)})}),o.composer?.models?.length&&!l.some(m=>m.renderComposer)){let m=o.composer?.modelPicker?.presentation??"native";(!rr||Md!==m)&&(Md=m,rr=wb({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Se.getState().selectedModelId,onSelect:y=>Fg(y),presentation:m,getSuffix:()=>o.composer?.modelPicker?.suffix})),r.push(rr.action)}return r},Td=null,$g=l.find(r=>r.renderHeader);if($g?.renderHeader){let r=$g.renderHeader({config:o,defaultRenderer:()=>{let a=ys({config:o,showClose:Oe()});return Da(pe,a,o),a.header},onClose:()=>at(!1,"user")});if(r){let a=Te;a&&(a.replaceWith(r),Te=r,Tn.header.element=r)}}let qg=()=>{H&&(ne.style.display="none",Le.parentNode?.insertBefore(H.element,Le),H.update())},kd=()=>{if(!xt){Z();return}if(ee=!0,H?qg():dg().then(a=>{H||!ee||!xt||(H=a.createEventStreamView({buffer:xt,getFullHistory:()=>xt.getAllFromStore(),onClose:()=>As(),config:o,plugins:l,getThroughput:()=>dt?.getMetric()??{status:"idle"},renderIconByName:he}),qg())}).catch(()=>{As()}),Ze){Ze.style.boxShadow=`inset 0 0 0 1.5px ${mn.actionIconColor}`;let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(d=>d&&Ze.classList.add(d))}let r=()=>{if(!ee)return;let a=Date.now();a-D>=200&&(H?.update(),D=a),b=requestAnimationFrame(r)};D=0,b=requestAnimationFrame(r),Ut(),w.emit("eventStream:opened",{timestamp:Date.now()})},As=()=>{if(ee){if(ee=!1,H&&H.element.remove(),ne.style.display="",Ze){Ze.style.boxShadow="";let r=o.features?.eventStream?.classNames?.toggleButtonActive;r&&r.split(/\s+/).forEach(a=>a&&Ze.classList.remove(a))}b!==null&&(cancelAnimationFrame(b),b=null),Ut(),w.emit("eventStream:closed",{timestamp:Date.now()})}},Ze=null;if(It){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=mn.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let d=en(yC,"18px","currentColor",1.5);d&&Ze.appendChild(d);let m=De.clearChatButtonWrapper,y=De.closeButtonWrapper,C=m||y;C&&C.parentNode===Te?Te.insertBefore(Ze,C):Te.appendChild(Ze),Ze.addEventListener("click",()=>{ee?As():kd()})}let zg=r=>{let a=o.attachments;if(!a?.enabled)return;let d=r.querySelector("[data-persona-composer-attachment-previews]")??r.querySelector(".persona-attachment-previews");if(!d){d=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),d.setAttribute("data-persona-composer-attachment-previews",""),d.style.display="none";let y=r.querySelector("[data-persona-composer-form]");y?.parentNode?y.parentNode.insertBefore(d,y):r.insertBefore(d,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??Qo).join(","),y.multiple=(a.maxFiles??4)>1,y.style.display="none",y.setAttribute("aria-label",a.buttonTooltipText??"Attach files"),r.appendChild(y)}},Ms=!1,jg=r=>{let a=l.find(y=>y.renderComposer);if(!a?.renderComposer)return null;let d=o.composer,m=u?E.isStreaming():!1;return a.renderComposer({config:o,defaultRenderer:r,requestRender:()=>rh(),storage:g(a.id),onSubmit:y=>{!E||E.isStreaming()||Xl(y.trim(),{consumeDraft:!1})},streaming:m,disabled:m,openAttachmentPicker:()=>{gr()||ft?.click()},models:d?.models,selectedModelId:Se.getState().selectedModelId??d?.selectedModelId,onModelChange:y=>Fg(y),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Td?.()}:void 0})},Vg=jg(()=>Na({config:o}).footer);Vg&&(Tn.replaceComposer(Vg),Le=Tn.composer.footer,Ms=!0);let et=null,GC=r=>{to=r.form,de=r.input,uo=r.sendButton?r.sendButton.parentElement:null,r.sendButton&&(Ee=r.sendButton),r.micButton&&(re=r.micButton,Pn=r.micButton.parentElement),r.found.status&&(ot=r.found.status),r.found.suggestions&&(tr=r.found.suggestions),r.attachmentButton&&(wt=r.attachmentButton,vn=r.attachmentButton.parentElement),ft=r.attachmentInput??null,Cn=r.attachmentPreviews??null,r.found.actionsRow&&(NC=r.found.actionsRow),vd=r.found.actionsStart,Ka=r.found.actionsEnd};function Pd(){let r=de;if(!r)return;let a=o.composer?.inputAttributes,d=!a?.ariaLabel&&!(r instanceof HTMLTextAreaElement)?r.getAttribute("aria-label"):null;_c(r,a),d&&r.setAttribute("aria-label",d),Bc(r,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Pa(r)}),cb(r,Wc(o.composer?.maxLines,xe()?5:3))}let Kg=r=>{et=Zy(r,{debug:o.debug===!0}),et&&GC(et),Pd()};zg(Le),Kg(Le),go();let Li=Tr(o,xe());Li&&(Ie.style.maxWidth=Li,Ie.style.marginLeft="auto",Ie.style.marginRight="auto",Ie.style.width="100%",kn.style.maxWidth=Li,kn.style.marginLeft="auto",kn.style.marginRight="auto",kn.style.width="100%",bd.style.maxWidth=Li,Mi.style.maxWidth=Li,Mi.style.marginLeft="auto",Mi.style.marginRight="auto",Mi.style.width="100%");let Gg=()=>{let r=Tr(o,xe());if(!(!r||xe()))for(let a of[to,tr,Cn,ot])a&&(a.style.maxWidth=r,a.style.marginLeft="auto",a.style.marginRight="auto",a.style.width="100%")};Gg();let Qg=()=>{!o.attachments?.enabled||!ft||!Cn||(Xe?Xe.remountPreviews(Cn):(Xe=Ea.fromConfig(o.attachments,Ng),Xe.setPreviewsContainer(Cn)),et?.addListener(ft,"change",r=>{let a=r.target;Xe?.handleFileSelect(a.files),a.value=""}),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(SC(o.attachments.dropOverlay)))};Qg();let QC=()=>Ht?.prefetch(),Yg=()=>{if(!o.contextMentions?.enabled||!de)return;let r=et?.header??null,a=r?Xp(r):void 0;if(Ht=zb({config:o,textarea:de,anchor:to??de,getMessages:()=>E.getMessages(),liveRegionHost:pe,chipRow:a}),Ht&&!a){let d=de;d.parentElement?.insertBefore(Ht.contextRow,d)}};Yg();let fo=null,YC={getState:()=>Se.getState(),getValue:()=>de?.value??"",setValue:r=>{de&&(de.value=r,de.dispatchEvent(new Event("input",{bubbles:!0})),go())},submit:()=>{Wh(et?.form??null)},openAttachmentPicker:()=>{gr()||ft?.click()},toggleVoice:()=>{Td?.()},requestRender:()=>fo?.resolve()},XC=()=>{let r=[];return(Ht?.affordanceButtons??[]).forEach((d,m)=>{r.push({id:`core:mention-${m}`,placement:"start",order:ko.mention+m,element:d,managed:!0})}),vn&&r.push({id:"core:attachment",placement:"start",order:ko.attachment,element:vn}),Pn&&r.push({id:"core:mic",placement:"end",order:ko.mic,element:Pn}),uo&&r.push({id:"core:send",placement:"end",order:ko.send,element:uo}),r},Xg=()=>{fo?.destroy(),fo=bb({getBindings:()=>et,collect:()=>({builtIns:XC(),configActions:[...KC(),...o.composer?.actions??[]],plugins:l,contributionContext:{config:o,getState:()=>Se.getState(),requestRender:()=>fo?.resolve()},debug:o.debug===!0}),actionContext:YC,getState:()=>Se.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(r,a)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${a.actionId}" failed:`,r)}}),fo.resolve()};Xg();let Id=()=>{if(Ho?.destroy(),Ho=null,!ws().length)return;let r=et?.header;r&&(Ho=Sb({row:Xp(r),onRemove:a=>Ad(a),initialIds:Se.getState().activeModeIds}),Ho.render(Se.getState().activeModeIds,ws()))};Id();let Jg=()=>{sr?.destroy(),sr=null,ir?.destroy(),ir=null;let r=et?.header;r&&(sr=Ib({onDismiss:()=>mo(void 0)}),r.appendChild(sr.element),sr.render(Se.getState().quote),Ed()==="defer-one"&&(ir=Lb({onEdit:()=>AS(),onRemove:()=>xs(void 0)}),r.appendChild(ir.element),ir.render(Se.getState().pendingSubmission)))};Jg();let Ld=Ob(),JC=()=>{let r=et?.header?.querySelector(Rh);if(r)return r.childElementCount>0;let a=Se.getState();return a.mentionRefs.length>0||qc(a.activeModeIds,ws()).length>0},Zg=()=>!1;function no(){let r=Se.getState(),a=Ld.observe(Db(de),r.text);Le.toggleAttribute("data-persona-composer-compact",_b({text:r.text,wrapped:a,hasAttachments:r.attachments.length>0,hasChips:JC(),hasQuote:r.quote!==void 0,hasPendingSubmission:r.pendingSubmission!==void 0,dictationActive:Zg()}))}function em(){o.composer?.layout==="single-row"&&!xe()?Le.setAttribute("data-persona-composer-layout","single-row"):Le.removeAttribute("data-persona-composer-layout")}em(),Se.subscribe(()=>{fo?.sync(),Qd(),Sl(),no(),Hm()}),Sl();let tm=!1,ZC=r=>{if(tm||o.debug!==!0)return;let a=["messages","composer"].filter(d=>r[d]);a.length&&(tm=!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??{};ZC(r);let a=m=>{switch(m){case"body-top":return ne.querySelector("[data-persona-intro-card]");case"messages":return Ie;case"footer-top":return tr;case"composer":return to;case"footer-bottom":return ot;default:return null}},d=(m,y)=>{switch(m){case"header-left":case"header-center":case"header-right":if(m==="header-left")Te.insertBefore(y,Te.firstChild);else if(m==="header-right")Te.appendChild(y);else{let C=Te.querySelector(".persona-flex-col");C?C.parentNode?.insertBefore(y,C.nextSibling):Te.appendChild(y)}break;case"body-top":{let C=ne.querySelector("[data-persona-intro-card]");C?C.replaceWith(y):ne.insertBefore(y,ne.firstChild);break}case"body-bottom":ne.appendChild(y);break;case"footer-top":tr.replaceWith(y);break;case"footer-bottom":ot.replaceWith(y);break;default:break}};for(let[m,y]of Object.entries(r))if(y)try{let C=y({config:o,defaultContent:()=>a(m)});C&&d(m,C)}catch(C){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${m}":`,C)}})();let nm=r=>{let d=r.target.closest('button[data-expand-header="true"]');if(!d)return;let m=d.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!m)return;let y=m.getAttribute("data-message-id");if(!y)return;let C=d.getAttribute("data-bubble-type");if(C==="reasoning")fi.has(y)?fi.delete(y):fi.add(y),_v(y,m);else if(C==="tool")hi.has(y)?hi.delete(y):hi.add(y),Dv(y,m,o);else if(C==="approval"&&f){let z=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",q=f.approvalDetailsExpansionState.get(y)??z;f.approvalDetailsExpansionState.set(y,!q),f.updateApprovalDetailsUI(y,m,o)}Bt.delete(y)};Ie.addEventListener("pointerdown",r=>{r.target.closest('button[data-expand-header="true"]')&&(r.preventDefault(),nm(r))}),Ie.addEventListener("keydown",r=>{let a=r.target;(r.key==="Enter"||r.key===" ")&&a.closest('button[data-expand-header="true"]')&&(r.preventDefault(),nm(r))}),Ie.addEventListener("copy",r=>{let{clipboardData:a}=r;if(!a)return;let d=Ie.getRootNode(),m=typeof d.getSelection=="function"?d.getSelection():window.getSelection();if(!m||m.isCollapsed)return;let y=m.toString(),C=tv(y);!C||C===y||(a.setData("text/plain",C),r.preventDefault())});let Hd=new Map,om=null,rm="idle",ew={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},tw=(r,a)=>{let{icon:d,label:m}=ew[a];r.setAttribute("aria-label",m),r.title=m,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=he(d,14,"currentColor",2);y&&(r.innerHTML="",r.appendChild(y))},sm=()=>{Ie.querySelectorAll('[data-action="read-aloud"]').forEach(a=>{let m=a.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;tw(a,m&&m===om?rm:"idle")})};Ie.addEventListener("click",r=>{let d=r.target.closest(".persona-message-action-btn[data-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.closest("[data-actions-for]");if(!m)return;let y=m.getAttribute("data-actions-for");if(!y)return;let C=d.getAttribute("data-action");if(C==="copy"){let z=E.getMessages().find(q=>q.id===y);if(z&&En.onCopy){let q=z.content||"";navigator.clipboard.writeText(q).then(()=>{d.classList.add("persona-message-action-success");let j=en(bC,14,"currentColor",2);j&&(d.innerHTML="",d.appendChild(j)),setTimeout(()=>{d.classList.remove("persona-message-action-success");let X=en(vC,14,"currentColor",2);X&&(d.innerHTML="",d.appendChild(X))},2e3)}).catch(j=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",j)}),En.onCopy(z)}}else if(C==="read-aloud")E.toggleReadAloud(y);else if(C==="upvote"||C==="downvote"){let z=(Hd.get(y)??null)===C,q=C==="upvote"?"thumbs-up":"thumbs-down";if(z){Hd.delete(y),d.classList.remove("persona-message-action-active");let j=he(q,14,"currentColor",2);j&&(d.innerHTML="",d.appendChild(j))}else{let j=C==="upvote"?"downvote":"upvote",X=m.querySelector(`[data-action="${j}"]`);if(X){X.classList.remove("persona-message-action-active");let lt=he(j==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);lt&&(X.innerHTML="",X.appendChild(lt))}Hd.set(y,C),d.classList.add("persona-message-action-active");let se=he(q,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),d.innerHTML="",d.appendChild(se)),d.classList.remove("persona-message-action-pop"),d.offsetWidth,d.classList.add("persona-message-action-pop");let Ye=E.getMessages().find(it=>it.id===y);Ye&&En.onFeedback&&En.onFeedback({type:C,messageId:Ye.id,message:Ye})}}else if(C==="regenerate")el?.regenerate(y);else if(C==="edit")el?.edit(y);else if(C==="quote")el?.quote(y);else if(C?.startsWith(td)){let B=C.slice(td.length),z=o.messageActions?.custom?.find(j=>j.id===B),q=E.getMessages().find(j=>j.id===y);if(!z||!q)return;try{z.onSelect(q)}catch(j){console.error(`[AgentWidget] messageActions.custom "${B}" onSelect failed:`,j)}}});let el=null;Ie.addEventListener("click",r=>{let d=r.target.closest("button[data-approval-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.closest(".persona-approval-bubble");if(!m)return;let y=m.getAttribute("data-message-id");if(!y)return;let C=d.getAttribute("data-approval-action");if(!C)return;let B=C==="approve"?"approved":"denied",q=E.getMessages().find(X=>X.id===y);if(!q?.approval)return;let j=m.querySelector("[data-approval-buttons]");j&&j.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),q.approval.toolType==="webmcp"?E.resolveWebMcpApproval(y,B):E.resolveApproval(q.approval,B)});let ze=null,im=!1,Hi=null,_r=()=>{},Ri="none",tl=null,$n={artifacts:[],selectedId:null},Ro=!1,oo=!1,Wi=!1,Es=!1,am=()=>Es||$n.artifacts.some(r=>wr(o.features?.artifacts,r)==="panel"),nl=()=>$n.artifacts.length>0&&!Ro&&am(),st={current:null},Rd=(r,a)=>{let d=E.getArtifactById(a),m=d?.markdown,y=d?.title||"artifact",C=d?.file,B=d?.artifactType??"markdown";if(!m){let j=r.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(j){let se=E.getMessages().find(ge=>ge.id===j);if(se?.rawContent)try{let ge=JSON.parse(se.rawContent);m=ge?.props?.markdown,y=ge?.props?.title||y,ge?.props?.file&&typeof ge.props.file=="object"&&(C=ge.props.file),!d&&typeof ge?.props?.artifactType=="string"&&(B=ge.props.artifactType)}catch{}}}return{markdown:m,title:y,file:C,artifactType:B}};Ie.addEventListener("click",r=>{let d=r.target.closest("[data-download-artifact]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-download-artifact");if(!m||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:m})===!0)return;let{markdown:C,title:B,file:z}=Rd(d,m);if(!C)return;let q=Jo();q&&q.triggerArtifactDownload(q.downloadInfoFor({title:B,markdown:C,file:z}))}),Ie.addEventListener("click",r=>{let d=r.target.closest("[data-artifact-custom-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-artifact-custom-action");if(!m)return;let y=d.closest("[data-artifact-inline]"),C=y?null:d.closest("[data-open-artifact]"),B=y?y.getAttribute("data-artifact-inline"):C?.getAttribute("data-open-artifact")??null,q=(y?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(it=>it.id===m);if(!q)return;let{markdown:j,title:X,file:se,artifactType:ge}=Rd(d,B??""),Ye={artifactId:B,title:X,artifactType:ge,markdown:j,file:se};try{Promise.resolve(q.onClick(Ye)).catch(()=>{})}catch{}}),Ie.addEventListener("click",r=>{let d=r.target.closest("[data-copy-artifact]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-copy-artifact");if(!m)return;let y=E.getArtifactById(m),C=Jo();if(!C)return;let B="";if(y)B=C.artifactCopyText(y);else{let{markdown:z,file:q,artifactType:j}=Rd(d,m);j==="markdown"&&(B=C.artifactCopyText({id:m,artifactType:"markdown",status:"complete",markdown:z??"",...q?{file:q}:{}}))}B&&navigator.clipboard.writeText(B).then(()=>{let z=en(bC,16,"currentColor",2);z&&(d.replaceChildren(z),setTimeout(()=>{let q=en(vC,16,"currentColor",2);q&&d.replaceChildren(q)},1500))}).catch(()=>{})}),Ie.addEventListener("click",r=>{let d=r.target.closest("[data-expand-artifact-inline]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-expand-artifact-inline");!m||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:m})===!0||(Ro=!1,Es=!0,oo=!0,Wi=!0,E.selectArtifact(m),ro())}),Ie.addEventListener("click",r=>{let a=r.target;if(a.closest("[data-download-artifact]")||a.closest("[data-artifact-custom-action]"))return;let d=a.closest("[data-open-artifact]");if(!d)return;let m=d.getAttribute("data-open-artifact");!m||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:m})===!0||(r.preventDefault(),r.stopPropagation(),Ro=!1,Es=!0,E.selectArtifact(m),ro())}),Ie.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 Ts=De.composerOverlay,ks=(r,a,d)=>{let m=a.trim();if(!m||!st.current)return;let y=r.getAttribute("data-tool-call-id")??"",C=d.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:y,answer:m,answers:d.structured,values:d.values??(d.source==="multi"?m.split(", "):[m]),isFreeText:C,source:d.source},bubbles:!0,composed:!0})),ri(Ts,y);let B=st.current.getMessages().find(z=>z.toolCall?.id===y);B?.agentMetadata?.awaitingLocalTool?st.current.resolveAskUserQuestion(B,d.structured??m):st.current.sendMessage(m)},Or=r=>{let a=st.current;if(!a)return;let d=r.getAttribute("data-tool-call-id")??"",m=a.getMessages().find(y=>y.toolCall?.id===d);m&&a.persistAskUserQuestionProgress(m,{answers:Cc(r,m),currentIndex:Xn(r)})},lm=r=>Object.entries(r).map(([a,d])=>`${a}: ${Array.isArray(d)?d.join(", "):d}`).join(" | "),Wd=r=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let a=Xn(r),d=oi(r);if(a>=d-1)return;let m=st.current?.getMessages().find(y=>y.toolCall?.id===r.getAttribute("data-tool-call-id"));m&&(Sc(r,m,o,a+1),Or(r))};Ts.addEventListener("click",r=>{let d=r.target.closest("[data-ask-user-action]");if(!d)return;let m=d.closest("[data-persona-ask-sheet-for]");if(!m)return;let y=d.getAttribute("data-ask-user-action");if(r.preventDefault(),r.stopPropagation(),y==="dismiss"){let C=m.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),ri(Ts,C);let B=st.current?.getMessages().find(z=>z.toolCall?.id===C);B?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(B),st.current?.resolveAskUserQuestion(B,"(dismissed)"));return}if(y==="pick"){let C=d.getAttribute("data-option-label");if(!C)return;let B=m.getAttribute("data-multi-select")==="true",z=Sr(m);if(z&&B){let q=fs(m)[Xn(m)],j=new Set(Array.isArray(q)?q:[]);j.has(C)?j.delete(C):j.add(C),xr(m,Array.from(j)),Or(m);return}if(z){xr(m,C),Or(m),Wd(m);return}if(B){let q=d.getAttribute("aria-pressed")==="true";d.setAttribute("aria-pressed",q?"false":"true"),d.classList.toggle("persona-ask-pill-selected",!q);let j=m.querySelector('[data-ask-user-action="submit-multi"]');j&&(j.disabled=lu(m).length===0);return}ks(m,C,{source:"pick",values:[C]});return}if(y==="submit-multi"){let C=lu(m);if(C.length===0)return;ks(m,C.join(", "),{source:"multi",values:C});return}if(y==="open-free-text"){let C=m.querySelector('[data-ask-free-text-row="true"]');C&&(C.classList.remove("persona-hidden"),C.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(y==="focus-free-text"){m.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let B=m.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!B.trim())return;if(Sr(m)){xr(m,B.trim()),Or(m),Wd(m);return}ks(m,B,{source:"free-text"});return}if(y==="next"||y==="back"){if(!st.current)return;let C=m.getAttribute("data-tool-call-id")??"",B=st.current.getMessages().find(se=>se.toolCall?.id===C);if(!B)return;let q=m.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(q){let se=fs(m)[Xn(m)];(typeof se!="string"||se!==q)&&xr(m,q)}let j=y==="next"?1:-1,X=Xn(m)+j;Sc(m,B,o,X),Or(m);return}if(y==="submit-all"){if(!st.current)return;let C=m.getAttribute("data-tool-call-id")??"",B=st.current.getMessages().find(se=>se.toolCall?.id===C);if(!B)return;let q=m.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";q&&xr(m,q);let j=Cc(m,B);st.current.persistAskUserQuestionProgress(B,{answers:j,currentIndex:Xn(m)});let X=lm(j);ks(m,X||"(submitted)",{source:"submit-all",structured:j});return}if(y==="skip"){if(!st.current)return;let C=m.getAttribute("data-tool-call-id")??"",B=st.current.getMessages().find(ge=>ge.toolCall?.id===C);if(!B)return;let z=Sr(m),q=Xn(m),j=oi(m),X=q>=j-1;if(!z){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),ri(Ts,C),B.agentMetadata?.awaitingLocalTool&&(st.current.markAskUserQuestionResolved(B),st.current.resolveAskUserQuestion(B,"(dismissed)"));return}xr(m,"");let se=m.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),X){let ge=Cc(m,B),Ye=lm(ge);ks(m,Ye||"(skipped)",{source:"submit-all",structured:ge});return}Sc(m,B,o,q+1),Or(m);return}}),Ts.addEventListener("keydown",r=>{if(r.key!=="Enter")return;let d=r.target;if(!d.matches?.('[data-ask-free-text-input="true"]'))return;let m=d.closest("[data-persona-ask-sheet-for]");if(!m)return;r.preventDefault();let y=d.value;if(y.trim()){if(Sr(m)){xr(m,y.trim()),Or(m),Wd(m);return}ks(m,y,{source:"free-text"})}});let cm=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 d=Ts.querySelector("[data-persona-ask-sheet-for]");if(!d||d.getAttribute("data-ask-layout")!=="rows"||d.getAttribute("data-multi-select")==="true")return;let m=Number(r.key),C=d.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[m-1];C&&(r.preventDefault(),C.click())};document.addEventListener("keydown",cm);let ho=null,ht=null,Bi=null,ol=null,rl=()=>{},dm=!1,sl="",il="";function Bd(){ol?.(),ol=null}let nw=()=>{let r=Ns&&rs?.isConnected?rs:null,a=r?r.getBoundingClientRect().width:0;return a<=0?200:a+360},pm=()=>{if(!ho||!ht)return;let r=t.classList.contains("persona-artifact-welded-split"),a=t.ownerDocument.defaultView??window,d=a.innerWidth<=640;if(!r||t.classList.contains("persona-artifact-narrow-host")||d){ht.style.removeProperty("position"),ht.style.removeProperty("left"),ht.style.removeProperty("top"),ht.style.removeProperty("bottom"),ht.style.removeProperty("width"),ht.style.removeProperty("z-index");return}let m=ho.firstElementChild;if(!m||m===ht)return;let y=10;ht.style.position="absolute",ht.style.top="0",ht.style.bottom="0",ht.style.width=`${y}px`,ht.style.zIndex="5";let C=yg(ho,a),B=m.offsetWidth+C/2-y/2;ht.style.left=`${Math.max(0,B)}px`},al=()=>{},ow=()=>{let r=t.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,d=o.launcher?.mobileBreakpoint??640;return!a||r.innerWidth>d?!1:ue||Rt(o)},ll=()=>!hn(o)||!nl()||t.classList.contains("persona-artifact-narrow-host")||ow()||(t.ownerDocument.defaultView??window).innerWidth<lT?"none":mg(o)?"detached":"welded",ro=()=>{if(!ze||!hn(o))return;$a(t,o),qa(t,o),al();let r=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,a=Me.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",a>0&&a<=r);let d=nl();ze.setVisible(d),ze.update($n),Ro?(ze.setMobileOpen(!1),ze.element.classList.add("persona-hidden"),ze.backdrop?.classList.add("persona-hidden"),oo=!1,Wi=!1):$n.artifacts.length>0&&am()?(ze.element.classList.remove("persona-hidden"),ze.setMobileOpen(!0)):(ze.setMobileOpen(!1),ze.element.classList.add("persona-hidden"),ze.backdrop?.classList.add("persona-hidden"),oo=!1,Wi=!1);let m=o.features?.artifacts?.layout?.showExpandToggle===!0;if(ze.setExpandToggleVisible(m),ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),ze.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),ze.setTabFade(o.features?.artifacts?.layout?.tabFade),ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!m&&!Wi&&(oo=!1),oo!==dm){let C=ze.element;oo?(sl=C.style.width,il=C.style.maxWidth,C.style.removeProperty("width"),C.style.removeProperty("max-width")):(sl&&(C.style.width=sl),il&&(C.style.maxWidth=il),sl="",il=""),dm=oo}t.classList.toggle("persona-artifact-expanded",oo),ze.setExpanded(oo);let y=ll();y!==Ri&&(Ri=y,_r()),rl()};if(hn(o)){Me.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(pe),ho=a,a.appendChild(r),Me.appendChild(a);let d=y=>{im||ze||(ze=y.createArtifactPane(o,{onSelect:C=>st.current?.selectArtifact(C),onDismiss:()=>{Ro=!0,ro()},onToggleExpand:()=>{let C=!oo,B=$n.selectedId??$n.artifacts[$n.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:B,expanded:C})!==!0&&(oo=C,C||(Wi=!1),ro())}}),ze.element.classList.add("persona-hidden"),a.appendChild(ze.element),ze.backdrop&&Me.appendChild(ze.backdrop),rl(),ro())},m=Jo();m?d(m):(ug(()=>{let y=Jo();y&&d(y)}),ud().catch(()=>{})),rl=()=>{if(!ho||!ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Bi?.(),Bi=null,Bd(),ht&&(ht.remove(),ht=null),ze.element.style.removeProperty("width"),ze.element.style.removeProperty("maxWidth");return}if(!ht){let C=k("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");C.setAttribute("role","separator"),C.setAttribute("aria-orientation","vertical"),C.setAttribute("aria-label","Resize artifacts panel"),C.tabIndex=0;let B=t.ownerDocument,z=B.defaultView??window,q=j=>{if(!ze||j.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||z.innerWidth<=640)return;j.preventDefault(),Bd();let X=j.clientX,se=ze.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,Ye=lt=>{let Kt=ho.getBoundingClientRect().width,Ot=t.classList.contains("persona-artifact-welded-split"),Tt=yg(ho,z),nn=Ot?0:C.getBoundingClientRect().width||6,Je=se-(lt.clientX-X),on=Yv(Je,Kt,Tt,nn,ge?.resizableMinWidth,ge?.resizableMaxWidth,nw());ze.element.style.width=`${on}px`,ze.element.style.maxWidth="none",pm()},it=()=>{B.removeEventListener("pointermove",Ye),B.removeEventListener("pointerup",it),B.removeEventListener("pointercancel",it),ol=null;try{C.releasePointerCapture(j.pointerId)}catch{}};ol=it,B.addEventListener("pointermove",Ye),B.addEventListener("pointerup",it),B.addEventListener("pointercancel",it);try{C.setPointerCapture(j.pointerId)}catch{}};C.addEventListener("pointerdown",q),ht=C,ho.insertBefore(C,ze.element),Bi=()=>{C.removeEventListener("pointerdown",q)}}if(ht){let C=nl();ht.classList.toggle("persona-hidden",!C),pm()}},al=()=>{if(!ue||!ze||(o.launcher?.sidebarMode??!1)||Rt(o)&&Jn(o).reveal==="emerge")return;let C=t.ownerDocument.defaultView??window,B=o.launcher?.mobileFullscreen??!0,z=o.launcher?.mobileBreakpoint??640;if(B&&C.innerWidth<=z||!zv(o,ue))return;let q=o.launcher?.width??o.launcherWidth??Yo,j=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";nl()?(Me.style.width=j,Me.style.maxWidth=j):(Me.style.width=q,Me.style.maxWidth=q)},typeof ResizeObserver<"u"&&(Hi=new ResizeObserver(()=>{ro()}),Hi.observe(Me))}else Me.appendChild(pe);xe()&&Vt&&(De.peekBanner&&Vt.appendChild(De.peekBanner),Vt.appendChild(Le)),t.appendChild(Ke),Vt&&t.appendChild(Vt);let _d=()=>{if(xe()){Me.style.width="100%",Me.style.maxWidth="100%";let ve=o.launcher?.composerBar??{},Fe=Ke.dataset.state==="expanded",ut=ve.expandedSize??"anchored";if(!(Fe&&ut!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let jt=o.theme?.components?.panel,_n=di(o),ds=(ps,oc)=>ps==null||ps===""?oc:gn(_n,ps)??ps,mh="1px solid var(--persona-border)",St="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Qp="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=ds(jt?.border,mh),pe.style.borderRadius=ds(jt?.borderRadius,Qp),pe.style.boxShadow=ds(jt?.shadow,St),pe.style.overflow="hidden";return}let r=Rt(o),a=o.launcher?.sidebarMode??!1,d=r||a||(o.launcher?.fullHeight??!1),m=o.launcher?.enabled===!1,y=o.launcher?.detachedPanel===!0,C=o.theme?.components?.panel,B=di(o),z=(ve,Fe)=>ve==null||ve===""?Fe:gn(B,ve)??ve,q=t.ownerDocument.defaultView??window,j=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,se=q.innerWidth<=X,ge=j&&se&&ue,Ye=r&&j&&se,it=o.launcher?.position??"bottom-left",lt=it==="bottom-left"||it==="top-left",Kt=o.launcher?.zIndex??an,Ot="var(--persona-panel-border, 1px solid var(--persona-border))",Tt="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&&!ge&&!Ye;Je?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let on=Je?Ot:a||ge?"none":Ot,Vo=Je?Tt:ge?"none":a?lt?"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))":m?"none":Tt;r&&!ge&&!Je&&(Vo="none",on="none");let So=Je?nn:a||ge?"0":nn,xo=z(C?.border,on),W=z(C?.shadow,Vo),Re=z(C?.borderRadius,So),Be=ll(),fe=Be==="detached",pt=Be==="welded";t.classList.toggle("persona-artifact-detached-split",fe),t.classList.toggle("persona-artifact-welded-split",pt);let $t="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)))))",kt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&hn(o)&&mg(o)&&m&&!r;t.classList.toggle("persona-artifact-chat-flush",kt);let ke=fe||kt?"none":W,qt=fe?Ot:pt?"none":xo,zt=fe?nn:Re;kt&&(qt="none",zt="0");let Qn=C?.borderRadius!=null&&C.borderRadius!=="",He=kt&&!Qn?"0":Re,bt=ne.scrollTop;t.style.cssText="",Ke.style.cssText="",Me.style.cssText="",pe.style.cssText="",ne.style.cssText="",Ms||(Le.style.cssText=""),ee&&(ne.style.display="none"),(d||m)&&(t.style.minWidth="0");let Ao=()=>{if(bt<=0)return;(ne.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ne.scrollTop===bt)return;let Fe=ne.scrollHeight-ne.clientHeight;Fe<=0||(ne.scrollTop=Math.min(bt,Fe))})};if(ge){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",()=>{f=w,F.forEach((G,ie)=>{let oe=ie<w;G.classList.toggle("selected",oe),G.setAttribute("aria-checked",ie===w-1?"true":"false")})}),F.push(O),T.appendChild(O)}v.appendChild(T);let P=null;if(p){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 K=document.createElement("div");K.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 L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=l,L.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let w=P?.value.trim()||void 0;await e(f,w),g.remove()}catch(w){L.disabled=!1,L.textContent=l,console.error("[CSAT Feedback] Failed to submit:",w)}}),K.appendChild(x),K.appendChild(L),v.appendChild(K),g.appendChild(v),g}function yC(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:p=!0,lowLabel:u="Not likely",highLabel:g="Very likely"}=t,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let v=null,h=document.createElement("div");h.className="persona-feedback-content";let M=document.createElement("div");M.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=o,M.appendChild(A);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,M.appendChild(T),h.appendChild(M);let F=document.createElement("div");F.className="persona-feedback-rating persona-feedback-rating-nps",F.setAttribute("role","radiogroup"),F.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let K=document.createElement("span");K.className="persona-feedback-label-low",K.textContent=u;let x=document.createElement("span");x.className="persona-feedback-label-high",x.textContent=g,P.appendChild(K),P.appendChild(x);let L=document.createElement("div");L.className="persona-feedback-numbers";let w=[];for(let S=0;S<=10;S++){let _=document.createElement("button");_.type="button",_.className="persona-feedback-rating-btn persona-feedback-number-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`Rating ${S} out of 10`),_.textContent=String(S),_.dataset.rating=String(S),S<=6?_.classList.add("persona-feedback-detractor"):S<=8?_.classList.add("persona-feedback-passive"):_.classList.add("persona-feedback-promoter"),_.addEventListener("click",()=>{v=S,w.forEach((R,I)=>{R.classList.toggle("selected",I===S),R.setAttribute("aria-checked",I===S?"true":"false")})}),w.push(_),L.appendChild(_)}F.appendChild(P),F.appendChild(L),h.appendChild(F);let O=null;if(p){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 G=document.createElement("div");G.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?.(),f.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="persona-feedback-btn persona-feedback-btn-submit",oe.textContent=l,oe.addEventListener("click",async()=>{if(v===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let S=O?.value.trim()||void 0;await e(v,S),f.remove()}catch(S){oe.disabled=!1,oe.textContent=l,console.error("[NPS Feedback] Failed to submit:",S)}}),G.appendChild(ie),G.appendChild(oe),h.appendChild(G),f.appendChild(h),f}var Ci="persona-chat-history",pT=30*1e3,uT=641,wi="data-persona-composer-reason",gT={"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 mT(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=gT[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 yd(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 fT(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 hT(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var kg=t=>!t||typeof t!="object"?{}:{...t},wC=t=>t.map(e=>({...e,streaming:!1})),SC=(t,e,n)=>{let o=t?.markdown?vh(t.markdown):null,s=Ch(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 p=c.text??"",u=c.message.rawContent??null;if(e){let v=e.process({text:p,raw:u??p,message:c.message,streaming:c.streaming});v!==null&&(p=v.text,v.persist||(c.message.__skipPersist=!0),v.resubmit&&!c.streaming&&n&&n())}let g=Ys()!==null,f;if(t?.postprocessMessage){let v=t.postprocessMessage({...c,text:p,raw:u??c.text??""});f=s?s(v):v}else if(o){let v=c.streaming?Zh(p):p,h=o(v);f=s&&g?s(h):h}else f=ac(p);return f};return c=>{try{return l(c)}catch(p){return i||(i=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",p)),ac(c.text??"")}}};function xC(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=he(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 yT=(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},bT=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:yT(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),AC=(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=Rc(e),s=()=>{rb({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};s();let i=o.features;o=yg(o);let l=Cg.getForInstance(o.plugins),c=tv(t),p=[],u=!1,g=_v(()=>o),f=null,v=null,h=null,M=!1,A=null,T=r=>{f=r,r.initApprovalUi({webMcpToolTitle:lc});let a=r.createBuiltInApprovalPlugin();v=a.plugin,h=a.teardown},F=()=>{if(f)return f;let r=Uv();return r?(T(r),r):(Fv().then(a=>{M||f||(T(a),A?.())}).catch(()=>{}),null)},P=!1,K=!1,x=null,L=(r,a,d,m)=>{if(!r.querySelector("[data-tv-form]"))return;let y=Zv();if(y){y.enhanceWithForms(r,a,d,m);return}Jv().then(()=>{P||K||!x||(K=!0,x())}).catch(()=>{})};o.components&&Go.registerAll(o.components);let w=oC(),G=o.persistState===!1?null:o.storageAdapter??sC(),ie={},oe=null,S,_=new Promise(r=>{S=r}),R,I=!1,Y=r=>{if(o.onStateLoaded)try{let a=o.onStateLoaded(r);if(a&&typeof a=="object"&&"state"in a){let{state:d,open:m}=a;return m&&(I=!0),d}return a}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}return r};if(G?.load)try{let r=G.load();if(r&&typeof r.then=="function")oe=r.then(a=>Y(a??{messages:[],metadata:{}}));else{let d=Y(r??{messages:[],metadata:{}});d.metadata&&(ie=kg(d.metadata)),d.messages?.length&&(o={...o,initialMessages:d.messages}),d.artifacts?.length&&(o={...o,initialArtifacts:d.artifacts,initialSelectedArtifactId:d.selectedArtifactId??null}),R=d.draft}}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",r)}else if(o.onStateLoaded)try{let r=Y({messages:[],metadata:{}});r.messages?.length&&(o={...o,initialMessages:r.messages})}catch(r){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",r)}oe||S();let V=()=>ie,ae=r=>{ie=r({...ie})??{},Oi()},ce=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Sg],me=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[za.message,za.messageAndClick],Ce=xg({parsers:ce,handlers:me,getSessionMetadata:V,updateSessionMetadata:ae,emit:w.emit,documentRef:typeof document<"u"?document:null});Ce.syncFromMetadata();let ue=o.launcher?.enabled??!0,_e=o.launcher?.autoExpand??!1,ct=o.autoFocusInput??!1,we=_e,$=ue,Pe=o.layout?.header?.layout,Ne=!1,xe=()=>_a(o),Oe=()=>ue||xe(),ye=xe()?!1:ue?_e:!0,gt=!1,Zn=null,Cs=()=>{gt=!0,Zn&&clearTimeout(Zn),Zn=setTimeout(()=>{gt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),gt=!1)},1e4)},Jt=SC(o,Ce,Cs),Fn=o.features?.showReasoning??!0,Io=o.features?.showToolCalls??!0,It=o.features?.showEventStreamToggle??!1,Pr=o.features?.scrollToBottom??{},yn=o.features?.scrollBehavior??{},po=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Ir=`${po()}event-stream`,ln=null,Ai=o.features?.eventStream?.maxEvents??2e3,xt=null,dt=null,eo=null,Va=!1,H=null,ee=!1,b=null,D=0,N=(r,a)=>{xt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:r,timestamp:Date.now(),payload:JSON.stringify(a)})},U=(r,a)=>{dt?.processEvent(r,a),xt?N(r,a):eo&&(eo.length>=Ai&&eo.shift(),eo.push({type:r,payload:a}))},Z=()=>{xt||!It||(eo??(eo=[]),pg().then(r=>{if(Va||xt||!It)return;ln=new r.EventStreamStore(Ir),xt=new r.EventStreamBuffer(Ai,ln),dt=dt??new r.ThroughputTracker,ln.open().then(()=>xt?.restore()).catch(d=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",d)});let a=eo??[];eo=null;for(let d of a)dt?.processEvent(d.type,d.payload),N(d.type,d.payload)}).catch(()=>{}))};It&&Z();let te=!1,le=null,Ae=()=>{},mt=()=>{},qe=()=>{},Lt=()=>{},Ct=()=>{},Lr=()=>ee||te&&le==="panel",En={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)}},Nt=o.statusIndicator??{},cn=r=>r==="idle"?Nt.idleText??Dt.idle:r==="connecting"?Nt.connectingText??Dt.connecting:r==="connected"?Nt.connectedText??Dt.connected:r==="error"?Nt.errorText??Dt.error:r==="paused"?Nt.pausedText??Dt.paused:r==="resuming"?Nt.resumingText??Dt.resuming:Dt[r];function tn(r,a,d,m){if(!r.hasAttribute(wi))if(m==="idle"&&d.idleLink){r.textContent="";let y=document.createElement("a");y.href=d.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 Tn=Bv({config:o,showClose:Oe()}),{wrapper:Ke,panel:Me,pillRoot:Vt}=Tn.shell,De=Tn.panelElements,{container:pe,body:ne,messagesWrapper:Ie,starterSuggestions:vd,transcriptSuggestions:Mi,suggestions:tr,textarea:de,sendButton:Ee,composerForm:to,statusText:ot,welcomeHost:bn,welcomeIconHolder:_C,greetingHost:kn,introKicker:OC,introTitle:DC,introSubtitle:NC,closeButton:Ue,iconHolder:At,headerTitle:nr,headerSubtitle:Hr,header:Te,footer:Le,actionsRow:FC}=De,Cd=De.leftActions,Ka=De.rightActions,uo=De.sendButtonWrapper,Bg=De.setSendButtonMode,re=De.micButton,Pn=De.micButtonWrapper,wt=De.attachmentButton,vn=De.attachmentButtonWrapper,ft=De.attachmentInput,Cn=De.attachmentPreviewsContainer;pe.classList.add("persona-relative"),ne.classList.add("persona-relative");let UC=12,Ei=()=>Pr.label??"",$C=()=>Pr.iconName??"arrow-down",qC=()=>Pr.enabled!==!1,In=()=>yn.mode??"anchor-top",or=()=>In()==="follow"||In()==="anchor-top"&&_i,Ti=()=>yn.anchorTopOffset??16,zC=()=>yn.restorePosition??"bottom",_g=()=>yn.pauseOnInteraction===!0,Og=()=>yn.showActivityWhilePinned!==!1,Dg=()=>yn.announce===!0,wd=()=>yn.scrollbar??"on-scroll",Wt=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");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let ki=k("span","persona-flex persona-items-center"),Sd=k("span",""),Rr=k("span","");Rr.setAttribute("data-persona-scroll-to-bottom-count",""),Rr.style.display="none",Wt.append(ki,Sd,Rr),pe.appendChild(Wt);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",ne.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"}),pe.appendChild(Lo);let Pi=null,Ga=null,Qa=r=>{!Dg()||!r||(Ga=r,Pi===null&&(Pi=setTimeout(()=>{Pi=null,Ga&&Dg()&&(Lo.textContent=Ga),Ga=null},400)))},Ya="empty",Xa=0,xd=()=>Xa||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Wr=()=>{let a=Le.style.display==="none"?0:Le.offsetHeight;Wt.style.bottom=`${a+xd()+UC}px`};Wr();let Ad=()=>{Ms||(Le.style.marginBottom=Xa>0?`${Xa}px`:"")},Ja=()=>{let r=Nu(o,xe()),a=Xo(o),m=Le.style.display==="none"?0:Le.offsetHeight,y=a.anchor==="center"&&Ya==="empty"?Ha(a.anchorComposerTop)??Ha("44%"):null,C=y===null||xe()?0:Jb({columnHeight:pe.clientHeight,footerHeight:m,fraction:y});t.style.setProperty("--persona-composer-overlay-height",`${m}px`),t.style.setProperty("--persona-composer-lift",`${r==="overlay"?C:0}px`),Xa=r==="block"?C:0,Ad(),Wr()},Ng=()=>{let r=!!Ei();Wt.setAttribute("aria-label",Ei()||"Jump to latest"),Wt.title=Ei(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",r?"true":"false"),ki.innerHTML="";let a=he($C(),"14px","currentColor",2);a?(ki.appendChild(a),ki.style.display=""):ki.style.display="none",Sd.textContent=Ei(),Sd.style.display=r?"":"none"};Ng();let Xe=null,Ht=null,Se=Jy(),jC=r=>{try{pe.dispatchEvent(new CustomEvent("persona:composer:state",{detail:r,bubbles:!0,composed:!0}))}catch{}};Se.subscribe(jC);let go=()=>{Se.setText(de?.value??"")},Br=()=>{Se.setMentionRefs(Ht?.getMentionRefs()??[])},VC=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}),Fg=r=>{let a=Object.freeze(r.map(VC));Se.setAttachments(a);try{o.attachments?.onChange?.(a)}catch(d){console.error("[AgentWidget] attachments.onChange failed:",d)}Yd()};Se.setSelectedModelId(o.composer?.selectedModelId);let Ii=()=>o.composer?.modes??[],ws=()=>Eb(Ii(),o.composer?.modeGroups);{let r=zc(o.composer?.defaultActiveModeIds??[],Ii());r.length&&Se.setActiveModeIds(r)}function Ug(r){if(Se.getState().selectedModelId!==r){Se.setSelectedModelId(r),rr?.repaint();try{o.composer?.onModelChange?.(r)}catch(a){console.error("[AgentWidget] composer.onModelChange failed:",a)}}}function Za(r){Se.setActiveModeIds(r),Ho?.render(r,ws()),Ss.forEach(a=>a.repaint()),fo?.resolve(),Al(),no()}function Md(r){Za(Tb(Se.getState().activeModeIds,r,Ii(),o.composer?.modeGroups))}let rr=null,Ed=null,Ho=null,Ss=new Map,sr=null;function mo(r){Se.setQuote(r),sr?.render(Se.getState().quote),no(),Rm()}let $g=!1;function Td(){let r=o.composer?.streamingSubmitBehavior??"block";return r!=="interrupt"?r:o.clientToken?"interrupt":(!$g&&o.debug===!0&&($g=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ir=null;function xs(r){Se.setPendingSubmission(r),ir?.render(Se.getState().pendingSubmission),no()}let KC=r=>{let a=Ss.get(r);if(a)return a;let d=Ib({groupId:r,getGroup:()=>o.composer?.modeGroups?.find(m=>m.id===r),getModes:()=>Ii().filter(m=>m.groupId===r),getActiveIds:()=>Se.getState().activeModeIds,onSelect:m=>Md(m)});return Ss.set(r,d),d},GC=()=>{let r=[],a=Se.getState().activeModeIds,d=new Set;if(Ii().forEach((m,y)=>{if(qc(m.groupId,o.composer?.modeGroups)){let C=m.groupId;if(d.has(C))return;d.add(C);let B=KC(C);B.action.order=Wu(y),B.action.label=o.composer?.modeGroups?.find(z=>z.id===C)?.label??C,r.push(B.action);return}r.push({id:Ab(m.id),kind:"button",placement:"start",order:Wu(y),presentation:m.presentation??"auto",label:m.label,shortLabel:m.shortLabel,iconName:m.iconName,pressed:a.includes(m.id),onSelect:()=>Md(m.id)})}),o.composer?.models?.length&&!l.some(m=>m.renderComposer)){let m=o.composer?.modelPicker?.presentation??"native";(!rr||Ed!==m)&&(Ed=m,rr=Sb({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Se.getState().selectedModelId,onSelect:y=>Ug(y),presentation:m,getSuffix:()=>o.composer?.modelPicker?.suffix})),r.push(rr.action)}return r},kd=null,qg=l.find(r=>r.renderHeader);if(qg?.renderHeader){let r=qg.renderHeader({config:o,defaultRenderer:()=>{let a=ys({config:o,showClose:Oe()});return Da(pe,a,o),a.header},onClose:()=>at(!1,"user")});if(r){let a=Te;a&&(a.replaceWith(r),Te=r,Tn.header.element=r)}}let zg=()=>{H&&(ne.style.display="none",Le.parentNode?.insertBefore(H.element,Le),H.update())},Pd=()=>{if(!xt){Z();return}if(ee=!0,H?zg():pg().then(a=>{H||!ee||!xt||(H=a.createEventStreamView({buffer:xt,getFullHistory:()=>xt.getAllFromStore(),onClose:()=>As(),config:o,plugins:l,getThroughput:()=>dt?.getMetric()??{status:"idle"},renderIconByName:he}),zg())}).catch(()=>{As()}),Ze){Ze.style.boxShadow=`inset 0 0 0 1.5px ${mn.actionIconColor}`;let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(d=>d&&Ze.classList.add(d))}let r=()=>{if(!ee)return;let a=Date.now();a-D>=200&&(H?.update(),D=a),b=requestAnimationFrame(r)};D=0,b=requestAnimationFrame(r),Ut(),w.emit("eventStream:opened",{timestamp:Date.now()})},As=()=>{if(ee){if(ee=!1,H&&H.element.remove(),ne.style.display="",Ze){Ze.style.boxShadow="";let r=o.features?.eventStream?.classNames?.toggleButtonActive;r&&r.split(/\s+/).forEach(a=>a&&Ze.classList.remove(a))}b!==null&&(cancelAnimationFrame(b),b=null),Ut(),w.emit("eventStream:closed",{timestamp:Date.now()})}},Ze=null;if(It){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=mn.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let d=en(bC,"18px","currentColor",1.5);d&&Ze.appendChild(d);let m=De.clearChatButtonWrapper,y=De.closeButtonWrapper,C=m||y;C&&C.parentNode===Te?Te.insertBefore(Ze,C):Te.appendChild(Ze),Ze.addEventListener("click",()=>{ee?As():Pd()})}let jg=r=>{let a=o.attachments;if(!a?.enabled)return;let d=r.querySelector("[data-persona-composer-attachment-previews]")??r.querySelector(".persona-attachment-previews");if(!d){d=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),d.setAttribute("data-persona-composer-attachment-previews",""),d.style.display="none";let y=r.querySelector("[data-persona-composer-form]");y?.parentNode?y.parentNode.insertBefore(d,y):r.insertBefore(d,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??Qo).join(","),y.multiple=(a.maxFiles??4)>1,y.style.display="none",y.setAttribute("aria-label",a.buttonTooltipText??"Attach files"),r.appendChild(y)}},Ms=!1,Vg=r=>{let a=l.find(y=>y.renderComposer);if(!a?.renderComposer)return null;let d=o.composer,m=u?E.isStreaming():!1;return a.renderComposer({config:o,defaultRenderer:r,requestRender:()=>sh(),storage:g(a.id),onSubmit:y=>{!E||E.isStreaming()||Xl(y.trim(),{consumeDraft:!1})},streaming:m,disabled:m,openAttachmentPicker:()=>{gr()||ft?.click()},models:d?.models,selectedModelId:Se.getState().selectedModelId??d?.selectedModelId,onModelChange:y=>Ug(y),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{kd?.()}:void 0})},Kg=Vg(()=>Na({config:o}).footer);Kg&&(Tn.replaceComposer(Kg),Le=Tn.composer.footer,Ms=!0);let et=null,QC=r=>{to=r.form,de=r.input,uo=r.sendButton?r.sendButton.parentElement:null,r.sendButton&&(Ee=r.sendButton),r.micButton&&(re=r.micButton,Pn=r.micButton.parentElement),r.found.status&&(ot=r.found.status),r.found.suggestions&&(tr=r.found.suggestions),r.attachmentButton&&(wt=r.attachmentButton,vn=r.attachmentButton.parentElement),ft=r.attachmentInput??null,Cn=r.attachmentPreviews??null,r.found.actionsRow&&(FC=r.found.actionsRow),Cd=r.found.actionsStart,Ka=r.found.actionsEnd};function Id(){let r=de;if(!r)return;let a=o.composer?.inputAttributes,d=!a?.ariaLabel&&!(r instanceof HTMLTextAreaElement)?r.getAttribute("aria-label"):null;_c(r,a),d&&r.setAttribute("aria-label",d),Bc(r,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Pa(r)}),db(r,Wc(o.composer?.maxLines,xe()?5:3))}let Gg=r=>{et=eb(r,{debug:o.debug===!0}),et&&QC(et),Id()};jg(Le),Gg(Le),go();let Li=Tr(o,xe());Li&&(Ie.style.maxWidth=Li,Ie.style.marginLeft="auto",Ie.style.marginRight="auto",Ie.style.width="100%",kn.style.maxWidth=Li,kn.style.marginLeft="auto",kn.style.marginRight="auto",kn.style.width="100%",vd.style.maxWidth=Li,Mi.style.maxWidth=Li,Mi.style.marginLeft="auto",Mi.style.marginRight="auto",Mi.style.width="100%");let Qg=()=>{let r=Tr(o,xe());if(!(!r||xe()))for(let a of[to,tr,Cn,ot])a&&(a.style.maxWidth=r,a.style.marginLeft="auto",a.style.marginRight="auto",a.style.width="100%")};Qg();let Yg=()=>{!o.attachments?.enabled||!ft||!Cn||(Xe?Xe.remountPreviews(Cn):(Xe=Ea.fromConfig(o.attachments,Fg),Xe.setPreviewsContainer(Cn)),et?.addListener(ft,"change",r=>{let a=r.target;Xe?.handleFileSelect(a.files),a.value=""}),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(xC(o.attachments.dropOverlay)))};Yg();let YC=()=>Ht?.prefetch(),Xg=()=>{if(!o.contextMentions?.enabled||!de)return;let r=et?.header??null,a=r?Jp(r):void 0;if(Ht=jb({config:o,textarea:de,anchor:to??de,getMessages:()=>E.getMessages(),liveRegionHost:pe,chipRow:a}),Ht&&!a){let d=de;d.parentElement?.insertBefore(Ht.contextRow,d)}};Xg();let fo=null,XC={getState:()=>Se.getState(),getValue:()=>de?.value??"",setValue:r=>{de&&(de.value=r,de.dispatchEvent(new Event("input",{bubbles:!0})),go())},submit:()=>{Bh(et?.form??null)},openAttachmentPicker:()=>{gr()||ft?.click()},toggleVoice:()=>{kd?.()},requestRender:()=>fo?.resolve()},JC=()=>{let r=[];return(Ht?.affordanceButtons??[]).forEach((d,m)=>{r.push({id:`core:mention-${m}`,placement:"start",order:ko.mention+m,element:d,managed:!0})}),vn&&r.push({id:"core:attachment",placement:"start",order:ko.attachment,element:vn}),Pn&&r.push({id:"core:mic",placement:"end",order:ko.mic,element:Pn}),uo&&r.push({id:"core:send",placement:"end",order:ko.send,element:uo}),r},Jg=()=>{fo?.destroy(),fo=vb({getBindings:()=>et,collect:()=>({builtIns:JC(),configActions:[...GC(),...o.composer?.actions??[]],plugins:l,contributionContext:{config:o,getState:()=>Se.getState(),requestRender:()=>fo?.resolve()},debug:o.debug===!0}),actionContext:XC,getState:()=>Se.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(r,a)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${a.actionId}" failed:`,r)}}),fo.resolve()};Jg();let Ld=()=>{if(Ho?.destroy(),Ho=null,!ws().length)return;let r=et?.header;r&&(Ho=xb({row:Jp(r),onRemove:a=>Md(a),initialIds:Se.getState().activeModeIds}),Ho.render(Se.getState().activeModeIds,ws()))};Ld();let Zg=()=>{sr?.destroy(),sr=null,ir?.destroy(),ir=null;let r=et?.header;r&&(sr=Lb({onDismiss:()=>mo(void 0)}),r.appendChild(sr.element),sr.render(Se.getState().quote),Td()==="defer-one"&&(ir=Hb({onEdit:()=>MS(),onRemove:()=>xs(void 0)}),r.appendChild(ir.element),ir.render(Se.getState().pendingSubmission)))};Zg();let Hd=Db(),ZC=()=>{let r=et?.header?.querySelector(Wh);if(r)return r.childElementCount>0;let a=Se.getState();return a.mentionRefs.length>0||zc(a.activeModeIds,ws()).length>0},em=()=>!1;function no(){let r=Se.getState(),a=Hd.observe(Nb(de),r.text);Le.toggleAttribute("data-persona-composer-compact",Ob({text:r.text,wrapped:a,hasAttachments:r.attachments.length>0,hasChips:ZC(),hasQuote:r.quote!==void 0,hasPendingSubmission:r.pendingSubmission!==void 0,dictationActive:em()}))}function tm(){o.composer?.layout==="single-row"&&!xe()?Le.setAttribute("data-persona-composer-layout","single-row"):Le.removeAttribute("data-persona-composer-layout")}tm(),Se.subscribe(()=>{fo?.sync(),Yd(),Sl(),no(),Rm()}),Sl();let nm=!1,ew=r=>{if(nm||o.debug!==!0)return;let a=["messages","composer"].filter(d=>r[d]);a.length&&(nm=!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??{};ew(r);let a=m=>{switch(m){case"body-top":return ne.querySelector("[data-persona-intro-card]");case"messages":return Ie;case"footer-top":return tr;case"composer":return to;case"footer-bottom":return ot;default:return null}},d=(m,y)=>{switch(m){case"header-left":case"header-center":case"header-right":if(m==="header-left")Te.insertBefore(y,Te.firstChild);else if(m==="header-right")Te.appendChild(y);else{let C=Te.querySelector(".persona-flex-col");C?C.parentNode?.insertBefore(y,C.nextSibling):Te.appendChild(y)}break;case"body-top":{let C=ne.querySelector("[data-persona-intro-card]");C?C.replaceWith(y):ne.insertBefore(y,ne.firstChild);break}case"body-bottom":ne.appendChild(y);break;case"footer-top":tr.replaceWith(y);break;case"footer-bottom":ot.replaceWith(y);break;default:break}};for(let[m,y]of Object.entries(r))if(y)try{let C=y({config:o,defaultContent:()=>a(m)});C&&d(m,C)}catch(C){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${m}":`,C)}})();let om=r=>{let d=r.target.closest('button[data-expand-header="true"]');if(!d)return;let m=d.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!m)return;let y=m.getAttribute("data-message-id");if(!y)return;let C=d.getAttribute("data-bubble-type");if(C==="reasoning")fi.has(y)?fi.delete(y):fi.add(y),Ov(y,m);else if(C==="tool")hi.has(y)?hi.delete(y):hi.add(y),Nv(y,m,o);else if(C==="approval"&&f){let z=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",q=f.approvalDetailsExpansionState.get(y)??z;f.approvalDetailsExpansionState.set(y,!q),f.updateApprovalDetailsUI(y,m,o)}Bt.delete(y)};Ie.addEventListener("pointerdown",r=>{r.target.closest('button[data-expand-header="true"]')&&(r.preventDefault(),om(r))}),Ie.addEventListener("keydown",r=>{let a=r.target;(r.key==="Enter"||r.key===" ")&&a.closest('button[data-expand-header="true"]')&&(r.preventDefault(),om(r))}),Ie.addEventListener("copy",r=>{let{clipboardData:a}=r;if(!a)return;let d=Ie.getRootNode(),m=typeof d.getSelection=="function"?d.getSelection():window.getSelection();if(!m||m.isCollapsed)return;let y=m.toString(),C=nv(y);!C||C===y||(a.setData("text/plain",C),r.preventDefault())});let Rd=new Map,rm=null,sm="idle",tw={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},nw=(r,a)=>{let{icon:d,label:m}=tw[a];r.setAttribute("aria-label",m),r.title=m,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=he(d,14,"currentColor",2);y&&(r.innerHTML="",r.appendChild(y))},im=()=>{Ie.querySelectorAll('[data-action="read-aloud"]').forEach(a=>{let m=a.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;nw(a,m&&m===rm?sm:"idle")})};Ie.addEventListener("click",r=>{let d=r.target.closest(".persona-message-action-btn[data-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.closest("[data-actions-for]");if(!m)return;let y=m.getAttribute("data-actions-for");if(!y)return;let C=d.getAttribute("data-action");if(C==="copy"){let z=E.getMessages().find(q=>q.id===y);if(z&&En.onCopy){let q=z.content||"";navigator.clipboard.writeText(q).then(()=>{d.classList.add("persona-message-action-success");let j=en(vC,14,"currentColor",2);j&&(d.innerHTML="",d.appendChild(j)),setTimeout(()=>{d.classList.remove("persona-message-action-success");let X=en(CC,14,"currentColor",2);X&&(d.innerHTML="",d.appendChild(X))},2e3)}).catch(j=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",j)}),En.onCopy(z)}}else if(C==="read-aloud")E.toggleReadAloud(y);else if(C==="upvote"||C==="downvote"){let z=(Rd.get(y)??null)===C,q=C==="upvote"?"thumbs-up":"thumbs-down";if(z){Rd.delete(y),d.classList.remove("persona-message-action-active");let j=he(q,14,"currentColor",2);j&&(d.innerHTML="",d.appendChild(j))}else{let j=C==="upvote"?"downvote":"upvote",X=m.querySelector(`[data-action="${j}"]`);if(X){X.classList.remove("persona-message-action-active");let lt=he(j==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);lt&&(X.innerHTML="",X.appendChild(lt))}Rd.set(y,C),d.classList.add("persona-message-action-active");let se=he(q,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),d.innerHTML="",d.appendChild(se)),d.classList.remove("persona-message-action-pop"),d.offsetWidth,d.classList.add("persona-message-action-pop");let Ye=E.getMessages().find(it=>it.id===y);Ye&&En.onFeedback&&En.onFeedback({type:C,messageId:Ye.id,message:Ye})}}else if(C==="regenerate")el?.regenerate(y);else if(C==="edit")el?.edit(y);else if(C==="quote")el?.quote(y);else if(C?.startsWith(nd)){let B=C.slice(nd.length),z=o.messageActions?.custom?.find(j=>j.id===B),q=E.getMessages().find(j=>j.id===y);if(!z||!q)return;try{z.onSelect(q)}catch(j){console.error(`[AgentWidget] messageActions.custom "${B}" onSelect failed:`,j)}}});let el=null;Ie.addEventListener("click",r=>{let d=r.target.closest("button[data-approval-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.closest(".persona-approval-bubble");if(!m)return;let y=m.getAttribute("data-message-id");if(!y)return;let C=d.getAttribute("data-approval-action");if(!C)return;let B=C==="approve"?"approved":"denied",q=E.getMessages().find(X=>X.id===y);if(!q?.approval)return;let j=m.querySelector("[data-approval-buttons]");j&&j.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),q.approval.toolType==="webmcp"?E.resolveWebMcpApproval(y,B):E.resolveApproval(q.approval,B)});let ze=null,am=!1,Hi=null,_r=()=>{},Ri="none",tl=null,$n={artifacts:[],selectedId:null},Ro=!1,oo=!1,Wi=!1,Es=!1,lm=()=>Es||$n.artifacts.some(r=>wr(o.features?.artifacts,r)==="panel"),nl=()=>$n.artifacts.length>0&&!Ro&&lm(),st={current:null},Wd=(r,a)=>{let d=E.getArtifactById(a),m=d?.markdown,y=d?.title||"artifact",C=d?.file,B=d?.artifactType??"markdown";if(!m){let j=r.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(j){let se=E.getMessages().find(ge=>ge.id===j);if(se?.rawContent)try{let ge=JSON.parse(se.rawContent);m=ge?.props?.markdown,y=ge?.props?.title||y,ge?.props?.file&&typeof ge.props.file=="object"&&(C=ge.props.file),!d&&typeof ge?.props?.artifactType=="string"&&(B=ge.props.artifactType)}catch{}}}return{markdown:m,title:y,file:C,artifactType:B}};Ie.addEventListener("click",r=>{let d=r.target.closest("[data-download-artifact]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-download-artifact");if(!m||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:m})===!0)return;let{markdown:C,title:B,file:z}=Wd(d,m);if(!C)return;let q=Jo();q&&q.triggerArtifactDownload(q.downloadInfoFor({title:B,markdown:C,file:z}))}),Ie.addEventListener("click",r=>{let d=r.target.closest("[data-artifact-custom-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-artifact-custom-action");if(!m)return;let y=d.closest("[data-artifact-inline]"),C=y?null:d.closest("[data-open-artifact]"),B=y?y.getAttribute("data-artifact-inline"):C?.getAttribute("data-open-artifact")??null,q=(y?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(it=>it.id===m);if(!q)return;let{markdown:j,title:X,file:se,artifactType:ge}=Wd(d,B??""),Ye={artifactId:B,title:X,artifactType:ge,markdown:j,file:se};try{Promise.resolve(q.onClick(Ye)).catch(()=>{})}catch{}}),Ie.addEventListener("click",r=>{let d=r.target.closest("[data-copy-artifact]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-copy-artifact");if(!m)return;let y=E.getArtifactById(m),C=Jo();if(!C)return;let B="";if(y)B=C.artifactCopyText(y);else{let{markdown:z,file:q,artifactType:j}=Wd(d,m);j==="markdown"&&(B=C.artifactCopyText({id:m,artifactType:"markdown",status:"complete",markdown:z??"",...q?{file:q}:{}}))}B&&navigator.clipboard.writeText(B).then(()=>{let z=en(vC,16,"currentColor",2);z&&(d.replaceChildren(z),setTimeout(()=>{let q=en(CC,16,"currentColor",2);q&&d.replaceChildren(q)},1500))}).catch(()=>{})}),Ie.addEventListener("click",r=>{let d=r.target.closest("[data-expand-artifact-inline]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-expand-artifact-inline");!m||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:m})===!0||(Ro=!1,Es=!0,oo=!0,Wi=!0,E.selectArtifact(m),ro())}),Ie.addEventListener("click",r=>{let a=r.target;if(a.closest("[data-download-artifact]")||a.closest("[data-artifact-custom-action]"))return;let d=a.closest("[data-open-artifact]");if(!d)return;let m=d.getAttribute("data-open-artifact");!m||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:m})===!0||(r.preventDefault(),r.stopPropagation(),Ro=!1,Es=!0,E.selectArtifact(m),ro())}),Ie.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 Ts=De.composerOverlay,ks=(r,a,d)=>{let m=a.trim();if(!m||!st.current)return;let y=r.getAttribute("data-tool-call-id")??"",C=d.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:y,answer:m,answers:d.structured,values:d.values??(d.source==="multi"?m.split(", "):[m]),isFreeText:C,source:d.source},bubbles:!0,composed:!0})),ri(Ts,y);let B=st.current.getMessages().find(z=>z.toolCall?.id===y);B?.agentMetadata?.awaitingLocalTool?st.current.resolveAskUserQuestion(B,d.structured??m):st.current.sendMessage(m)},Or=r=>{let a=st.current;if(!a)return;let d=r.getAttribute("data-tool-call-id")??"",m=a.getMessages().find(y=>y.toolCall?.id===d);m&&a.persistAskUserQuestionProgress(m,{answers:Cc(r,m),currentIndex:Xn(r)})},cm=r=>Object.entries(r).map(([a,d])=>`${a}: ${Array.isArray(d)?d.join(", "):d}`).join(" | "),Bd=r=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let a=Xn(r),d=oi(r);if(a>=d-1)return;let m=st.current?.getMessages().find(y=>y.toolCall?.id===r.getAttribute("data-tool-call-id"));m&&(Sc(r,m,o,a+1),Or(r))};Ts.addEventListener("click",r=>{let d=r.target.closest("[data-ask-user-action]");if(!d)return;let m=d.closest("[data-persona-ask-sheet-for]");if(!m)return;let y=d.getAttribute("data-ask-user-action");if(r.preventDefault(),r.stopPropagation(),y==="dismiss"){let C=m.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),ri(Ts,C);let B=st.current?.getMessages().find(z=>z.toolCall?.id===C);B?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(B),st.current?.resolveAskUserQuestion(B,"(dismissed)"));return}if(y==="pick"){let C=d.getAttribute("data-option-label");if(!C)return;let B=m.getAttribute("data-multi-select")==="true",z=Sr(m);if(z&&B){let q=fs(m)[Xn(m)],j=new Set(Array.isArray(q)?q:[]);j.has(C)?j.delete(C):j.add(C),xr(m,Array.from(j)),Or(m);return}if(z){xr(m,C),Or(m),Bd(m);return}if(B){let q=d.getAttribute("aria-pressed")==="true";d.setAttribute("aria-pressed",q?"false":"true"),d.classList.toggle("persona-ask-pill-selected",!q);let j=m.querySelector('[data-ask-user-action="submit-multi"]');j&&(j.disabled=cu(m).length===0);return}ks(m,C,{source:"pick",values:[C]});return}if(y==="submit-multi"){let C=cu(m);if(C.length===0)return;ks(m,C.join(", "),{source:"multi",values:C});return}if(y==="open-free-text"){let C=m.querySelector('[data-ask-free-text-row="true"]');C&&(C.classList.remove("persona-hidden"),C.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(y==="focus-free-text"){m.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let B=m.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!B.trim())return;if(Sr(m)){xr(m,B.trim()),Or(m),Bd(m);return}ks(m,B,{source:"free-text"});return}if(y==="next"||y==="back"){if(!st.current)return;let C=m.getAttribute("data-tool-call-id")??"",B=st.current.getMessages().find(se=>se.toolCall?.id===C);if(!B)return;let q=m.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(q){let se=fs(m)[Xn(m)];(typeof se!="string"||se!==q)&&xr(m,q)}let j=y==="next"?1:-1,X=Xn(m)+j;Sc(m,B,o,X),Or(m);return}if(y==="submit-all"){if(!st.current)return;let C=m.getAttribute("data-tool-call-id")??"",B=st.current.getMessages().find(se=>se.toolCall?.id===C);if(!B)return;let q=m.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";q&&xr(m,q);let j=Cc(m,B);st.current.persistAskUserQuestionProgress(B,{answers:j,currentIndex:Xn(m)});let X=cm(j);ks(m,X||"(submitted)",{source:"submit-all",structured:j});return}if(y==="skip"){if(!st.current)return;let C=m.getAttribute("data-tool-call-id")??"",B=st.current.getMessages().find(ge=>ge.toolCall?.id===C);if(!B)return;let z=Sr(m),q=Xn(m),j=oi(m),X=q>=j-1;if(!z){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),ri(Ts,C),B.agentMetadata?.awaitingLocalTool&&(st.current.markAskUserQuestionResolved(B),st.current.resolveAskUserQuestion(B,"(dismissed)"));return}xr(m,"");let se=m.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),X){let ge=Cc(m,B),Ye=cm(ge);ks(m,Ye||"(skipped)",{source:"submit-all",structured:ge});return}Sc(m,B,o,q+1),Or(m);return}}),Ts.addEventListener("keydown",r=>{if(r.key!=="Enter")return;let d=r.target;if(!d.matches?.('[data-ask-free-text-input="true"]'))return;let m=d.closest("[data-persona-ask-sheet-for]");if(!m)return;r.preventDefault();let y=d.value;if(y.trim()){if(Sr(m)){xr(m,y.trim()),Or(m),Bd(m);return}ks(m,y,{source:"free-text"})}});let dm=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 d=Ts.querySelector("[data-persona-ask-sheet-for]");if(!d||d.getAttribute("data-ask-layout")!=="rows"||d.getAttribute("data-multi-select")==="true")return;let m=Number(r.key),C=d.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[m-1];C&&(r.preventDefault(),C.click())};document.addEventListener("keydown",dm);let ho=null,ht=null,Bi=null,ol=null,rl=()=>{},pm=!1,sl="",il="";function _d(){ol?.(),ol=null}let ow=()=>{let r=Ns&&rs?.isConnected?rs:null,a=r?r.getBoundingClientRect().width:0;return a<=0?200:a+360},um=()=>{if(!ho||!ht)return;let r=t.classList.contains("persona-artifact-welded-split"),a=t.ownerDocument.defaultView??window,d=a.innerWidth<=640;if(!r||t.classList.contains("persona-artifact-narrow-host")||d){ht.style.removeProperty("position"),ht.style.removeProperty("left"),ht.style.removeProperty("top"),ht.style.removeProperty("bottom"),ht.style.removeProperty("width"),ht.style.removeProperty("z-index");return}let m=ho.firstElementChild;if(!m||m===ht)return;let y=10;ht.style.position="absolute",ht.style.top="0",ht.style.bottom="0",ht.style.width=`${y}px`,ht.style.zIndex="5";let C=bg(ho,a),B=m.offsetWidth+C/2-y/2;ht.style.left=`${Math.max(0,B)}px`},al=()=>{},rw=()=>{let r=t.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,d=o.launcher?.mobileBreakpoint??640;return!a||r.innerWidth>d?!1:ue||Rt(o)},ll=()=>!hn(o)||!nl()||t.classList.contains("persona-artifact-narrow-host")||rw()||(t.ownerDocument.defaultView??window).innerWidth<uT?"none":fg(o)?"detached":"welded",ro=()=>{if(!ze||!hn(o))return;$a(t,o),qa(t,o),al();let r=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,a=Me.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",a>0&&a<=r);let d=nl();ze.setVisible(d),ze.update($n),Ro?(ze.setMobileOpen(!1),ze.element.classList.add("persona-hidden"),ze.backdrop?.classList.add("persona-hidden"),oo=!1,Wi=!1):$n.artifacts.length>0&&lm()?(ze.element.classList.remove("persona-hidden"),ze.setMobileOpen(!0)):(ze.setMobileOpen(!1),ze.element.classList.add("persona-hidden"),ze.backdrop?.classList.add("persona-hidden"),oo=!1,Wi=!1);let m=o.features?.artifacts?.layout?.showExpandToggle===!0;if(ze.setExpandToggleVisible(m),ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),ze.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),ze.setTabFade(o.features?.artifacts?.layout?.tabFade),ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!m&&!Wi&&(oo=!1),oo!==pm){let C=ze.element;oo?(sl=C.style.width,il=C.style.maxWidth,C.style.removeProperty("width"),C.style.removeProperty("max-width")):(sl&&(C.style.width=sl),il&&(C.style.maxWidth=il),sl="",il=""),pm=oo}t.classList.toggle("persona-artifact-expanded",oo),ze.setExpanded(oo);let y=ll();y!==Ri&&(Ri=y,_r()),rl()};if(hn(o)){Me.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(pe),ho=a,a.appendChild(r),Me.appendChild(a);let d=y=>{am||ze||(ze=y.createArtifactPane(o,{onSelect:C=>st.current?.selectArtifact(C),onDismiss:()=>{Ro=!0,ro()},onToggleExpand:()=>{let C=!oo,B=$n.selectedId??$n.artifacts[$n.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:B,expanded:C})!==!0&&(oo=C,C||(Wi=!1),ro())}}),ze.element.classList.add("persona-hidden"),a.appendChild(ze.element),ze.backdrop&&Me.appendChild(ze.backdrop),rl(),ro())},m=Jo();m?d(m):(gg(()=>{let y=Jo();y&&d(y)}),gd().catch(()=>{})),rl=()=>{if(!ho||!ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Bi?.(),Bi=null,_d(),ht&&(ht.remove(),ht=null),ze.element.style.removeProperty("width"),ze.element.style.removeProperty("maxWidth");return}if(!ht){let C=k("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");C.setAttribute("role","separator"),C.setAttribute("aria-orientation","vertical"),C.setAttribute("aria-label","Resize artifacts panel"),C.tabIndex=0;let B=t.ownerDocument,z=B.defaultView??window,q=j=>{if(!ze||j.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||z.innerWidth<=640)return;j.preventDefault(),_d();let X=j.clientX,se=ze.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,Ye=lt=>{let Kt=ho.getBoundingClientRect().width,Ot=t.classList.contains("persona-artifact-welded-split"),Tt=bg(ho,z),nn=Ot?0:C.getBoundingClientRect().width||6,Je=se-(lt.clientX-X),on=Xv(Je,Kt,Tt,nn,ge?.resizableMinWidth,ge?.resizableMaxWidth,ow());ze.element.style.width=`${on}px`,ze.element.style.maxWidth="none",um()},it=()=>{B.removeEventListener("pointermove",Ye),B.removeEventListener("pointerup",it),B.removeEventListener("pointercancel",it),ol=null;try{C.releasePointerCapture(j.pointerId)}catch{}};ol=it,B.addEventListener("pointermove",Ye),B.addEventListener("pointerup",it),B.addEventListener("pointercancel",it);try{C.setPointerCapture(j.pointerId)}catch{}};C.addEventListener("pointerdown",q),ht=C,ho.insertBefore(C,ze.element),Bi=()=>{C.removeEventListener("pointerdown",q)}}if(ht){let C=nl();ht.classList.toggle("persona-hidden",!C),um()}},al=()=>{if(!ue||!ze||(o.launcher?.sidebarMode??!1)||Rt(o)&&Jn(o).reveal==="emerge")return;let C=t.ownerDocument.defaultView??window,B=o.launcher?.mobileFullscreen??!0,z=o.launcher?.mobileBreakpoint??640;if(B&&C.innerWidth<=z||!jv(o,ue))return;let q=o.launcher?.width??o.launcherWidth??Yo,j=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";nl()?(Me.style.width=j,Me.style.maxWidth=j):(Me.style.width=q,Me.style.maxWidth=q)},typeof ResizeObserver<"u"&&(Hi=new ResizeObserver(()=>{ro()}),Hi.observe(Me))}else Me.appendChild(pe);xe()&&Vt&&(De.peekBanner&&Vt.appendChild(De.peekBanner),Vt.appendChild(Le)),t.appendChild(Ke),Vt&&t.appendChild(Vt);let Od=()=>{if(xe()){Me.style.width="100%",Me.style.maxWidth="100%";let ve=o.launcher?.composerBar??{},Fe=Ke.dataset.state==="expanded",ut=ve.expandedSize??"anchored";if(!(Fe&&ut!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let jt=o.theme?.components?.panel,_n=di(o),ds=(ps,oc)=>ps==null||ps===""?oc:gn(_n,ps)??ps,fh="1px solid var(--persona-border)",St="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Yp="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=ds(jt?.border,fh),pe.style.borderRadius=ds(jt?.borderRadius,Yp),pe.style.boxShadow=ds(jt?.shadow,St),pe.style.overflow="hidden";return}let r=Rt(o),a=o.launcher?.sidebarMode??!1,d=r||a||(o.launcher?.fullHeight??!1),m=o.launcher?.enabled===!1,y=o.launcher?.detachedPanel===!0,C=o.theme?.components?.panel,B=di(o),z=(ve,Fe)=>ve==null||ve===""?Fe:gn(B,ve)??ve,q=t.ownerDocument.defaultView??window,j=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,se=q.innerWidth<=X,ge=j&&se&&ue,Ye=r&&j&&se,it=o.launcher?.position??"bottom-left",lt=it==="bottom-left"||it==="top-left",Kt=o.launcher?.zIndex??an,Ot="var(--persona-panel-border, 1px solid var(--persona-border))",Tt="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&&!ge&&!Ye;Je?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let on=Je?Ot:a||ge?"none":Ot,Vo=Je?Tt:ge?"none":a?lt?"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))":m?"none":Tt;r&&!ge&&!Je&&(Vo="none",on="none");let So=Je?nn:a||ge?"0":nn,xo=z(C?.border,on),W=z(C?.shadow,Vo),Re=z(C?.borderRadius,So),Be=ll(),fe=Be==="detached",pt=Be==="welded";t.classList.toggle("persona-artifact-detached-split",fe),t.classList.toggle("persona-artifact-welded-split",pt);let $t="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)))))",kt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&hn(o)&&fg(o)&&m&&!r;t.classList.toggle("persona-artifact-chat-flush",kt);let ke=fe||kt?"none":W,qt=fe?Ot:pt?"none":xo,zt=fe?nn:Re;kt&&(qt="none",zt="0");let Qn=C?.borderRadius!=null&&C.borderRadius!=="",He=kt&&!Qn?"0":Re,bt=ne.scrollTop;t.style.cssText="",Ke.style.cssText="",Me.style.cssText="",pe.style.cssText="",ne.style.cssText="",Ms||(Le.style.cssText=""),ee&&(ne.style.display="none"),(d||m)&&(t.style.minWidth="0");let Ao=()=>{if(bt<=0)return;(ne.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ne.scrollTop===bt)return;let Fe=ne.scrollHeight-ne.clientHeight;Fe<=0||(ne.scrollTop=Math.min(bt,Fe))})};if(ge){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 bu=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
|
-
`,ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",Le.style.flexShrink="0",
|
|
70
|
+
`,ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",Le.style.flexShrink="0",Ad(),Ne=!0,Ao();return}let We=o?.launcher?.width??o?.launcherWidth??Yo;if(!a&&!r)m&&d?(Me.style.width="100%",Me.style.maxWidth="100%"):(Me.style.width=We,Me.style.maxWidth=We);else if(r)if(Jn(o).reveal==="emerge"&&!y){let Fe=Jn(o).width;Me.style.width=Fe,Me.style.maxWidth=Fe}else Me.style.width="100%",Me.style.maxWidth="100%";if(al(),Me.style.boxShadow=ke,Me.style.borderRadius=He,fe?Me.style.border="none":pt&&(Me.style.border=xo),pe.style.border=qt,pe.style.borderRadius=zt,pe.style.boxShadow=fe&&!kt?$t:"",kt&&(pe.style.background="transparent",ne.style.background="transparent",Le.style.background="transparent",Le.style.borderTop="none"),pt){let ve=o.features?.artifacts?.layout;tl=ve?.unifiedSplitOuterRadius?.trim()||ve?.paneBorderRadius?.trim()||Re}else tl=null;if(r&&!ge&&!Je&&!fe&&!pt&&C?.border===void 0&&(pe.style.border="none",Jn(o).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.style.borderRight="1px solid var(--persona-border)"),r&&!ge&&pt&&C?.border===void 0&&(Jn(o).side==="right"?Me.style.borderLeft="1px solid var(--persona-border)":Me.style.borderRight="1px solid var(--persona-border)"),d&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",m&&(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%",m&&(Ke.style.overflow="hidden"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",fe||(Me.style.overflow="hidden"),pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.overflow="hidden",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",Le.style.flexShrink="0"),m&&(Je||fe||kt)&&!r&&(kt||(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&&!m&&!r&&(Nn[it]??Nn["bottom-right"]).split(" ").forEach(Fe=>Ke.classList.add(Fe)),a){let ve=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;
|
|
@@ -125,7 +125,7 @@ _Details: ${n.message}_`:o}var bu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
125
125
|
border-top: none !important;
|
|
126
126
|
padding: 8px 16px 12px 16px !important;
|
|
127
127
|
${kt?"background: transparent !important;":""}
|
|
128
|
-
`)}if(!m&&!r){let ve="max-height: -moz-available !important; max-height: stretch !important;",Fe=a?"":"padding-top: 1.25em !important;",ut=a?"":`z-index: ${o.launcher?.zIndex??an} !important;`;Ke.style.cssText+=ve+Fe+ut}xd(),Ao()},Od=()=>{t.style.setProperty("--persona-content-max-width",Tr(o,xe()))},um=!1,gm=()=>{let r=Du(o,xe());xe()&&o.composer?.placement&&o.debug===!0&&!um&&(um=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let a=Xo(o);t.setAttribute("data-persona-composer-placement",r),t.setAttribute("data-persona-conversation-state",Ya),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",a.composerGap??Kc),Ja()},mm=()=>{if(xe())return;let r=Rt(o),a=o.launcher?.sidebarMode??!1;if(r||a||(o.launcher?.fullHeight??!1)||!ue)return;let m=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,C=o.launcher?.mobileBreakpoint??640;if(y&&m.innerWidth<=C)return;let B=m.innerHeight,z=64,q=o.launcher?.heightOffset??0,j=Math.max(200,B-z),X=Math.min(640,j);Me.style.height=`${Math.max(200,X-q)}px`};_d(),La(t,o),$a(t,o),qa(t,o),Od(),gm(),_r=()=>{_d(),mm(),La(t,o),$a(t,o),qa(t,o),Od(),gm(),tl?t.style.setProperty("--persona-artifact-welded-outer-radius",tl):t.style.removeProperty("--persona-artifact-welded-outer-radius"),mt(),Ae()};let be=[];be.push(()=>{im=!0}),be.push(()=>{p.forEach(r=>r()),c.destroy()}),be.push(()=>{document.removeEventListener("keydown",cm)}),be.push(()=>{Pi!==null&&clearTimeout(Pi)});let yo=null,bo=null;be.push(()=>{yo?.(),yo=null,bo?.(),bo=null}),Hi&&be.push(()=>{Hi?.disconnect(),Hi=null}),be.push(()=>{Bi?.(),Bi=null,Bd(),ht&&(ht.remove(),ht=null),ze?.element.style.removeProperty("width"),ze?.element.style.removeProperty("maxWidth"),ze?.destroy()}),It&&be.push(()=>{Va=!0,eo=null,b!==null&&(cancelAnimationFrame(b),b=null),H?.destroy(),H=null,xt?.destroy(),xt=null,ln=null});let Dr=null,fm=()=>{Dr&&(Dr(),Dr=null),o.colorScheme==="auto"&&(Dr=Vc(()=>{La(t,o)}))};fm(),be.push(()=>{Dr&&(Dr(),Dr=null)}),be.push(()=>{M=!0,h?.()}),be.push(()=>{P=!0});let hm=!1;be.push(()=>{hm=!0});let Dd=(r,a)=>{let d=ma(r,a);return d||!zh.includes(r)?d:(lv().then(m=>{if(hm)return;Zp(m.wipe),Zp(m.glyphCycle);let y=ma(r,a);y&&ya(y,t)}).catch(()=>{}),null)},cl=o.features?.streamAnimation;if(cl?.type&&cl.type!=="none"){let r=Dd(cl.type,cl.plugins);r&&ya(r,t),be.push(()=>jh(t))}let Wo=Oa(tr),ym=Oa(bd),bm=Oa(Mi),Nr=[Wo,ym,bm];be.push(()=>{Nr.forEach(r=>r.destroy())});let Fr=null,E,Ur=null,vm=!1,Cm=0,wm=null,Sm=r=>r.reduce((a,d)=>d.role==="user"?a+1:a,0),xm=r=>{for(let a=r.length-1;a>=0;a--)if(wa(r[a]))return r[a].id??null;return null},Am=!1,rw=()=>{Am||o.debug!==!0||(Am=!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".'))},Mm=!1,Em=!1,Tm=(r,a)=>{Mm||o.debug!==!0||!a.enabled||a.expose||vm||Em&&(E.isStreaming()||r.some(wa)||(Mm=!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.")))},Ps=r=>{if(!E)return;let a=r??E.getMessages(),d=j=>{j.render([],E,de,a)},m=j=>{Nr.forEach(X=>{X!==j&&d(X)})};Ur&&(Sm(a)>Cm||xm(a)!==wm)&&(Ur=null);let y=Mr(o);Tm(a,y);let C=y.enabled?wy(a):null,B=Ur??C,z=Ur?"host":"agent";if(B){let j=o.suggestions?.followUps,X=j?.placement??(j?"auto":"composer"),ge=(X==="auto"?xe()?"composer":"after-message":X)==="after-message"?bm:Wo;m(ge),ge.render(B,E,de,a,o.suggestionChipsConfig,{source:z,surface:"followUp",variant:j?.variant??"chip",behavior:j?.behavior??"send",overflow:j?.overflow??"wrap",maxItems:j?.maxItems??4,config:o,plugins:l,submitPrompt:Yl});return}if(a.some(j=>j.role==="user")){Nr.forEach(d);return}let q=o.suggestions?.starters;if(q){let j=mi(Xo(o),a),X=q.placement??"auto",se=X==="auto"?j?"welcome":"composer":X;if(se==="welcome"&&!j){rw(),Nr.forEach(d);return}let ge=se==="welcome"?ym:Wo;m(ge),ge.render(q.items??o.suggestionChips,E,de,a,o.suggestionChipsConfig,{surface:"starter",variant:q.variant??"card",behavior:q.behavior??"send",overflow:q.overflow??"wrap",maxItems:q.maxItems??4,config:o,plugins:l,submitPrompt:Yl});return}m(Wo),Wo.render(o.suggestionChips,E,de,a,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:l,submitPrompt:Yl})},km=()=>{Ur&&(Ur=null,Ps())},sw=r=>{let a=Array.isArray(r)?[...r]:[];if(!a.length){km();return}let d=E?E.getMessages():[];Ur=a,vm=!0,Cm=Sm(d),wm=xm(d),Ps(d)},Ln=!1,Bt=rv(),Is=new Map,$r=new Map,ar=new Map,qr=null,lr=null;function zr(){if(!qr)return;let r=qr;qr=null,lr?.destroy(),lr=null,Bt.delete(r),pe.querySelector(`#wrapper-${r}`)?.removeAttribute("data-preserve-runtime"),E&&qn(Ie,E.getMessages(),Jt)}let jr=0,iw=Ys()!==null,Hn=Nh(),Rn=0,cr=null,wn=!1,dl=!1,dr=0,Ft=null,Vr=null,Nd=!1,Ls=!1,Kr=null,_i=!0,pl=!1,Hs=null,ul=!1,Gr=()=>{ul=!0,dw()},Fd=null,aw=4,Bo=24,lw=80,cw=1e3,_o=null,Pm=()=>{t.setAttribute("data-persona-scrollbar",Cd()),Cd()!=="on-scroll"&&(_o!==null&&clearTimeout(_o),_o=null,ne.removeAttribute("data-persona-scrollbar-visible"))},dw=()=>{Cd()==="on-scroll"&&(ne.setAttribute("data-persona-scrollbar-visible",""),_o!==null&&clearTimeout(_o),_o=setTimeout(()=>{_o=null,gs(ne,Bo)&&ne.removeAttribute("data-persona-scrollbar-visible")},cw))};Pm(),be.push(()=>{_o!==null&&clearTimeout(_o)});let Ud=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Zg=()=>je.active,no();let Im=o.voiceRecognition?.autoResume??!1,Oo=r=>{w.emit("voice:state",{active:je.active,source:r,timestamp:Date.now()})},so=()=>{ae(r=>({...r,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},pw=()=>{if(o.voiceRecognition?.enabled===!1)return;let r=Tg(ie.voiceState),a=!!r.active,d=Number(r.timestamp??0);je.manuallyDeactivated=!!r.manuallyDeactivated,a&&Date.now()-d<aT&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?E.toggleVoice().then(()=>{je.active=E.isVoiceActive(),Oo("restore"),E.isVoiceActive()&&Gs()}):Zl("restore"))},1e3)},uw=()=>E?CC(E.getMessages()).filter(r=>!r.__skipPersist):[],gl=null,Lm=(r,a)=>{typeof console<"u"&&console.error(r,a)},ml=(r,a)=>{let d=()=>{try{let B=r();return!B||typeof B.then!="function"?null:Promise.resolve(B).catch(z=>{Lm(a,z)})}catch(B){return Lm(a,B),null}},m=gl,y=m?m.then(()=>d()??void 0):d();if(!y)return;let C=y.finally(()=>{gl===C&&(gl=null)});gl=C};function Oi(r){if(!G?.save)return;let d={messages:r?CC(r):E?uw():[],metadata:ie,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId,...Qr?{draft:Qr}:{}};ml(()=>G.save(d),"[AgentWidget] Failed to persist state:")}let Qr,fl=()=>!G?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Di=Bb({write:()=>{if(!fl())return;let r=Se.getState(),a=Rb({text:r.text,mentionRefs:r.mentionRefs,contentSegments:Bp(),selectedModelId:r.selectedModelId,activeModeIds:r.activeModeIds,quote:r.quote});JSON.stringify(a)!==JSON.stringify(Qr)&&(Qr=a,Oi())}});function Hm(){fl()&&Di.schedule()}function $d(){Di.flush()}function Rm(r){if(!fl())return;let a=Wb(r,{mentionSourceIds:(o.contextMentions?.sources??[]).map(d=>d.id),modelIds:(o.composer?.models??[]).map(d=>d.id),modes:o.composer?.modes??[]});a&&(Qr=r,de&&!de.value&&(de.value=a.text,de.dispatchEvent(new Event("input",{bubbles:!0})),go()),a.selectedModelId&&(Se.setSelectedModelId(a.selectedModelId),rr?.repaint()),Za(a.activeModeIds??[]),a.quote&&mo(a.quote),Di.cancel())}function hl(){Di.cancel(),Qr&&(Qr=void 0,fl()&&Oi())}let Rs=null,Wm=()=>Ke.querySelector("#persona-scroll-container")||ne,Ws=()=>{Rs!==null&&(cancelAnimationFrame(Rs),Rs=null),wn=!1},Bm=()=>{cr!==null&&(cancelAnimationFrame(cr),cr=null),dl=!1,Ws()},gw=()=>Ln&&zd()&&(In()!=="anchor-top"||_g()),qd=()=>{let r=Ei()||"Jump to latest",a=gw();Wt.toggleAttribute("data-persona-scroll-to-bottom-streaming",a),dr>0?(Rr.textContent=String(dr),Rr.style.display="",Wt.setAttribute("aria-label",`${r} (${dr} new)`)):(Rr.textContent="",Rr.style.display="none",Wt.setAttribute("aria-label",a?`${r} (response streaming below)`:r))},_m=()=>{dr!==0&&(dr=0,qd())},mw=()=>{let r=Ft?.spacerHeight??0;return r<=0?gs(ne,Bo):Cl(r)-ne.scrollTop-ne.clientHeight<=Bo},zd=()=>or()?!Hn.isFollowing():!mw(),jd=()=>!!E&&E.getMessages().length>0,Ut=()=>{if(!$C()||Lr()){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==pe&&pe.appendChild(Wt),Wr();let a=Ko(ne)>0&&zd()&&jd();a?qd():_m(),Wt.style.display=a?"":"none"},Ni=()=>{Hn.pause()&&(Bm(),Ut())},Sn=()=>{Hn.resume(),_m(),Ut()},pr=(r=!1)=>{or()&&jd()&&Hn.isFollowing()&&(!r&&!Ln||(cr!==null&&(cancelAnimationFrame(cr),cr=null),dl=!0,cr=requestAnimationFrame(()=>{cr=null,dl=!1,Hn.isFollowing()&&fw(Wm(),r?220:140)})))},Om=(r,a,d,m=()=>!0)=>{let y=r.scrollTop,C=a(),B=C-y;if(Ws(),Math.abs(B)<1){wn=!0,r.scrollTop=C,Rn=r.scrollTop,wn=!1;return}let z=performance.now();wn=!0;let q=X=>1-Math.pow(1-X,3),j=X=>{if(!m()){Ws();return}let se=a();se!==C&&(C=se,B=C-y);let ge=X-z,Ye=Math.min(ge/d,1),it=q(Ye),lt=y+B*it;r.scrollTop=lt,Rn=r.scrollTop,Ye<1?Rs=requestAnimationFrame(j):(r.scrollTop=C,Rn=r.scrollTop,Rs=null,wn=!1)};Rs=requestAnimationFrame(j)},fw=(r,a=500)=>{let d=Ko(r)-r.scrollTop;if(Math.abs(d)<1){Rn=r.scrollTop;return}if(Math.abs(d)>=lw){Ws(),wn=!0,r.scrollTop=Ko(r),Rn=r.scrollTop,wn=!1;return}Om(r,()=>Ko(r),a,()=>Hn.isFollowing())},yl=()=>{if(!jd()){Ut();return}let r=Wm();wn=!0,r.scrollTop=Ko(r),Rn=r.scrollTop,wn=!1,Ut()},Yr=r=>{let a=0,d=r;for(;d&&d!==ne;)a+=d.offsetTop,d=d.offsetParent;return a},hw=()=>{let r=ne.getRootNode();return(typeof r.getSelection=="function"?r.getSelection():null)??ne.ownerDocument.getSelection()},bl=()=>$h(hw(),ne),Vd=()=>{if(qC()!=="last-user-turn")return!1;let r=E?.getMessages()??[];if(r.length<2)return!1;let a=[...r].reverse().find(C=>C.role==="user");if(!a)return!1;let d=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a.id):a.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=ne.querySelector(`[data-message-id="${d}"]`);if(!m)return!1;let y=Math.min(Math.max(0,Yr(m)-Ti()),Ko(ne));return wn=!0,ne.scrollTop=y,Rn=ne.scrollTop,wn=!1,In()==="follow"&&!gs(ne,Bo)&&Hn.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(ne).paddingBottom)||0,d=0;for(let y of Array.from(ne.children)){if(y===Un||y.offsetHeight===0)continue;let C=Yr(y)+y.offsetHeight;C>d&&(d=C)}let m=ne.scrollHeight-r;return d>0?Math.min(d+a,m):m},yw=()=>{if(!Ft||Ft.spacerHeight<=0)return;let r=Cl(Ft.spacerHeight),a=Math.max(0,Math.round(ne.scrollTop)+ne.clientHeight-r+Bo);a<Ft.spacerHeight&&(vl(a),Ut())},io=()=>{Vr!==null&&(cancelAnimationFrame(Vr),Vr=null),Ws(),Ft=null,Un.style.height="0px",Un.style.display="none"},Dm=r=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Kd=r=>ne.querySelector(`[data-message-id="${Dm(r)}"]`),Nm=r=>{Vr!==null&&cancelAnimationFrame(Vr),Vr=requestAnimationFrame(()=>{Vr=null;let a=Dm(r),d=ne.querySelector(`[data-message-id="${a}"]`);if(!d)return;let m=Yr(d),y=Ft?.spacerHeight??0,C=Cl(y),{targetScrollTop:B,spacerHeight:z}=Jp({anchorOffsetTop:m,topOffset:Ti(),viewportHeight:ne.clientHeight,contentHeight:C,slack:Bo});Ft={initialSpacerHeight:z,contentHeightAtAnchor:C,spacerHeight:z},vl(z),Om(ne,()=>d.isConnected?Math.max(0,Yr(d)-Ti()):B,220)})},xn=()=>{if(In()!=="anchor-top"||!Ft||!Hs)return;let r=Kd(Hs);if(!r)return;Ws();let a=Ft.spacerHeight,d=Cl(a),{targetScrollTop:m,spacerHeight:y}=Jp({anchorOffsetTop:Yr(r),topOffset:Ti(),viewportHeight:ne.clientHeight,contentHeight:d,slack:Bo});Ft={initialSpacerHeight:y,contentHeightAtAnchor:d,spacerHeight:y},vl(y),wn=!0,ne.scrollTop=m,Rn=ne.scrollTop,wn=!1,Ut()},bw=()=>{if(or()){if(!Hn.isFollowing()||gs(ne,1))return;pr(!Ln);return}if(Ft&&Ft.initialSpacerHeight>0){let r=ne.scrollHeight-Ft.spacerHeight,a=qh({initialSpacerHeight:Ft.initialSpacerHeight,contentHeightAtAnchor:Ft.contentHeightAtAnchor,currentContentHeight:r});a!==Ft.spacerHeight&&vl(a)}Ut()},vw=r=>{let a=In();a==="follow"?(Sn(),pr(!0)):a==="anchor-top"&&(_i=!1,pl=!0,ul=!1,Hs=r,Nm(r))},Cw=()=>{if(In()==="anchor-top"){if(pl){_i=!1;return}_i=!0,io(),Sn(),pr(!0)}},ww=96,Sw=r=>{if(Kr===null)return!0;let a=Kd(Kr),d=Kd(r);if(!a||!d)return!0;let m=Yr(d)-Yr(a);return Ti()+m>ne.clientHeight-ww},xw=r=>{if(In()!=="anchor-top"||!pl||ul||bl())return;let a=Kr===null;for(let d of r){if(!a){d.id===Kr&&(a=!0);continue}if(Dh(d)){if(d.id===Hs||!Sw(d.id))return;Hs=d.id,Nm(d.id);return}}},Aw=r=>{let a=new Map;r.forEach(d=>{let m=Ud.get(d.id);a.set(d.id,{streaming:d.streaming,role:d.role}),!m&&d.role==="assistant"&&(w.emit("assistant:message",d),!Ls&&(In()!=="anchor-top"||_g())&&zd()&&(dr+=1,qd(),Ut(),Qa(dr===1?"1 new message below.":`${dr} new messages below.`))),d.role==="assistant"&&m?.streaming&&d.streaming===!1&&w.emit("assistant:complete",d),d.variant==="approval"&&d.approval&&(m?d.approval.status!=="pending"&&w.emit("approval:resolved",{approval:d.approval,decision:d.approval.status}):w.emit("approval:requested",{approval:d.approval,message:d}))}),Ud.clear(),a.forEach((d,m)=>{Ud.set(m,d)})},Fi=(r,a)=>{let d=a==="user"?"user":"assistant",m=o.layout?.messages?.[d],y=m?.width??"content",C=m?.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),C?r.style.setProperty("--persona-message-row-max-width",C):r.style.removeProperty("--persona-message-row-max-width")},Do=(r,a)=>{let d=document.createElement("div");return d.className="persona-flex",d.id=`wrapper-${r}`,d.setAttribute("data-wrapper-id",r),Fi(d,a),d},Mw=(r,a,d)=>{let m=document.createElement("div"),C=(()=>{let W=l.find(Re=>Re.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),B=(W,Re)=>Re==null?!1:typeof Re=="string"?(W.textContent=Re,!0):(W.appendChild(Re),!0),z=new Set,q=new Map,j=new Set,X=l.some(W=>W.renderAskUserQuestion),se=[],ge=[],Ye=o.enableComponentStreaming!==!1,it=o.approval!==!1,lt=[],Kt=o.messageActions,Ot=Kt?.showRegenerate===!0&&Kt.enabled!==!1&&st.current?.isStreaming()!==!0?zy(a):null,Tt=Kt?.showEdit===!0&&Kt.enabled!==!1,nn=Kt?.showQuote===!0&&Kt.enabled!==!1,Je=null,on=o.features?.reasoningDisplay?.completedVisibility==="removed";if(a.forEach(W=>{if(on&&W.variant==="reasoning"&&W.reasoning?.status==="complete")return;if(z.add(W.id),q.set(W.id,W.role),qr===W.id&&lr){let He=Do(W.id,W.role);He.setAttribute("data-persona-message-edit-stub","true"),He.setAttribute("data-preserve-runtime","true"),m.appendChild(He),Je={messageId:W.id,element:lr.element};return}let Re=X&&ms(W),Be=it&&W.variant==="approval"&&!!W.approval,fe=!Re&&W.role==="assistant"&&!W.variant&&Ye&&Eg(W);!Be&&ar.has(W.id)&&(r.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),ar.delete(W.id)),!fe&&$r.has(W.id)&&(r.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),$r.delete(W.id));let pt=ms(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",$t={canRegenerate:Ot===W.id,canEdit:Tt&&uu(W),canQuote:nn&&!W.variant&&(W.content?.trim().length??0)>0},rn=`${$t.canRegenerate?"r":""}${$t.canEdit?"e":""}${$t.canQuote?"q":""}`,sn=ov(W,jr)+pt+`:${rn}`,kt=Re||Be||fe?null:sv(Bt,W.id,sn);if(kt){m.appendChild(kt.cloneNode(!0)),ms(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(j.add(W.toolCall.id),wc(W,o,De.composerOverlay));return}let ke=null,qt=l.find(He=>!!(W.variant==="reasoning"&&He.renderReasoning||W.variant==="tool"&&He.renderToolCall||!W.variant&&He.renderMessage)),zt=o.layout?.messages;if(ms(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){Is.delete(W.id),r.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(wa(W)&&Mr(o).enabled)return;if(ms(W)&&o.features?.askUserQuestion?.enabled!==!1){let He=l.find(bt=>typeof bt.renderAskUserQuestion=="function");if(He&&st.current){let bt=Is.get(W.id),Ao=bt!==sn,ao=null;if(Ao){let{payload:Fe,complete:ut}=ni(W),vr=W.id,jt=()=>st.current?.getMessages().find(_n=>_n.id===vr);ao=He.renderAskUserQuestion({message:W,payload:Fe,complete:ut,resolve:_n=>{let ds=jt();ds&&st.current?.resolveAskUserQuestion(ds,_n)},dismiss:()=>{let _n=jt();_n?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(_n),st.current?.resolveAskUserQuestion(_n,"(dismissed)"))},config:o})}let We=bt!=null;if(Ao&&ao===null&&!We){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(j.add(W.toolCall.id),wc(W,o,De.composerOverlay));return}let ve=Do(W.id,W.role);ve.setAttribute("data-ask-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),m.appendChild(ve),se.push({messageId:W.id,fingerprint:sn,bubble:ao});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(j.add(W.toolCall.id),wc(W,o,De.composerOverlay));return}}else if(Be){let He=F();if(!He){m.appendChild(Do(W.id,W.role));return}let bt=l.find(ve=>typeof ve.renderApproval=="function")??v,ao=ar.get(W.id)!==sn,We=null;if(ao&&bt?.renderApproval){let ve=W.id,Fe=(ut,vr)=>{let jt=st.current?.getMessages().find(_n=>_n.id===ve);jt?.approval&&(jt.approval.toolType==="webmcp"?st.current?.resolveWebMcpApproval(jt.id,ut):st.current?.resolveApproval(jt.approval,ut,vr))};We=bt.renderApproval({message:W,defaultRenderer:()=>He.createApprovalBubble(W,o),config:o,approve:ut=>Fe("approved",ut),deny:ut=>Fe("denied",ut)})}if(ao&&We===null)r.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),ar.delete(W.id),ke=He.createApprovalBubble(W,o);else{let ve=Do(W.id,W.role);ve.setAttribute("data-approval-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),m.appendChild(ve),lt.push({messageId:W.id,fingerprint:sn,bubble:We});return}}else if(qt)if(W.variant==="reasoning"&&W.reasoning&&qt.renderReasoning){if(!Fn)return;ke=qt.renderReasoning({message:W,defaultRenderer:()=>ag(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&qt.renderToolCall){if(!Io)return;ke=qt.renderToolCall({message:W,defaultRenderer:()=>cg(W,o),config:o})}else qt.renderMessage&&(ke=qt.renderMessage({message:W,defaultRenderer:()=>{let He=Yu(W,d,zt,o.messageActions,En,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:$t});return W.role!=="user"&&L(He,W,o,E),He},config:o}));if(!ke&&fe){let He=mC(W);if(He){let bt=$r.get(W.id),Ao=bt!==sn,ao=o.wrapComponentDirectiveInBubble!==!1&&Go.getOptions(He.component)?.bubbleChrome!==!1,We=null;if(Ao){let ve=uC(He,{config:o,message:W,transform:d});if(ve&&He.component==="PersonaArtifactInline"){let Fe=ve.hasAttribute("data-artifact-inline")?ve:ve.querySelector("[data-artifact-inline]"),ut=Fe?.getAttribute("data-artifact-inline")??"",vr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(ut):ut,jt=ut?r.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${vr}"]`)??null:null;Fe&&jt&&jt!==Fe&&Jo()?.hasLiveInlineArtifactBlock(jt)&&(Fe===ve?ve=jt:Fe.replaceWith(jt))}if(ve)if(ao){let Fe=document.createElement("div");if(Fe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Fe.id=`bubble-${W.id}`,Fe.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let ut=document.createElement("div");ut.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ut.innerHTML=d({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Fe.appendChild(ut)}Fe.appendChild(ve),We=Fe}else{let Fe=document.createElement("div");if(Fe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Fe.id=`bubble-${W.id}`,Fe.setAttribute("data-message-id",W.id),Fe.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let ut=document.createElement("div");ut.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ut.innerHTML=d({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Fe.appendChild(ut)}Fe.appendChild(ve),We=Fe}}if(We||bt!=null){let ve=Do(W.id,W.role);ve.setAttribute("data-component-directive-stub","true"),ve.setAttribute("data-preserve-runtime","true"),m.appendChild(ve),ge.push({messageId:W.id,fingerprint:sn,bubble:We});return}}}if(!ke)if(W.variant==="reasoning"&&W.reasoning){if(!Fn)return;ke=ag(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!Io)return;ke=cg(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;let He=F();if(!He)return;ke=He.createApprovalBubble(W,o)}else{let He=o.layout?.messages;He?.renderUserMessage&&W.role==="user"?ke=He.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):He?.renderAssistantMessage&&W.role==="assistant"?ke=He.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):ke=Yu(W,d,He,o.messageActions,En,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:$t}),W.role!=="user"&&ke&&L(ke,W,o,E)}let Qn=Do(W.id,W.role);Qn.appendChild(ke),iv(Bt,W.id,sn,Qn),m.appendChild(Qn)}),De.composerOverlay&&De.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Be=Re.getAttribute("data-persona-ask-sheet-for");Be&&!j.has(Be)&&ri(De.composerOverlay,Be)}),o.features?.toolCallDisplay?.grouped){let W=[],Re=[],Be=o.features.toolCallDisplay.groupedMode==="summary";a.forEach(fe=>{if(fe.variant==="tool"&&fe.toolCall&&Io){Re.push(fe);return}fe.variant==="reasoning"&&(!Fn||on&&fe.reasoning?.status==="complete")||((Re.length>1||Be&&Re.length>0)&&W.push(Re),Re=[])}),(Re.length>1||Be&&Re.length>0)&&W.push(Re),W.forEach(fe=>{let pt=fe.map(zt=>Array.from(m.children).find(Qn=>Qn instanceof HTMLElement&&Qn.getAttribute("data-wrapper-id")===zt.id)).filter(zt=>!!zt);if(pt.length<(Be?1:2))return;let $t=Do(`tool-group-${fe[0].id}`,"assistant");$t.setAttribute("data-persona-tool-group-row","true");let rn=document.createElement("div");rn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",rn.setAttribute("data-persona-tool-group","true");let sn=document.createElement("div");sn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",sn.id=`tool-group-summary-${fe[0].id}`;let kt=`Called ${fe.length} ${fe.length===1?"tool":"tools"}`,ke=o.toolCall?.renderGroupedSummary?.({messages:fe,toolCalls:fe.map(zt=>zt.toolCall).filter(zt=>!!zt),defaultSummary:kt,config:o});B(sn,ke)||(sn.textContent=kt);let qt=document.createElement("div");qt.className="persona-tool-group-stack persona-flex persona-flex-col",qt.id=`tool-group-stack-${fe[0].id}`,qt.setAttribute("data-persona-tool-group-stack","true"),rn.appendChild(sn),Be||rn.appendChild(qt),$t.appendChild(rn),pt[0].before($t),pt.forEach((zt,Qn)=>{if(Be){zt.remove();return}zt.style.setProperty("--persona-message-row-max-width","100%");let He=document.createElement("div");He.className="persona-tool-group-item persona-relative",He.setAttribute("data-persona-tool-group-item","true"),Qn<pt.length-1&&He.setAttribute("data-persona-tool-group-connector","true"),He.appendChild(zt),qt.appendChild(He)})})}av(Bt,z);let Vo=a.some(W=>W.role==="assistant"&&W.streaming),So=a[a.length-1],xo=So?.role==="assistant"&&!So.streaming&&So.variant!=="approval";if(Ln&&a.some(W=>W.role==="user")&&!Vo&&!xo){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:Fa},Re=l.find(fe=>fe.renderLoadingIndicator),Be=null;if(Re?.renderLoadingIndicator&&(Be=Re.renderLoadingIndicator(W)),Be===null&&o.loadingIndicator?.render&&(Be=o.loadingIndicator.render(W)),Be===null&&(Be=Fa()),Be){let fe=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1,$t=o.layout?.messages?.layout??"bubble";fe.className=pt?Ua("assistant",$t).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),fe.setAttribute("data-typing-indicator","true"),pt&&(fe.style.color="var(--persona-message-assistant-text, var(--persona-text))",$t!=="flat"&&(fe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),fe.appendChild(Be);let rn=Do("typing-indicator","assistant");rn.appendChild(fe),m.appendChild(rn)}}if(!Ln&&a.length>0){let W=a[a.length-1],Re={config:o,lastMessage:W,messageCount:a.length},Be=l.find(pt=>pt.renderIdleIndicator),fe=null;if(Be?.renderIdleIndicator&&(fe=Be.renderIdleIndicator(Re)),fe===null&&o.loadingIndicator?.renderIdle&&(fe=o.loadingIndicator.renderIdle(Re)),fe){let pt=document.createElement("div"),$t=o.loadingIndicator?.showBubble!==!1;pt.className=$t?["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(" "),pt.setAttribute("data-idle-indicator","true"),pt.appendChild(fe);let rn=Do("idle-indicator","assistant");rn.appendChild(pt),m.appendChild(rn)}}if(ny(m),Xc(r,m),tu(r),Je){let{messageId:W,element:Re}=Je,Be=r.querySelector(`#wrapper-${W}`);Be&&Re.parentElement!==Be&&(Fi(Be,q.get(W)??"user"),Be.replaceChildren(Re))}if(se.length>0)for(let{messageId:W,fingerprint:Re,bubble:Be}of se){let fe=r.querySelector(`#wrapper-${W}`);fe&&(Fi(fe,q.get(W)??"assistant"),Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Re),Is.set(W,Re)))}if(Is.size>0)for(let W of Is.keys())z.has(W)||Is.delete(W);if(ge.length>0)for(let{messageId:W,fingerprint:Re,bubble:Be}of ge){let fe=r.querySelector(`#wrapper-${W}`);fe&&(Fi(fe,q.get(W)??"assistant"),Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Re),$r.set(W,Re)))}if($r.size>0)for(let W of $r.keys())z.has(W)||$r.delete(W);if(lt.length>0)for(let{messageId:W,fingerprint:Re,bubble:Be}of lt){let fe=r.querySelector(`#wrapper-${W}`);fe&&(Fi(fe,q.get(W)??"assistant"),Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Re),ar.set(W,Re)))}if(ar.size>0)for(let W of ar.keys())z.has(W)||ar.delete(W)},Gd=!1,wl=()=>{Gd||(Gd=!0,yh().catch(()=>{Gd=!1}))},qn=(r,a,d)=>{a.length>0&&wl(),Mw(r,a,d),sm()},Ui=null,Ew=()=>{if(Ui)return;let r=d=>{let m=d.composedPath();m.includes(Ke)||Vt&&m.includes(Vt)||at(!1,"user")};Ui=r,(t.ownerDocument??document).addEventListener("pointerdown",r,!0)},Fm=()=>{if(!Ui)return;(t.ownerDocument??document).removeEventListener("pointerdown",Ui,!0),Ui=null};be.push(()=>Fm());let $i=null,Tw=()=>{if($i)return;let r=d=>{d.key==="Escape"&&(d.isComposing||at(!1,"user"))};$i=r,(t.ownerDocument??document).addEventListener("keydown",r,!0)},Um=()=>{if(!$i)return;(t.ownerDocument??document).removeEventListener("keydown",$i,!0),$i=null};be.push(()=>Um());let qi=!1,$m=new Set,kw=()=>{let r=o.launcher?.composerBar?.peek?.streamAnimation;return r||o.features?.streamAnimation},Bs=()=>{if(!xe())return;let r=De.peekBanner,a=De.peekTextNode;if(!r||!a)return;if(ye){r.classList.remove("persona-pill-peek--visible");return}let d=E?.getMessages()??[],m;for(let Ot=d.length-1;Ot>=0;Ot--){let Tt=d[Ot];if(Tt.role==="assistant"&&Tt.content){m=Tt;break}}if(!m){r.classList.remove("persona-pill-peek--visible");return}let y=m.content,C=!!m.streaming,B=kw(),z=hc(B),q=z.type!=="none"?Dd(z.type,B?.plugins):null,j=q?.isAnimating?.(m)===!0,X=q!==null&&(C||j);X&&q&&!$m.has(q.name)&&(ya(q,t),$m.add(q.name));let se=X&&q?.containerClass?q.containerClass:null,ge=a.dataset.personaPeekStreamClass??null;ge&&ge!==se&&(a.classList.remove(ge),delete a.dataset.personaPeekStreamClass),se&&ge!==se&&(a.classList.add(se),a.dataset.personaPeekStreamClass=se),X?(a.style.setProperty("--persona-stream-step",`${z.speed}ms`),a.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(a.style.removeProperty("--persona-stream-step"),a.style.removeProperty("--persona-stream-duration"));let Ye=X?yc(y,z.buffer,q,m,C):y;if(X&&z.placeholder==="skeleton"&&C&&(!Ye||!Ye.trim())){let Ot=document.createElement("div"),Tt=ha();Tt.classList.add("persona-pill-peek__skeleton"),Ot.appendChild(Tt),Xc(a,Ot)}else{let Ot=Math.max(0,Ye.length-100),Tt=Ye.length>100?Ye.slice(-100):Ye,nn=ac(Tt);if(!X||!q){let Je=Ye.length>100?`\u2026${Tt}`:Tt;a.textContent!==Je&&(a.textContent=Je)}else{let Je=nn;(q.wrap==="char"||q.wrap==="word")&&(Je=fa(nn,q.wrap,`peek-${m.id}`,{skipTags:q.skipTags,startIndex:Ot}));let on=document.createElement("div");if(on.innerHTML=Je,q.useCaret&&Tt.length>0){let Vo=bc(),So=on.querySelectorAll(".persona-stream-char, .persona-stream-word"),xo=So[So.length-1];xo?.parentNode?xo.parentNode.insertBefore(Vo,xo.nextSibling):on.appendChild(Vo)}Xc(a,on),q.onAfterRender?.({container:a,bubble:r,messageId:m.id,message:m,speed:z.speed,duration:z.duration})}}let Kt=Ln||qi;r.classList.toggle("persona-pill-peek--visible",Kt)};if(xe()){let r=De.peekBanner;if(r){let m=y=>{y.preventDefault(),y.stopPropagation(),at(!0,"user")};r.addEventListener("pointerdown",m),be.push(()=>{r.removeEventListener("pointerdown",m)})}let a=()=>{qi||(qi=!0,Bs())},d=()=>{qi&&(qi=!1,Bs())};Me.addEventListener("pointerenter",a),Me.addEventListener("pointerleave",d),be.push(()=>{Me.removeEventListener("pointerenter",a),Me.removeEventListener("pointerleave",d)}),Vt&&(Vt.addEventListener("pointerenter",a),Vt.addEventListener("pointerleave",d),be.push(()=>{Vt.removeEventListener("pointerenter",a),Vt.removeEventListener("pointerleave",d)}))}let Pw=r=>{let a=o.launcher?.composerBar??{},d=a.expandedSize??"anchored",m=a.bottomOffset??"16px",y=a.collapsedMaxWidth,C=a.expandedMaxWidth??"880px",B=a.expandedTopOffset??"5vh",z=a.modalMaxWidth??"880px",q=a.modalMaxHeight??"min(90vh, 800px)",j="calc(100vw - 32px)",X="var(--persona-pill-area-height, 80px)",se=Ke.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",Vt){let ge=Vt.style;ge.bottom=m,ge.width=y??""}if(r&&d!=="fullscreen"){if(d==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=z,se.maxWidth=j,se.maxHeight=q,se.height=q;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${m} + ${X})`,se.top=B,se.width=C,se.maxWidth=j}},zi=()=>{if(ye&&wl(),!Oe())return;if(xe()){let j=(o.launcher?.composerBar??{}).expandedSize??"anchored",X=ye?"expanded":"collapsed";Ke.dataset.state=X,Ke.dataset.expandedSize=j,Vt&&(Vt.dataset.state=X,Vt.dataset.expandedSize=j),Ke.style.removeProperty("display"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Pw(ye),pe.style.display=ye?"flex":"none",_r(),ye?(Ew(),Tw()):(Fm(),Um()),Bs();return}let r=Rt(o),a=t.ownerDocument.defaultView??window,d=o.launcher?.mobileBreakpoint??640,m=o.launcher?.mobileFullscreen??!0,y=a.innerWidth<=d,C=m&&y&&ue,B=Jn(o).reveal;ye?(Ke.style.removeProperty("display"),Ke.style.display=r?"flex":"",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-95","persona-opacity-0"),Me.classList.add("persona-scale-100","persona-opacity-100"),Mt?(Mt.setPanelOpen(!0),Mt.element.style.display="none"):pn&&(pn.style.display="none")):(r?r&&(B==="overlay"||B==="push")&&!C?(Ke.style.removeProperty("display"),Ke.style.display="flex",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.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"),Me.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"),Me.classList.remove("persona-scale-100","persona-opacity-100"),Me.classList.add("persona-scale-95","persona-opacity-0")),Mt?(Mt.setPanelOpen(!1),Mt.element.style.display=r?"none":""):pn&&(pn.style.display=r?"none":""))},at=(r,a="user")=>{if(!Oe()||ye===r)return;let d=ye;ye=r,zi();let m=(()=>{let C=o.launcher?.sidebarMode??!1,B=t.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640,j=B.innerWidth<=q,X=Rt(o)&&z&&j,se=xe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return C||z&&j&&ue||X||se})();if(ye&&m){if(!yo){let C=t.getRootNode(),B=C instanceof ShadowRoot?C.host:t.closest(".persona-host");B&&(yo=Uu(B,o.launcher?.zIndex??an))}bo||(bo=$u(t.ownerDocument))}else ye||(yo?.(),yo=null,bo?.(),bo=null);ye&&(la(),Vd()||(In()==="follow"?pr(!0):yl()));let y={open:ye,source:a,timestamp:Date.now()};ye&&!d?w.emit("widget:opened",y):!ye&&d&&w.emit("widget:closed",y),w.emit("widget:state",{open:ye,launcherEnabled:ue,voiceActive:je.active,streaming:E.isStreaming()})},ur={inputDisabled:!1,sendDisabled:!1},gr=()=>ur.inputDisabled,Xr=()=>ur.inputDisabled||ur.sendDisabled,Iw=()=>(ur.inputDisabled?ur.inputReason:void 0)??(ur.sendDisabled?ur.sendReason:void 0);function Qd(){if(!Ee)return;if(Se.getState().phase==="streaming"){Ee.disabled=!1;return}let r=Xe?!Xe.isReady():!1;Ee.disabled=Xr()||r}function Sl(){if(!uo)return;let r=Se.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 Lw(){let r=Iw();if(xe()){let a=to??Le;r?a.setAttribute("title",r):a.removeAttribute("title"),Le.toggleAttribute(wi,!!r);return}if(r){ot.setAttribute("role","status"),ot.setAttribute("aria-live","polite"),ot.setAttribute(wi,""),ot.textContent=r;return}if(ot.hasAttribute(wi)&&(ot.removeAttribute("role"),ot.removeAttribute("aria-live"),ot.removeAttribute(wi),u)){let a=E.getStatus();tn(ot,cn(a),o.statusIndicator??{},a)}}function Yd(){let r=Mu(o.composer?.inputDisabled),a=Mu(o.composer?.sendDisabled);ur={inputDisabled:r.disabled,inputReason:r.reason,sendDisabled:a.disabled,sendReason:a.reason},Se.setInputDisabled(r.disabled),Se.setSendDisabled(a.disabled);let d=Se.getState().phase==="streaming",m=r.disabled,y=d||m;de&&(de instanceof HTMLTextAreaElement?de.disabled=m:de.setAttribute("contenteditable",m?"false":"true"),de.setAttribute("aria-disabled",m?"true":"false")),wt&&(wt.disabled=m),ft&&(ft.disabled=m);for(let C of Ht?.affordanceButtons??[])C.querySelectorAll("button").forEach(B=>{B.disabled=m});re&&(re.disabled=y),Nr.forEach(C=>{C.elements.forEach(B=>{B.toggleAttribute("data-disabled",y),B instanceof HTMLButtonElement||B.setAttribute("aria-disabled",y?"true":"false")}),C.buttons.forEach(B=>{B.disabled=y})}),tp.forEach(C=>{C.toggleAttribute("data-disabled",y),C instanceof HTMLButtonElement?C.disabled=y:C.setAttribute("aria-disabled",y?"true":"false"),C.querySelectorAll("button").forEach(B=>{B.disabled=y})}),Le.dataset.personaComposerStreaming=d?"true":"false",Le.dataset.personaComposerInputDisabled=m?"true":"false",Le.dataset.personaComposerSendDisabled=Xr()?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(C=>{(C instanceof HTMLButtonElement||C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement||C instanceof HTMLSelectElement)&&(C.disabled=d)}),Qd(),Lw()}let ji=r=>{Se.setStreaming(r),Wg(r?"stop":"send"),Yd()},Jr=()=>{je.active||de&&de.focus()};w.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Jr(),200)});let Zr=null,Vi=!1,Xd=!bn.hidden,mr=null,Jd=!oe,xl=null;be.push(()=>{xl?.cancel(),xl=null});let Hw=r=>{let a=Ev(r);if(a===Ya)return;Ya=a,t.setAttribute("data-persona-conversation-state",a);let d=Sd();Ja(),Jd&&(xl?.cancel(),xl=Av(Le,a==="active"?d:Sd(),a==="active"?"drop":"rise")),xn()},qm=null,zm,jm=null,_s=null,Zd=!1,Ki=r=>{let a=Xo(o),d=`${a.variant}|${a.dismiss}|${a.anchor??"bottom"}|${a.align??""}|${a.iconPlacement}|${a.kicker??""}|${a.title}|${a.subtitle}`;(d!==qm||a.icon!==zm)&&(qm=d,zm=a.icon,od({host:bn,iconHolder:BC,kicker:_C,title:OC,subtitle:DC,starterSuggestions:bd},a));let m=a.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${a.message}`;m!==jm&&(jm=m,rd(kn,a.message,o));let y=r??(E?E.getMessages():o.initialMessages);Hw(y);let C=Vi,B=!C&&mi(a,y),z=B!==Xd;if(Xd=B,_s){mr?.cancel(),mr=null,C!==Zd&&(Zd=C,C?Zu(ne,bn,null):Ju(ne,bn,_s)),gi(ne,bn,!C);return}if(z&&!B&&!C&&a.dismiss==="on-first-message"&&Jd){mr=xv(bn,j=>{mr===j&&(mr=null),!Xd&&!_s&&(gi(ne,bn,!1),xn()),j?.cancel()});return}if(mr){if(!B&&!C)return;mr.cancel(),mr=null}let q=!bn.hidden;gi(ne,bn,B),!B&&q&&xn()},ep=[],tp=[],np=!1,Vm=null,Km,Gm=()=>{tp.length=0;let r=ep.splice(0,ep.length);for(let a of r)try{a()}catch(d){console.warn("[persona] renderWelcome cleanup threw",d)}};be.push(Gm);let Rw=(r,a)=>{let d=zu(r,a);if(!d)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),k("span");let m=o.suggestions?.starters,y=ju({item:{...d,behavior:d.behavior??m?.behavior??"send"},index:a,surface:"starter",source:"config",variant:m?.variant??"card",streaming:u?E.isStreaming():!1,config:o,plugins:l,chipsConfig:o.suggestionChipsConfig,session:E,getTextarea:()=>de,eventTarget:bn,submitPrompt:Yl});return tp.push(y),y},op=()=>{if(np)return;np=!0;let r=Xo(o);Vm=`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`,Km=r.icon;try{Gm(),Zu(ne,bn,_s),_s=null,Zd=!1;let a=E?E.getMessages():o.initialMessages,d=mi(r,a),m=0,y=null;for(let C of l)if(C.renderWelcome&&(y=C.renderWelcome({config:r,variant:r.variant,visible:d,defaultRenderer:()=>bn,sendMessage:B=>{if(!E||E.isStreaming())return;let z=B.trim();z&&E.sendMessage(z)},requestRender:()=>op(),renderStarter:B=>Rw(B,m++),storage:g(C.id),onCleanup:B=>{ep.push(B)}}),y))break;y&&y!==bn&&(_s=y,Ju(ne,bn,y))}finally{np=!1}Ki()},Ww=()=>{let r=Xo(o);`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`===Vm&&r.icon===Km||op()},Al=()=>{Ki(),Ms||(de.placeholder=kb(Se.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!E?.isStreaming()&&(Ee.textContent=o.copy?.sendButtonLabel??"Send")),de.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',de.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Bw=!!o.setStoredConversationId,Gi=r=>ae(a=>{let d={...a};return delete d[r],d}),Ml=r=>{let a=ie[r];return typeof a=="string"?a:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Ml("sessionId"),setStoredSessionId:r=>{ae(a=>({...a,sessionId:r}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Gi("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ml("conversationId")),setStoredConversationId:o.setStoredConversationId??(r=>{ae(a=>({...a,conversationId:r}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Gi("conversationId"))});let Qm=()=>o.features?.history?.enabled===!0?o.clientToken??null:null,Ym=r=>iC(r,po(),o.persistState===!1),Xm=Qm(),No=Xm?Ym(Xm):null,es={...No?{visitorStore:No}:{},historyBootstrapReady:O,getStoredMessageCursor:()=>Ml("historyMessageCursor"),setStoredMessageCursor:r=>{if(r===null){Gi("historyMessageCursor");return}ae(a=>({...a,historyMessageCursor:r}))},getPendingDisplayProjections:()=>{let r=ie.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(d=>typeof d=="string")}},setPendingDisplayProjections:r=>{if(!r){Gi("pendingDisplayProjections");return}ae(a=>({...a,pendingDisplayProjections:r}))},...Bw?{}:{getStoredConversationRevision:()=>Ml("conversationRevision"),setStoredConversationRevision:r=>{if(r===null){Gi("conversationRevision");return}ae(a=>({...a,conversationRevision:r}))}}},_w=()=>{let r=Qm();if(r&&No?.matches(r,po(),o.persistState===!1)||!r&&!No)return;No?.destroy(),No=r?Ym(r):null;let a={...es};No?a.visitorStore=No:delete a.visitorStore,es=a,E.setHistoryInternals(es)},ts=null,Ow=()=>{ts==null&&(ts=setInterval(()=>{let r=Ie.querySelectorAll("[data-tool-elapsed]");if(r.length===0){clearInterval(ts),ts=null;return}let a=Date.now();r.forEach(d=>{let m=Number(d.getAttribute("data-tool-elapsed"));m&&(d.textContent=Mh(a-m))})},100))},rp=(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,z)=>rp(B,a[z]));let d=r,m=a,y=Object.keys(d),C=Object.keys(m);return y.length===C.length&&y.every(B=>Object.prototype.hasOwnProperty.call(m,B)&&rp(d[B],m[B]))},Jm=r=>{let{content:a,rawContent:d,llmContent:m,...y}=r;return y},sp=r=>r.role==="assistant"&&r.streaming===!0&&!r.variant&&!r.toolCall&&!r.tools&&!r.approval&&!r.reasoning&&!r.contentParts&&!r.stopReason&&!Eg(r),Dw=(r,a,d)=>{if(r.length!==a.length)return!1;let m=r[d.index],y=a[d.index];return!m||!y||m.id!==d.id||y.id!==d.id?!1:(!Object.is(m.content,y.content)||!Object.is(m.rawContent,y.rawContent)||!Object.is(m.llmContent,y.llmContent))&&sp(m)&&sp(y)&&rp(Jm(m),Jm(y))},ip=null,Os=null,ns=null,Fo=null,El=r=>{ip=r;let a,d;Os=null;for(let y=r.length-1;y>=0;y-=1){let C=r[y];if(!a&&C.role==="user"&&(a=C),!d&&C.role==="assistant"&&(d=C),!Os&&sp(C)&&(Os={index:y,id:C.id}),a&&d&&Os)break}qn(Ie,r,Jt),Jo()?.updateInlineArtifactBlocks(Ie,$n.artifacts,{suppressTransition:Ln}),Ow(),Ki(r),Ps(r),pr(!Ln),Aw(r),r.length===0&&(io(),_i=!0,pl=!1,Hs=null,ul=!1),!Nd||Ls?(Nd=!0,Kr=a?.id??null,Fd=d?.id??null):a&&a.id!==Kr?(Kr=a.id,vw(a.id)):d&&d.id!==Fd&&Cw(),d&&(Fd=d.id),xw(r);let m=je.lastUserMessageId;a&&a.id!==m&&(je.lastUserMessageId=a.id,w.emit("user:message",a)),je.lastUserMessageWasVoice=!!a?.viaVoice,Oi(r),Bs()},ap=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null);let r=ns;ns=null,r&&El(r)},Zm=()=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=null,ns=null},Nw=r=>{let a=ns??ip;if(Ln&&a&&Os&&Dw(a,r,Os)){ns=r,Fo===null&&(Fo=requestAnimationFrame(()=>{Fo=null;let d=ns;ns=null,d&&El(d)}));return}if(r.length===0){Zm(),El(r);return}ap(),El(r)};E=new Pc(o,{onMessagesChanged(r){Nw(r)},onStatusChanged(r){let a=o.statusIndicator??{};tn(ot,(m=>m==="idle"?a.idleText??Dt.idle:m==="connecting"?a.connectingText??Dt.connecting:m==="connected"?a.connectedText??Dt.connected:m==="error"?a.errorText??Dt.error:m==="paused"?a.pausedText??Dt.paused:m==="resuming"?a.resumingText??Dt.resuming:Dt[m])(r),a,r),Ct()},onStreamingChanged(r){r||(E?.getMessages().length===0?Zm():ap()),Ln=r,ji(r),Ct(),E&&qn(Ie,E.getMessages(),Jt),r||(pr(!0),yw(),Em=!0,E&&Tm(E.getMessages(),Mr(o))),Ut(),Qa(r?"Responding\u2026":"Response complete."),Bs()},onVoiceStatusChanged(r){if(w.emit("voice:status",{status:r,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(r){case"listening":jo(),Gs();break;case"processing":jo(),US();break;case"speaking":jo(),$S();break;default:r==="idle"&&E.isBargeInActive()?(jo(),Gs(),re?.setAttribute("aria-label","End voice session")):(je.active=!1,jo(),Oo("system"),so());break}},onArtifactsState(r){$n=r,r.artifacts.length===0&&(Es=!1),Jo()?.updateInlineArtifactBlocks(Ie,r.artifacts,{suppressTransition:Ln}),ro(),Oi()},onHistoryStateChanged(r){qe(r)},onHistoryNotice(r){Lt(r)},onReconnect(r){let{executionId:a,lastEventId:d}=r.handle;r.phase==="paused"?w.emit("stream:paused",{executionId:a,after:d}):r.phase==="resuming"?w.emit("stream:resuming",{executionId:a,after:d,attempt:r.attempt??1}):w.emit("stream:resumed",{executionId:a,after:d})}},es),st.current=E,be.push(()=>E.cancel()),be.push(()=>{E.destroy(),No?.destroy()});let lp=null;if(E.onReadAloudChange((r,a)=>{om=r,rm=a,sm();let d=r??lp;r&&(lp=r);let m=d?E.getMessages().find(y=>y.id===d)??null:null;w.emit("message:read-aloud",{messageId:d,message:m,state:a,timestamp:Date.now()}),a==="idle"&&(lp=null)}),u=!0,Nd=!0,o.voiceRecognition?.provider?.type==="runtype")try{E.setupVoice()}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",r)}let Fw=720,Uw=250,Qe=eu(o.features?.history?.copy),Wn=null,cp=!1,rt=null,Tl=null,kl="conversation",dp=null,dn=null,vo=null,Pl=E.getHistoryState(),pp=null,Qi=0,up=null,Il=null,Ll=null,gp=`persona-history-${Math.random().toString(36).slice(2,8)}`,mp=()=>o.features?.history?.enabled===!0,Co=()=>mp()&&!!Wn&&!cp,ef=()=>{let r=E.getStatus();return Ln||r==="paused"||r==="resuming"},fp=()=>{let r=o.features?.history?.scope;if(r)return r;let a=o.getIdentityProof?"verified-user":"browser",d=Wn?.capabilities.scopes;return!d||d.includes(a)?a:d[0]??a},Ds=()=>Tl?.scope??fp(),tf=()=>E.getClientSession()?.targetId??null,nf=r=>`${r.state}:${"reason"in r?r.reason:""}`,$w=r=>{let a=nf(r);a!==pp&&(pp=a,w.emit("history:identityStatusChanged",{status:r,timestamp:Date.now()}))},Hl=r=>{r&&(Lo.textContent="",Lo.textContent=r)},of=null,rf=null,qw=()=>{if(!mp())return null;let r=dC();if(r)return r();let a=o.features?.history?.provider;return a?typeof a!="function"?a:(of!==a&&(of=a,rf=a()),rf):E.isClientTokenMode()?pC({client:E.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:d=>E.bindActivatedSession(d),getClient:()=>E.getClient()}):null},sf=()=>{Il?.(),Il=null,Ll?.(),Ll=null,cp=!1,Wn=qw();let r={...es};Wn?r.historyProvider=Wn:delete r.historyProvider,es=r,E.setHistoryInternals(es),Wn&&(Il=Wn.subscribeAvailability?.(a=>{cp=!a,a||An({restoreFocus:!1}),hr()})??null,Ll=Wn.subscribeIdentityStatus(a=>$w(a)),pp=nf(Wn.getIdentityStatus()))},hp=()=>{let r=o.features?.history?.presentation??"panel";if(r==="panel"||r==="auto"&&!(!ue||Rt(o)))return"panel";let a=ho??pe;return(a.getBoundingClientRect().width||a.clientWidth)>=Fw?"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",Bn=null,fr=null,os=null,Yi=null,yp=null,af="",lf=()=>Te===yp?af:o.layout?.showHeader===!1?"none":"",zw=()=>le==="panel"&&!!os&&Yi===os.element&&o.layout?.showHeader!==!1&&lf()!=="none",jw=()=>{for(let r of Array.from(Te.children))r!==Bn&&r.setAttribute(Rl,"")},Vw=()=>{for(let r of Array.from(pe.querySelectorAll(`[${Rl}]`)))r.removeAttribute(Rl)},Kw=()=>{let r=os;if(!r)return;if(Array.from(Te.children).some(m=>m!==Bn&&!m.hasAttribute(Rl))){fr&&fr!==Te&&(fr.style.removeProperty("min-height"),fr=null);let m=Te.offsetHeight;m>0&&(Te.style.minHeight=`${m}px`,fr=Te)}Bn||(Bn=k("div","persona-history-header-host")),r.setHeaderPlacement("external");let d=r.getHeaderElement();d.parentNode!==Bn&&Bn.replaceChildren(d),Bn.parentNode!==Te&&Te.appendChild(Bn),jw()},cf=()=>{fr&&(fr.style.removeProperty("min-height"),fr=null),Bn&&(os?.setHeaderPlacement("inline"),Bn.remove(),Bn=null,Vw())},Wl=null,bp=()=>{if(Wl){if(ne.style.display="none",zn(ne,!0),Le.hidden=!0,zn(Le,!0),zw()){Kw(),Te.style.display=lf(),zn(Te,!1);return}cf(),Te.style.display="none",zn(Te,!0)}};Ae=bp;let Gw=r=>{let a=ne.style.display,d=Le.hidden,m=Le,y=Te,C=Te.style.display;yp=y,af=C,Wl=()=>{Wl=null,cf(),yp=null,ne.style.display=a,zn(ne,!1),m.hidden=d,zn(m,!1),Le!==m&&(Le.hidden=!1,zn(Le,!1)),y.style.display=C,zn(y,!1),Te!==y&&(Te.style.display=o.layout?.showHeader===!1?"none":"",zn(Te,!1))},Le.parentNode?.insertBefore(r,Le),bp()},Ns=null,rs=null,Xi=null,Fs=null,df=()=>[Te,De.closeButtonWrapper,De.clearChatButtonWrapper,ne,Le],Qw=52,Bl=()=>o.features?.history?.rail?.collapsible!==!1,Us=()=>o.features?.history?.rail?.side==="right"?"right":"left",vp=200,Cp=400,wp=r=>Math.min(Cp,Math.max(vp,Math.round(r))),Yw=()=>o.features?.history?.rail?.resizable===!0,Ji,Xw=()=>{if(Ji===void 0&&(Ji=null,o.persistState!==!1))try{let r=Number(window.localStorage.getItem(`${po()}rail-width`));r&&(Ji=r)}catch{}return Ji},Zi=()=>wp(Xw()??o.features?.history?.rail?.width??260),Jw=r=>{if(Ji=r,o.persistState!==!1)try{window.localStorage.setItem(`${po()}rail-width`,String(r))}catch{}},_l=()=>Bl()&&o.features?.history?.rail?.collapsedBehavior==="overlay",_t=!1,pf=r=>{let a=k("img");return a.src=r,a.alt="",a.setAttribute("aria-hidden","true"),a},Zw=()=>{let r=o.features?.history?.rail?.brand;if(!r)return;let a=!1,d;return m=>{if(r.render)try{return r.render({collapsed:m})??null}catch(y){return a||(a=!0,console.warn("[persona] history rail brand threw",y)),null}return d===void 0&&(r.iconUrl?d=pf(r.iconUrl):d=r.icon?he(r.icon,20):null),d?d.cloneNode(!0):null}},eS=()=>o.features?.history?.rail?.sections?.map(r=>{let a=!1,d=m=>{a||(a=!0,console.warn("[persona] history rail section threw",r.id,m))};return{id:r.id,title:r.title,placement:r.placement??"above-conversations",items:r.items.map(m=>{let y;return{id:m.id,label:m.label,badge:m.badge,iconNode:()=>{if(y!==void 0)return y;try{m.renderIcon?y=m.renderIcon()??null:m.iconUrl?y=pf(m.iconUrl):y=m.icon?he(m.icon,20):null}catch(C){d(C),y=null}return y},onSelect:()=>{try{m.onSelect()}catch(C){d(C)}}}})}})??[],tS=r=>{let a=eS();for(let d of r)a.some(m=>m.id===d.id)?console.warn("[persona] duplicate history rail section id",d.id):a.push(d);return a.length?a:void 0},ea=null,uf=()=>`${po()}rail-collapsed`,Sp=()=>{if(ea===null&&(ea=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let r=window.localStorage.getItem(uf());r&&(ea=r==="1")}catch{}return ea},xp=r=>{if(ea=r,o.persistState!==!1)try{window.localStorage.setItem(uf(),r?"1":"0")}catch{}},ta=()=>le==="rail"&&Bl()&&!_l()&&Sp(),Ap=()=>{},gf=()=>{if(_l()){Ap();return}xp(!Sp()),rt?.view.setCollapsed(ta()),mt(),xn()},Mp=()=>{let r=o.features?.history?.rail?.collapseShortcut;return!r||!Qc(r)?null:{combo:r,hint:Yc(r),aria:Ra(r)}},mf=()=>{p.forEach(a=>a()),p=[];let r=Mp();r&&p.push(c.register({id:"history-rail-collapse",combo:r.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>te&&le==="rail"&&Bl()||qs(),run:()=>_l()?Ap():gf()}));for(let a of o.layout?.header?.trailingActions??[])a.shortcut&&p.push(c.register({id:`header-action-${a.id}`,combo:a.shortcut,run:()=>{let d=t.querySelector(`[data-persona-header-action="${a.id}"]`);d?d.click():o.layout?.header?.onAction?.(a.id)}}));for(let a of l)for(let d of a.shortcuts??[])p.push(c.register({...d,id:`${a.id}:${d.id}`}))};mf();let nS=300,Ol="var(--persona-history-overlay-margin,8px)",jn=null,Uo=null,Dl=0,$o=null,$s=null,ss=!1,Ep=0,ff=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,qs=()=>Co()&&_l()&&(le??hp())==="rail",oS=()=>te&&!_t,na=()=>{$s!==null&&clearTimeout($s),$s=null},rS=()=>{xg().catch(()=>{})},hf=()=>{na(),_t&&($s=setTimeout(()=>{$s=null,!(ss||!_t)&&($o?.contains(document.activeElement)||An({restoreFocus:!1}))},nS))},sS=(r,a)=>{let d=$o?.getBoundingClientRect();if(!d)return!1;let m=jn?.getBoundingClientRect(),y=m?Math.min(m.top,d.top):d.top;return r>=d.left&&r<=d.right&&a>=y&&a<=d.bottom||!!m&&r>=m.left&&r<=m.right&&a>=m.top&&a<=m.bottom},Tp=r=>{_t&&(ss=sS(r.clientX,r.clientY),ss?na():$s===null&&hf())},yf=r=>{te||!qs()||(_t=!0,ra({invoker:jn,keyboard:r?.keyboard===!0}).then(()=>{te?!ss&&document.activeElement!==jn&&An():_t=!1}))},bf=()=>{let r=Yi?.querySelector('[data-persona-history-focus="collapse"]');r&&(r.setAttribute("aria-label",_t?Qe.expandLabel:Qe.collapseLabel),r.setAttribute("aria-expanded",_t?"false":"true"))},vf=()=>{xp(!1);let r=rt;if(!_t||!r){ra({invoker:jn});return}let a=document.activeElement===jn;_t=!1,Nl(),r.element.remove(),Pp(r.element),bf(),a&&Ul(),xn(),hr()},iS=()=>{xp(!0),An()};Ap=()=>{!te||_t?vf():iS()};let aS=()=>{let r=Mp(),a=hs({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":gp,...r?{"aria-keyshortcuts":r.aria}:{}}}),d=a.button;d.addEventListener("mouseenter",()=>{ss=!0,na(),!(ff()||Date.now()<Ep)&&yf()}),d.addEventListener("mouseleave",()=>{ss=!1,Ep=0,hf()}),d.addEventListener("focus",()=>{te||rS()}),d.addEventListener("click",m=>{Co()&&(m.detail!==0&&ff()&&!te?yf():vf())}),jn=d,Uo=a.wrapper},oa=()=>{if(Uo&&!Uo.isConnected&&(Uo=null,jn=null),!qs()){Uo?.remove(),Uo=null,jn=null;return}jn||aS();let r=Uo,a=jn;if(!r||!a)return;let d=Us()!=="right"?Te.firstChild:null;(d??Te.lastChild)!==r&&Te.insertBefore(r,d),r.style.display=oS()||Dl>0?"none":"",a.setAttribute("aria-label",Qe.expandLabel),a.setAttribute("aria-expanded",te?"true":"false"),$o&&mt()},Cf=r=>{if(!_t)return;let a=r.target;a instanceof Node&&($o?.contains(a)||Uo?.contains(a)||a instanceof Element&&a.closest('.persona-dropdown-menu,[role="alertdialog"]')||An({restoreFocus:!1}))};document.addEventListener("pointerdown",Cf,!0),be.push(()=>{document.removeEventListener("pointerdown",Cf,!0),document.removeEventListener("pointermove",Tp),zs?.(),na()});let kp=null,zs=null,wf=16,Sf=r=>{Jw(wp(r)),mt(),xn()},lS=()=>{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(vp)),r.setAttribute("aria-valuemax",String(Cp)),r.addEventListener("pointerdown",a=>{let d=rs;if(!d||a.button!==0)return;a.preventDefault(),zs?.();let m=a.clientX,y=d.getBoundingClientRect().width||Zi(),C=Us()==="right"?-1:1,B=y,z=t.ownerDocument;d.style.transition="none";let q=X=>{B=wp(y+C*(X.clientX-m)),d.style.flex=`0 0 ${B}px`,r.setAttribute("aria-valuenow",String(B))},j=()=>{zs=null,z.removeEventListener("pointermove",q),z.removeEventListener("pointerup",j),z.removeEventListener("pointercancel",j),d.style.removeProperty("transition");try{r.releasePointerCapture(a.pointerId)}catch{}Sf(B)};zs=j,z.addEventListener("pointermove",q),z.addEventListener("pointerup",j),z.addEventListener("pointercancel",j);try{r.setPointerCapture(a.pointerId)}catch{}}),r.addEventListener("keydown",a=>{let d=Us()==="right"?-wf:wf,m=Zi(),y=a.key==="ArrowRight"?m+d:a.key==="ArrowLeft"?m-d:a.key==="Home"?vp:a.key==="End"?Cp:null;y!==null&&(a.preventDefault(),Sf(y))}),r},cS=(r,a)=>{if(!Yw()||ta()){zs?.(),kp?.remove();return}let d=kp??lS();kp=d,d.setAttribute("aria-label",Qe.resizeLabel),d.setAttribute("aria-valuenow",String(Zi())),d.nextElementSibling!==a&&r.insertBefore(d,a)};mt=()=>{rt?.view.setRailSide(Us());let r=Us()==="right",a=$o;if(a){let z=jn?jn.getBoundingClientRect().bottom-pe.getBoundingClientRect().top:0;a.style.top=`calc(${Math.max(0,Math.round(z))}px + ${Ol})`,a.style.width=`${Zi()}px`,a.style.left=r?"":Ol,a.style.right=r?Ol:""}let d=rs,m=Ns,y=Xi;if(!d||!m||!y)return;d.style.flex=`0 0 ${ta()?Qw:Zi()}px`;let C="1px solid var(--persona-divider,#e5e7eb)";d.style.borderRight=r?"":C,d.style.borderLeft=r?C:"";let B=r?y:d;m.firstElementChild!==B&&m.append(B,r?d:y),cS(m,r?d:y)};let xf=r=>{if(Fs&&rs){Fs.replaceWith(r),Fs=null,mt();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 d=k("div","persona-history-rail-conversation");d.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let m=k("div","persona-history-rail-host");m.style.cssText="display:flex;min-height:0;overflow:hidden",pe.insertBefore(a,Te.parentNode===pe?Te:ne);for(let y of df())y?.parentNode===pe&&d.appendChild(y);a.append(m,d),m.appendChild(r),Ns=a,rs=m,Xi=d,mt()},dS=()=>{if(Ns)return;let r=k("div","persona-history-rail-placeholder");r.style.cssText="flex:1 1 auto;min-height:0",Fs=r,xf(r),xn()},Af=()=>{Fs&&(Nl(),xn())},pS=r=>{let a=k("div","persona-history-rail-overlay");a.style.cssText=`position:absolute;bottom:${Ol};display:flex;overflow:hidden;z-index:${gc-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))`,pe.style.position="relative",pe.appendChild(a),a.appendChild(r),document.addEventListener("pointermove",Tp),$o=a,mt(),bf()},Nl=()=>{Wl?.(),$o&&(ss&&(Ep=Date.now()+150),document.removeEventListener("pointermove",Tp),$o.remove(),$o=null);let r=Ns;if(r){zs?.();for(let a of df())a&&r.contains(a)&&pe.insertBefore(a,r);r.remove(),Ns=null,rs=null,Xi=null,Fs=null}},Mf=r=>{Yi=r,r.id=gp,r.style.flex="1 1 auto",r.style.minHeight="0"},Pp=r=>{Mf(r),(le!=="rail"||_t)&&Af(),le!=="rail"?Gw(r):_t?pS(r):xf(r)},Fl=()=>{if(oa(),_f(),!te||!rt)return;let r=hp();if(r===le)return;let a=document.activeElement,d=a instanceof HTMLElement&&(rt.element.contains(a)||Bn?.contains(a)===!0)?a:null;Nl(),rt.element.remove(),rt.view.setHeaderPlacement("inline"),le=r,rt.view.setPresentation(r),rt.view.setCollapsed(ta()),rt.requestRender(),rt.element.isConnected||Pp(rt.element),d?.isConnected?d.focus():Ul(),Ut(),xn(),hr()},Ef=(r,a)=>Bn?.querySelector(a)??r.querySelector(a),Ul=()=>{let r=rt?.element??Yi;if(!r)return;let a=Ef(r,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(a){a.focus();return}let d=Ef(r,".persona-history-title")??r;d.tabIndex=-1,d.focus()},ra=async r=>{if(!Co()||te)return;let a=Wn;if(!a)return;if(!_t&&qs()&&Sp()){oa();return}$l();let d=++Qi;kl=r?.returnSurface??"conversation",dp=r?.invoker??dn;let m=qs()&&!_t;m&&(Dl+=1,oa(),dS());let y;try{y=await xg()}catch{Hl(Qe.openHistoryLabel),m&&(Dl-=1,d===Qi&&(Af(),oa()));return}if(m&&(Dl-=1),d!==Qi||te)return;Tl={scope:fp()},le=hp(),te=!0;let C=le==="panel"&&o.layout?.showHeader!==!1&&Te.style.display!=="none"?"external":"inline",B=o.features?.history?.rowAvatar,z=Mp(),q=z?{hint:z.hint,aria:z.aria}:null,j={provider:a,context:Tl,targetId:tf(),presentation:le,collapsible:Bl(),collapsed:ta(),railSide:Us(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:Zw(),onToggleCollapse:gf,...q?{collapseShortcut:q}:{},headerPlacement:C,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=>Lp(X,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:X=>is(X),attachTooltip:Yt,onStartNew:()=>Hp({focusComposer:!0}),onClose:()=>An(),onRequestDeleteConversation:X=>Bf(X),onRequestClearHistory:()=>yS(),...a.resetDevice?{onRequestResetIdentity:()=>bS()}:{}};rt=cC({plugins:l,config:o,getPresentation:()=>le??"panel",getReturnSurface:()=>kl,close:()=>An(),createView:({slots:X,renderDom:se,onModelChange:ge,railSections:Ye})=>(os=y.createHistoryView({...j,railSections:tS(Ye),slots:X,renderDom:se,onModelChange:ge,onAnnounce:Hl}),os),onElementChanged:(X,se)=>{if(!se?.isConnected)return Pp(X);Mf(X),se.replaceWith(X),bp()}}),rt.view.setNewConversationRequired(Pl.recovery==="new_conversation_required"),r?.focus!==!1&&(le!=="rail"||r?.keyboard===!0)&&Ul(),Ut(),xn(),hr(),w.emit("history:opened",{presentation:le,returnSurface:kl,timestamp:Date.now()})},$l=()=>{},An=r=>{if(!te)return;Qi+=1;let a=kl,d=dp,m=rt,y=r?.restoreFocus!==!1;te=!1;let C=!1,B=null,z=()=>{if(!C){if(C=!0,$l=()=>{},B!==null&&clearTimeout(B),_t=!1,na(),Nl(),m?.dispose(),m?.view.destroy(),m?.element.remove(),rt===m&&(rt=null,os=null,Yi=null,le=null,Tl=null,dp=null),Ut(),xn(),hr(),y){let j=d??dn;j?.isConnected?j.focus():Jr()}w.emit("history:closed",{returnSurface:a,timestamp:Date.now()})}},q=m&&m.element===m.view.element?m.view.playExit():null;if(!q){z();return}$l=z,B=setTimeout(z,Uw),q.then(z)},Tf=r=>{if(!(r.key!=="Escape"||!te||!rt)){if(le==="rail"){let a=r.target;if(!(a instanceof Node)||!(rt.element.contains(a)||_t&&Uo?.contains(a)===!0))return}r.preventDefault(),r.stopPropagation(),An()}};pe.addEventListener("keydown",Tf),be.push(()=>pe.removeEventListener("keydown",Tf));let ql=null,kf=!1,sa=()=>{if(!nr)return;let r=o.layout?.header?.titleSource==="conversation",a=r&&ql?.trim()||null;nr.textContent=a??o.launcher?.title??"Chat Assistant";let d=nr.closest(".persona-combo-btn");if(!d)return;let m=!r||E.getActiveConversationId()!==null;d.setAttribute("data-persona-menu-locked",m?"false":"true"),d.setAttribute("aria-haspopup",m?"true":"false"),m||d.setAttribute("aria-expanded","false"),d.style.cursor=m?"pointer":"default";let y=d.querySelector("svg");y&&(y.style.display=m?"":"none")},uS=r=>{r!==ql&&(ql=r,sa())},is=r=>{kf=r?.starred===!0,uS(r&&r.title.trim()||null),sa()};sa(),pe.addEventListener("persona:title-menu-builtin",r=>{let a=r.detail?.actionId,d=E.getActiveConversationId();d&&(a==="delete"?Bf(d):a==="star"&&E.canUpdateConversations()&&Rp(d,{starred:!kf}).catch(()=>{}))});let zl=0,gS=250,jl=null,Vl=()=>{jl&&clearTimeout(jl),jl=null};be.push(Vl);let Pf=()=>{Vl();let r=Zr;r&&(Vi=!0,r.hidden=!1,Ie.style.display="none",Ki())},Kl=()=>{zl+=1,Vl(),Zr&&(Zr.remove(),Zr=null,Vi=!1,Ie.style.removeProperty("display"),zn(Le,!1),Ki())},mS=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Ie.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Ip=(r,a)=>Q("div",{className:On("persona-conversation-loading-bubble",a&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:r}}),If=()=>Q("div",{className:"persona-conversation-loading-body"},Ip("58%",!1),Ip("72%",!0),Ip("44%",!1)),Lf=r=>{Zr?.remove(),Zr=r,r.hidden=!Vi,ne.insertBefore(r,Ie),Vl(),Vi||(jl=setTimeout(Pf,gS)),zn(Le,!0)},fS=()=>{let r={config:o,streaming:!1,location:"conversation-open",defaultRenderer:If},a=null,d=l.find(m=>m.renderLoadingIndicator);d?.renderLoadingIndicator&&(a=d.renderLoadingIndicator(r)),a===null&&o.loadingIndicator?.render&&(a=o.loadingIndicator.render(r)),Lf(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},a??If()))},hS=r=>{let a=()=>{Lp(r,{focusComposer:!0}).catch(()=>{})},d=Co()?()=>{Kl(),ra()}:void 0,m=(z,q)=>{let j=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:z});return j.addEventListener("click",q),j},y=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},m(Qe.openConversationRetryLabel,a),d?m(Qe.openConversationBackLabel,d):null)),C=Object.freeze({conversationId:r,config:o,copy:Object.freeze({title:Qe.openConversationErrorTitle,retryLabel:Qe.openConversationRetryLabel,backLabel:Qe.openConversationBackLabel}),retry:a,...d?{back:d}:{},defaultRenderer:y}),B=null;for(let z of l)if(z.renderHistoryOpenError){try{B=z.renderHistoryOpenError(C)}catch(q){console.warn("[persona] renderHistoryOpenError threw",q),B=null}if(B)break}Lf(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},B??y())),Pf()};w.on("history:closed",()=>{Zr&&zn(Le,!0)});let Lp=async(r,{focusComposer:a=!1}={})=>{let d=Ds(),m=!!rt;rt?.view.setActiveConversationId(r),Kl();let y=zl;fS(),te&&(le==="panel"||_t)&&An({restoreFocus:!1}),Ls=!0;try{await E.openConversation(r,{scope:d})}catch(C){throw y===zl&&hS(r),C}finally{Ls=!1}y===zl&&(Kl(),Bt.clear(),io(),Sn(),Vd()||yl(),mS(),qo(),m||is(null),w.emit("history:conversationOpened",{conversationId:r,title:ql,scope:d,timestamp:Date.now()}),a&&Jr())},Hp=async({focusComposer:r=!1}={})=>{Kl(),await E.startNewConversation({scope:Ds()}),is(null),Bt.clear(),io(),Sn(),yl(),qo();let a=E.getActiveConversationId();rt?.view.setActiveConversationId(a),w.emit("history:conversationStarted",{conversationId:a,timestamp:Date.now()}),te&&(le==="panel"||_t)&&An({restoreFocus:!1}),r&&Jr()},Rp=async(r,a)=>{let d=await E.updateConversation(r,{...a,...a.title!==void 0?{title:a.title.trim()}:{}});return rt?.view.applyConversationSummary(d),!rt&&r===E.getActiveConversationId()&&is(d),d},Hf=async r=>{let a=Ds(),d=E.getActiveConversationId()===r;await E.deleteConversation(r,{scope:a}),rt?.view.removeConversationSummary(r),d&&(is(null),Bt.clear(),io(),Sn(),qo()),w.emit("history:conversationDeleted",{conversationId:r,scope:a,wasActive:d,timestamp:Date.now()})},Rf=async r=>{let a=r?.scope??Ds(),d=r?.allTargets?null:r?.targetId??tf(),m=await E.clearConversationHistory({...d?{targetId:d}:{},scope:a});return is(null),Bt.clear(),io(),Sn(),qo(),w.emit("history:cleared",{deleted:m.deleted,scope:a,targetId:d,timestamp:Date.now()}),m},Wf=async()=>{if(!Wn?.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{is(null),E.clearArtifacts(),Bt.clear(),ip=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),ie={},we.syncFromMetadata(),G?.clear&&ml(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),io(),Sn(),qo(),An({restoreFocus:!1}),Jr(),ye||Mt?.launcher.element.focus()}return Hl(r?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),w.emit("history:identityReset",{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},Wp=()=>ho?Me:pe,Bf=async r=>await fd({host:Wp(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Hf(r),"deleted"):"cancelled",yS=async()=>{let r=Ds()==="verified-user";return await fd({host:Wp(),title:Qe.clearHistoryConfirmTitle,description:r?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Rf(),"cleared"):"cancelled"},bS=async()=>{if(!await fd({host:Wp(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:a}=await Wf();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 qo=()=>{if(!(Co()&&!!Pl.nextMessageCursor&&!!E.getActiveConversationId())){Vn.remove();return}Vn.textContent=Qe.showEarlierMessagesLabel,Vn.parentNode!==ne&&ne.insertBefore(Vn,ne.firstChild)};Vn.addEventListener("click",()=>{let r=E.getActiveConversationId(),a=Pl.nextMessageCursor;if(!r||!a||Vn.disabled)return;Vn.disabled=!0;let d=ne.scrollHeight,m=ne.scrollTop;E.loadOlderMessages(r,a,{scope:Ds()}).then(()=>{ne.scrollTop=m+(ne.scrollHeight-d),xn()}).catch(()=>{}).finally(()=>{Vn.disabled=!1,qo()})});let vS=()=>{let r=hs({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()||ef())){if(te){An();return}ra({invoker:r.button,keyboard:a.detail===0})}}),r},_f=()=>{if(!Co()){vo?.remove(),dn=null,vo=null;return}if(vo&&!vo.isConnected&&(dn=null,vo=null),!dn&&Te){let m=vS();dn=m.button,vo=m.wrapper;let y=De.clearChatButtonWrapper||De.closeButtonWrapper;y?.parentNode&&Te.contains(y)?y.parentNode.insertBefore(vo,y):Te.appendChild(vo)}if(!dn||!vo)return;let r=qs()||te&&le==="rail";if(vo.style.display=r?"none":"",r){document.activeElement===dn&&Ul();return}let a=ef();dn.disabled=a,dn.setAttribute("aria-disabled",a?"true":"false");let d=a?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;dn.setAttribute("aria-label",d),(o.features?.history?.presentation??"panel")==="panel"?(dn.removeAttribute("aria-expanded"),dn.removeAttribute("aria-controls")):(dn.setAttribute("aria-expanded",te?"true":"false"),dn.setAttribute("aria-controls",gp))},Gl=!1,CS=()=>{let r=De.clearChatButton;if(r){if(Co()){Gl||(up=r.getAttribute("aria-label")??"",Gl=!0),r.setAttribute("aria-label",Qe.newConversationLabel),r.removeAttribute("title");return}Gl&&(Gl=!1,up&&r.setAttribute("aria-label",up))}},hr=()=>{Qe=eu(o.features?.history?.copy),_f(),oa(),CS(),qo()};Ct=hr,qe=r=>{Pl=r,rt?.view.setNewConversationRequired(r.recovery==="new_conversation_required"),ji(r.sendBlocked||Ln),qo()},Lt=r=>{(r.code==="history_continuity_reset"||r.code==="conversation_deleted_recovered")&&(Bt.clear(),io(),Sn()),Hl(r.message),rt?.view.refresh()},sf(),hr(),be.push(()=>{Il?.(),Ll?.(),Qi+=1,$l(),rt?.dispose(),rt?.view.destroy(),rt=null}),o.clientToken&&E.initClientSession().then(()=>{if(Co())return E.reconcileBootConversation({scope:fp()})}).then(()=>{qo()}).catch(r=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",r)}),(It||o.onSSEEvent)&&E.setSSEEventCallback((r,a)=>{o.onSSEEvent?.(r,a),U(r,a)});let Of=()=>{o.resume&&typeof o.reconnectStream=="function"&&E.resumeFromHandle(o.resume)};oe?oe.then(r=>{if(r){if(r.metadata&&(ie=Tg(r.metadata),we.syncFromMetadata()),r.messages?.length){Ls=!0;try{E.hydrateMessages(r.messages)}finally{Ls=!1}wl()}r.artifacts?.length&&E.hydrateArtifacts(r.artifacts,r.selectedArtifactId??null),Rm(r.draft)}}).catch(r=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",r)}).finally(()=>{Jd=!0,S(),Of()}):(Rm(R),Of());let wS=()=>{!xe()||ye||!(o.launcher?.composerBar?.expandOnSubmit??!0)||at(!0,"auto")},SS=(r,a)=>r?a?{refs:[...r.refs,...a.refs],finalize:async()=>{let[d,m]=await Promise.allSettled([r.finalize(),a.finalize()]),y=[];return d.status==="fulfilled"?y.push(d.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",d.reason),m.status==="fulfilled"?y.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),mT(y)}}:r:a,Bp=()=>{let a=de.getInlineMessageFields?.();return a&&a.contentSegments.some(m=>m.kind==="mention")?a.contentSegments:void 0},zo=!1,as=null,Ql=()=>{de.value="",de.style.height="auto",go(),aa()},_p="data-persona-composer-notice",js=null;function xS(r){Qa(r),!(xe()||!ot)&&(ot.hasAttribute(wi)||(ot.setAttribute(_p,""),ot.setAttribute("role","status"),ot.setAttribute("aria-live","polite"),ot.textContent=r,js&&clearTimeout(js),js=setTimeout(()=>{if(js=null,!!ot?.hasAttribute(_p)&&(ot.removeAttribute(_p),ot.removeAttribute("role"),ot.removeAttribute("aria-live"),u)){let a=E.getStatus();tn(ot,cn(a),o.statusIndicator??{},a)}},4e3)))}function AS(){let r=Se.getState().pendingSubmission;r&&(xs(void 0),de&&(de.value=r.text,de.dispatchEvent(new Event("input",{bubbles:!0})),go()),r.options.selectedModelId&&(Se.setSelectedModelId(r.options.selectedModelId),rr?.repaint()),r.options.activeModeIds?.length&&Za(r.options.activeModeIds),r.options.quote&&mo(r.options.quote),de?.focus())}let MS=r=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",r)},Df=(r={})=>{let a=(r.overrideText??de?.value??"").trim();return r.resolveInlineCommand&&a?(Ht?.takeInlineCommand(a)??Promise.resolve(null)).then(d=>Nf(r,a,d)):Nf(r,a,null)},Nf=(r,a,d)=>{if(d?.kind==="action"){Ql(),Ht?.clear(),Br();return}let m=d?.kind==="server"?d.mentions:null,y=d?.kind==="prompt"?d.sendText:a,C=r.pending?.contentParts,B=(Xe?.hasAttachments()??!1)||(C?.length??0)>0;if(!Fb({text:y,hasAttachments:B,attachmentsReady:Xe?.isReady()??!0,hasMentions:Ht?.hasMentions()??!1,hasServerMentions:!!m,inputDisabled:gr(),sendDisabled:Xr()}))return;let z=E.isStreaming()?Ed():"block";if(z==="defer-one"&&!r.pending){if(Se.getState().pendingSubmission){xS("One message is already queued. Edit or remove it first.");return}ES({intent:r,sendText:y,serverMentions:m});return}let q={text:y,mentionRefs:[...Ht?.getMentionRefs()??[],...m?.refs??[]],contentSegments:d?.kind==="prompt"?void 0:Bp(),options:{...Se.getState().selectedModelId&&{selectedModelId:Se.getState().selectedModelId},...Se.getState().activeModeIds.length>0&&{activeModeIds:[...Se.getState().activeModeIds]},...Se.getState().quote&&{quote:{...Se.getState().quote}}},viaVoice:r.viaVoice};r.pending&&(q.options={...r.pending.options},q.contentSegments=r.pending.contentSegments,q.mentionRefs=[...r.pending.mentionRefs],q.viaVoice=r.pending.viaVoice);let j=()=>{if(C?.length)return[...C];if(!Xe?.hasAttachments())return;let lt=[...Xe.getContentParts()];return q.text&<.push(Eo(q.text)),lt};q.contentParts=j();let X=()=>{zr(),wS();let lt=Ht?.collectForSubmit()??null,Kt=SS(lt,m),Ot=j();r.consumeDraft!==!1&&Ql();let Tt={selectedModelId:q.options.selectedModelId,activeModeIds:q.options.activeModeIds},nn=z==="interrupt";nn&&E.cancel(),E.sendMessage(q.text,{contentParts:Ot,mentions:Kt??void 0,contentSegments:q.contentSegments,viaVoice:q.viaVoice,composerOptions:Tt,...q.options.quote&&{quote:q.options.quote},...nn&&{interrupt:!0}}),Xe?.hasAttachments()&&Xe.clearAttachments(),lt&&Ht?.clear(),Br();let Je=Se.getState().activeModeIds,on=Tb(Je,o.composer?.modes);on.length!==Je.length&&Za(on),Se.getState().quote&&mo(void 0),hl(),Ld.release(),no()},se=o.composer?.onBeforeSend;if(!se){X();return}let ge=new AbortController;as=ge;let Ye=lt=>{if(as=null,lt.status==="error"){MS(lt.error);return}lt.status==="proceed"&&X()},it=Ub(se,q,ge.signal);if(!(it instanceof Promise)){Ye(it);return}return Se.setPreparing(!0),it.then(Ye).finally(()=>Se.setPreparing(!1))};function ES(r){let a=Se.getState(),d=Xe?.hasAttachments()??!1,m=d?[...Xe.getContentParts()]:[];d&&r.sendText&&m.push(Eo(r.sendText));let y=Wu({text:r.sendText,contentParts:m.length?m:void 0,mentionRefs:[...Ht?.getMentionRefs()??[],...r.serverMentions?.refs??[]],contentSegments:Bp(),options:{...a.selectedModelId&&{selectedModelId:a.selectedModelId},...a.activeModeIds.length>0&&{activeModeIds:[...a.activeModeIds]},...a.quote&&{quote:{...a.quote}}},viaVoice:r.intent.viaVoice});xs(y),r.intent.consumeDraft!==!1&&Ql(),d&&Xe.clearAttachments(),Ht?.clear(),Br(),a.quote&&mo(void 0),hl(),Ld.release(),no(),Qa("Message queued. It sends when the response finishes.")}function TS(){let r=Se.getState().pendingSubmission;r&&(xs(void 0),Xl(r.text,{consumeDraft:!1,pending:r}))}function kS(r){if(o.messageActions?.showEdit!==!0)return;let a=E.getMessages().find(d=>d.id===r);!a||!uu(a)||qr!==r&&(zr(),qr=r,lr=Hb({messageId:r,initialText:a.content,onSave:d=>PS(r,d),onCancel:()=>zr()}),Bt.delete(r),qn(Ie,E.getMessages(),Jt),lr.focus())}function PS(r,a){let d=lr;if(qr=null,lr=null,d?.destroy(),Bt.delete(r),!E.resubmitFrom(r,{reason:"edit",replacement:{text:a,mentionRefs:[],options:{}}})){qn(Ie,E.getMessages(),Jt);return}xn()}function IS(r){if(E.isStreaming())return;let a=pu(E.getMessages(),r);a&&(zr(),E.resubmitFrom(a,{reason:"retry"})&&xn())}el={regenerate:IS,edit:kS,quote:r=>{let d=E.getMessages().find(m=>m.id===r)?.content?.trim();d&&(mo({text:d,messageId:r}),de?.focus())}};let ia=async r=>{if(!zo){zo=!0;try{await Df({resolveInlineCommand:!0,...r})}finally{zo=!1}}};function Yl(r){Xr()||(Ql(),Xl(r,{consumeDraft:!1}))}let Xl=(r,a)=>{if(zo)return;zo=!0;let d=()=>{zo=!1};try{let m=Df({...a,overrideText:r});m instanceof Promise?m.finally(d):d()}catch(m){throw d(),m}},LS=r=>{if(r.preventDefault(),E.isStreaming()){E.cancel(),dt?.reset(),H?.update();return}zo||ia()},HS=()=>o.features?.composerHistory!==!1,Op={...Fu},Dp=!1,aa=()=>{Op={...Fu}},RS=()=>E.getMessages().filter(r=>r.role==="user").map(r=>r.content??"").filter(r=>r.length>0),WS=r=>{if(!de)return;Dp=!0,de.value=r,de.dispatchEvent(new Event("input",{bubbles:!0})),Dp=!1;let a=de.value.length;de.setSelectionRange(a,a)},BS=r=>{Dp||(r.isComposing||Ht?.handleInput(r.inputType??void 0),aa())},_S=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Pa(de)}),OS=r=>{if(de&&!gr()&&!(!r.isComposing&&Ht?.handleKeydown(r))){if(HS()&&(r.key==="ArrowUp"||r.key==="ArrowDown")&&!r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.isComposing){let a=de.selectionStart===0&&de.selectionEnd===0,d=nv({direction:r.key==="ArrowUp"?"up":"down",history:RS(),currentValue:de.value,atStart:a,state:Op});if(Op=d.state,d.handled){r.preventDefault(),d.value!==void 0&&WS(d.value);return}}if(pb(r,_S())){if(E.isStreaming()){if(r.preventDefault(),Ed()==="block"||zo||Xr())return;aa(),ia();return}if(zo){r.preventDefault();return}if(Xr()){r.preventDefault();return}aa(),r.preventDefault(),Ee.click()}}},Ff=r=>{if(!(r.key!=="Escape"||r.isComposing)&&r.composedPath().includes(pe)){if(as){as.abort(),as=null,r.preventDefault(),r.stopImmediatePropagation();return}E.isStreaming()&&(E.cancel(),dt?.reset(),H?.update(),aa(),r.preventDefault(),r.stopImmediatePropagation())}},DS=async r=>{if(o.attachments?.enabled!==!0||!Xe||gr())return;let a=dT(r.clipboardData);a.length!==0&&(r.preventDefault(),await Xe.handleFiles(a))},Kn=null,wo=!1,Vs=null,yt=null,Np=()=>o.voiceRecognition?.completionBehavior==="review";function ls(r){re?.setAttribute("data-state",r),r==="recording"?FS():qp()}let Uf="--persona-voice-level",Fp=.5,Ks=null,Up=-1,Jl=0,$f=()=>{let r=[],a=Pn??re?.parentElement??null;return a&&r.push(a),Le&&r.push(Le),r},$p=r=>{let a=Math.round(Math.max(0,Math.min(1,r))*100)/100;if(a!==Up){Up=a;for(let d of $f())d.style.setProperty(Uf,String(a))}},NS=()=>{Up=-1,Jl=0;for(let r of $f())r.style.removeProperty(Uf)};function FS(){if(Ks!==null)return;if(typeof requestAnimationFrame!="function"){$p(u?E.getVoiceLevel()??Fp:Fp);return}let r=()=>{Ks=requestAnimationFrame(r);let a=u?E.getVoiceLevel():null;if(a===null){$p(Fp);return}Jl+=(a-Jl)*.3,$p(Jl)};Ks=requestAnimationFrame(r)}function qp(){Ks!==null&&(cancelAnimationFrame(Ks),Ks=null),NS()}let qf=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Zl=(r="user")=>{if(wo||E.isStreaming())return;let a=qf();if(!a)return;Kn=new a;let d=o.voiceRecognition??{},m=d.pauseDuration??2e3;Kn.continuous=d.provider?.browser?.continuous??!0,Kn.interimResults=!0,Kn.lang=d.provider?.browser?.language??"en-US";let y=de.value;Kn.onresult=C=>{let B="",z="";for(let j=0;j<C.results.length;j++){let X=C.results[j],se=X[0].transcript;X.isFinal?B+=se+" ":z=se}let q=y+B+z;de.value=q,go(),Vs&&clearTimeout(Vs),(B||z)&&(Vs=window.setTimeout(()=>{if(de.value.trim()&&Kn&&wo){if(yr(),Np())return;ia({viaVoice:!0})}},m))},Kn.onerror=C=>{C.error!=="no-speech"&&yr()},Kn.onend=()=>{if(wo){let C=de.value.trim();!Np()&&C&&C!==y.trim()&&ia({viaVoice:!0}),yr()}};try{if(Kn.start(),wo=!0,je.active=!0,r!=="system"&&(je.manuallyDeactivated=!1),Oo(r),so(),no(),re){let C=o.voiceRecognition??{};yt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:C.iconName??"mic",iconSize:parseFloat(C.iconSize??"")||un};let B=C.recordingBackgroundColor,z=C.recordingIconColor,q=C.recordingBorderColor;if(re.classList.add("persona-voice-recording"),ls("recording"),re.style.backgroundColor=B??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let j=re.querySelector("svg");j&&j.setAttribute("stroke",z)}q&&(re.style.borderColor=q),re.setAttribute("aria-label","Stop voice recognition")}}catch{yr("system")}},yr=(r="user")=>{if(wo){if(wo=!1,Vs&&(clearTimeout(Vs),Vs=null),Kn){try{Kn.stop()}catch{}Kn=null}if(je.active=!1,Oo(r),so(),no(),re){if(re.classList.remove("persona-voice-recording"),ls("idle"),yt){re.style.backgroundColor=yt.backgroundColor,re.style.color=yt.color,re.style.borderColor=yt.borderColor;let a=re.querySelector("svg");a&&a.setAttribute("stroke",yt.color||"currentColor"),yt=null}re.setAttribute("aria-label","Start voice recognition")}}},zp=()=>{if(!re||yt)return;let r=o.voiceRecognition??{};yt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:r.iconName??"mic",iconSize:parseFloat(r.iconSize??"")||un}},jp=(r,a)=>{if(!re)return;let d=re.querySelector("svg");d&&d.remove();let m=yt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||un),y=he(r,m,a,1.5);y&&re.appendChild(y)},ec=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Gs=()=>{if(!re)return;zp();let r=o.voiceRecognition??{},a=r.recordingBackgroundColor,d=r.recordingIconColor,m=r.recordingBorderColor;if(ec(),re.classList.add("persona-voice-recording"),ls("recording"),re.style.backgroundColor=a??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=d??"var(--persona-voice-recording-indicator, #ffffff)",d){let y=re.querySelector("svg");y&&y.setAttribute("stroke",d)}m&&(re.style.borderColor=m),re.setAttribute("aria-label","Stop voice recognition")},US=()=>{if(!re)return;zp();let r=o.voiceRecognition??{},a=E.getVoiceInterruptionMode(),d=r.processingIconName??"loader",m=r.processingIconColor??yt?.color??"",y=r.processingBackgroundColor??yt?.backgroundColor??"",C=r.processingBorderColor??yt?.borderColor??"";ec(),re.classList.add("persona-voice-processing"),ls("processing"),re.style.backgroundColor=y,re.style.borderColor=C;let B=m||"currentColor";re.style.color=B,jp(d,B),re.setAttribute("aria-label","Processing voice input"),a==="none"&&(re.style.cursor="default")},$S=()=>{if(!re)return;zp();let r=o.voiceRecognition??{},a=E.getVoiceInterruptionMode(),d=a==="cancel"?"square":a==="barge-in"?"mic":"volume-2",m=r.speakingIconName??d,y=r.speakingIconColor??(a==="barge-in"?r.recordingIconColor??yt?.color??"":yt?.color??""),C=r.speakingBackgroundColor??(a==="barge-in"?r.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":yt?.backgroundColor??""),B=r.speakingBorderColor??(a==="barge-in"?r.recordingBorderColor??"":yt?.borderColor??"");ec(),re.classList.add("persona-voice-speaking"),ls("speaking"),re.style.backgroundColor=C,re.style.borderColor=B;let z=y||"currentColor";re.style.color=z,jp(m,z);let q=a==="cancel"?"Stop playback and re-record":a==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",q),a==="none"&&(re.style.cursor="default"),a==="barge-in"&&re.classList.add("persona-voice-recording")},jo=()=>{re&&(ec(),ls("idle"),yt&&(re.style.backgroundColor=yt.backgroundColor??"",re.style.color=yt.color??"",re.style.borderColor=yt.borderColor??"",jp(yt.iconName,yt.color||"currentColor"),yt=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},Vp=()=>{if(!gr()){if(o.voiceRecognition?.provider?.type==="runtype"){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(()=>{je.active=!1,je.manuallyDeactivated=!0,so(),Oo("user"),jo()});return}E.toggleVoice().then(()=>{je.active=E.isVoiceActive(),je.manuallyDeactivated=!E.isVoiceActive(),so(),Oo("user"),E.isVoiceActive()?Gs():jo()});return}if(wo){let r=de.value.trim();je.manuallyDeactivated=!0,so(),yr("user"),r&&!Np()&&ia()}else je.manuallyDeactivated=!1,so(),Zl("user")}};Td=Vp,re&&be.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(E.isVoiceActive()&&E.toggleVoice(),jo()):yr("system")});let qS=w.on("assistant:complete",()=>{Se.getState().pendingSubmission&&setTimeout(()=>{E.isStreaming()||TS()},0)});be.push(qS);let zS=w.on("assistant:complete",()=>{Im&&(je.active||je.manuallyDeactivated||Im==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?E.toggleVoice().then(()=>{je.active=E.isVoiceActive(),Oo("auto"),E.isVoiceActive()&&Gs()}):Zl("auto"))},600))});be.push(zS);let jS=w.on("action:resubmit",()=>{setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)});be.push(jS);let zf=()=>{at(!ye,"user")},Mt=null,pn=null;if(ue&&!xe()){let{instance:r,element:a}=sg({config:o,plugins:l,onToggle:zf});Mt=r,r||(pn=a)}Mt?t.appendChild(Mt.element):pn&&t.appendChild(pn),zi(),Ps(),Al(),op(),ji(E.isStreaming()),Vd()||(In()==="follow"?pr(!0):yl()),pw(),ct&&(!ue||xe()?setTimeout(()=>Jr(),0):ye&&setTimeout(()=>Jr(),200));let cs=null,jf=()=>{cs&&(cs.disconnect(),cs.observe(Le),cs.observe(pe))},la=()=>{if(xe()){Wr(),zi();return}let r=Rt(o),a=o.launcher?.sidebarMode??!1,d=t.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640,C=d.innerWidth<=y,B=m&&C&&ue;try{if(B){_r(),Ri=ll();return}let z=!1;Ne&&(Ne=!1,_r(),z=!0);let q=ll();if(!z&&q!==Ri&&(_r(),z=!0),Ri=q,z&&rl(),!ue&&!r){Me.style.height="",Me.style.width="";return}if(!a&&!r){let X=o?.launcher?.width??o?.launcherWidth??Yo;Me.style.width=X,Me.style.maxWidth=X}al(),mm()}finally{if(Wr(),Ja(),zi(),ye&&ue){let q=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),j=o.launcher?.sidebarMode??!1,X=o.launcher?.mobileFullscreen??!0,se=Rt(o)&&X&&q,ge=j||X&&q&&ue||se;if(ge&&!bo){let Ye=t.getRootNode(),it=Ye instanceof ShadowRoot?Ye.host:t.closest(".persona-host");it&&!yo&&(yo=Uu(it,o.launcher?.zIndex??an)),bo=$u(t.ownerDocument)}else ge||(yo?.(),yo=null,bo?.(),bo=null)}}};la();let tc=t.ownerDocument.defaultView??window;if(tc.addEventListener("resize",la),be.push(()=>tc.removeEventListener("resize",la)),typeof ResizeObserver<"u"){cs=new ResizeObserver(()=>{Ja()}),jf(),be.push(()=>{cs?.disconnect(),cs=null});let r=new ResizeObserver(()=>{Fl()});r.observe(pe),be.push(()=>r.disconnect())}tc.addEventListener("resize",Fl),be.push(()=>tc.removeEventListener("resize",Fl)),Rn=ne.scrollTop;let Vf=Ko(ne),Kf=()=>{let r=ne.scrollTop,a=Ko(ne),d=a<Vf;if(Vf=a,!or()){Rn=r,Ut();return}let{action:m,nextLastScrollTop:y}=Fh({following:Hn.isFollowing(),currentScrollTop:r,lastScrollTop:Rn,nearBottom:gs(ne,Bo),userScrollThreshold:aw,isAutoScrolling:wn||dl||d,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Rn=y,m==="resume"){bl()||Sn();return}m==="pause"&&Ni()};if(ne.addEventListener("scroll",Kf,{passive:!0}),be.push(()=>ne.removeEventListener("scroll",Kf)),typeof ResizeObserver<"u"){let r=new ResizeObserver(()=>{bw(),tu(Ie)});r.observe(Ie),r.observe(ne),be.push(()=>r.disconnect())}let Gf=()=>{or()&&Hn.isFollowing()&&bl()&&Ni()},Qf=ne.ownerDocument;Qf.addEventListener("selectionchange",Gf),be.push(()=>{Qf.removeEventListener("selectionchange",Gf)});let VS=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Yf=r=>{VS.has(r.key)&&(Gr(),Bg()&&or()&&Hn.isFollowing()&&Ni())},Xf=r=>{r.target?.closest("a, button, [tabindex], input, textarea, select")&&(Gr(),Bg()&&or()&&Hn.isFollowing()&&Ni())};ne.addEventListener("keydown",Yf),ne.addEventListener("focusin",Xf),be.push(()=>{ne.removeEventListener("keydown",Yf),ne.removeEventListener("focusin",Xf)});let Jf=r=>{if(r.deltaY!==0&&Gr(),!or())return;let a=Uh({following:Hn.isFollowing(),deltaY:r.deltaY,nearBottom:gs(ne,Bo),resumeWhenNearBottom:!0});a==="pause"?Ni():a==="resume"&&!bl()&&Sn()};ne.addEventListener("wheel",Jf,{passive:!0}),ne.addEventListener("touchmove",Gr,{passive:!0}),ne.addEventListener("pointerdown",Gr,{passive:!0}),be.push(()=>{ne.removeEventListener("touchmove",Gr),ne.removeEventListener("pointerdown",Gr)}),be.push(()=>ne.removeEventListener("wheel",Jf)),Wt.addEventListener("click",()=>{io(),ne.scrollTop=ne.scrollHeight,Rn=ne.scrollTop,Sn(),pr(!0),Ut()}),be.push(()=>Wt.remove()),be.push(()=>{Bm(),io()});let Zf=()=>{Ue&&(Fr&&(Ue.removeEventListener("click",Fr),Fr=null),Oe()?(Ue.style.display="",Fr=()=>{at(!1,"user")},Ue.addEventListener("click",Fr)):Ue.style.display="none")};Zf(),(()=>{let{clearChatButton:r}=De;r&&r.addEventListener("click",()=>{if(Co()){Hp({focusComposer:!0}).catch(d=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",d)});return}E.clearMessages(),Bt.clear(),Sn(),ri(De.composerOverlay);try{localStorage.removeItem(Ci),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ci}`)}catch(d){console.error("[AgentWidget] Failed to clear default localStorage:",d)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ci)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(d){console.error("[AgentWidget] Failed to clear custom localStorage:",d)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),G?.clear&&ml(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ie={},we.syncFromMetadata(),Xe?.clearAttachments(),hl(),xs(void 0),mo(void 0),zr(),xt?.clear(),dt?.reset(),H?.update()})})();let eh=[["keydown",OS],["input",BS],["input",go],["input",Br],["keyup",Br],["paste",DS],["focus",QC]],th=r=>{if(r)for(let[a,d]of eh)et?.addListener(r,a,d)},KS=r=>{if(r)for(let[a,d]of eh)et?.removeListener(r,a,d)},nh=()=>{et&&(et.addListener(et.form,"submit",LS),et.addListener(et.footer,"click",Br),th(de),re&&et.addListener(re,"click",Vp))};nh();let oh=()=>{Ht?.onComposerSwap((r,a)=>{KS(a),de=r,et&&(et.input=r),th(r),Pd(),Yd(),go()})};oh();let Kp=!1;function rh(){if(!Kp){Kp=!0;try{let r=de?.value??"",a=Le.ownerDocument??document,d=de?a.activeElement===de:!1;qp(),et?.destroy(),et=null,Ht?.destroy(),Ht=null;let m=null,y=()=>(m=xe()?ed({config:o}):Na({config:o}),m.footer),C=jg(y)??y();Tn.replaceComposer(C),Le=Tn.composer.footer;let B=m!==null&&C===m.footer;Ms=!B,Wg=B?m.setSendButtonMode:()=>{},zg(Le),Kg(Le),Gg(),Qg(),Yg(),oh(),Xg(),Id(),Jg(),nh();let z=Nr.indexOf(Wo);Wo.destroy(),Wo=Oa(tr),z>=0&&(Nr[z]=Wo),de&&(de.value=r),go(),Br(),Al(),Ps(),ji(E.isStreaming()),je.active&&ls("recording"),_r(),jf(),Wr(),no(),Sl(),d&&de?.focus()}finally{Kp=!1}}}let ca=t.ownerDocument??document;ca.addEventListener("keydown",Ff,!0);let sh=()=>{$d()},ih=()=>{ca.visibilityState==="hidden"&&$d()};typeof window<"u"&&(window.addEventListener("pagehide",sh),ca.addEventListener("visibilitychange",ih),be.push(()=>{window.removeEventListener("pagehide",sh),ca.removeEventListener("visibilitychange",ih)}));let ah="persona-attachment-drop-active",da=0,Gp=()=>{da=0,pe.classList.remove(ah)},Qs=()=>o.attachments?.enabled===!0&&Xe!==null&&!gr(),lh=r=>{!hd(r.dataTransfer)||!Qs()||(da++,da===1&&pe.classList.add(ah))},ch=r=>{!hd(r.dataTransfer)||!Qs()||(da--,da<=0&&Gp())},dh=r=>{!hd(r.dataTransfer)||!Qs()||(r.preventDefault(),r.dataTransfer.dropEffect="copy")},ph=r=>{if(!hd(r.dataTransfer)||!Qs())return;r.preventDefault(),r.stopPropagation(),Gp();let a=Array.from(r.dataTransfer.files??[]);a.length!==0&&Xe.handleFiles(a)},br=!0;pe.addEventListener("dragenter",lh,br),pe.addEventListener("dragleave",ch,br),t.addEventListener("dragover",dh,br),t.addEventListener("drop",ph,br);let nc=t.ownerDocument,uh=r=>{Qs()&&r.preventDefault()},gh=r=>{Qs()&&r.preventDefault()};nc.addEventListener("dragover",uh),nc.addEventListener("drop",gh),be.push(()=>{et?.destroy(),et=null,qp(),fo?.destroy(),fo=null,Ho?.destroy(),Ho=null,sr?.destroy(),sr=null,ir?.destroy(),ir=null,rr=null,Md=null,$d(),Di.destroy(),js&&clearTimeout(js),zr(),as?.abort(),as=null,Xe?.destroy(),Xe=null,Se.destroy(),ca.removeEventListener("keydown",Ff,!0),Ht?.destroy()}),be.push(()=>{pe.removeEventListener("dragenter",lh,br),pe.removeEventListener("dragleave",ch,br),t.removeEventListener("dragover",dh,br),t.removeEventListener("drop",ph,br),nc.removeEventListener("dragover",uh),nc.removeEventListener("drop",gh),Gp()}),be.push(()=>{E.cancel()}),Mt?be.push(()=>{Mt?.destroy()}):pn&&be.push(()=>{pn?.remove()});let Et={update(r){let a=o.toolCall,d=o.messageActions,m=o.layout?.messages,y=o.colorScheme,C=o.loadingIndicator,B=o.iterationDisplay,z=o.features?.showReasoning,q=o.features?.showToolCalls,j=o.features?.toolCallDisplay,X=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type,ge=o.features?.history?.enabled===!0,Ye=o.features?.history?.provider,it=o.getIdentityProof,lt=o.clientToken,Kt=o.contextMentions;o=tC({...o,features:i},r),i=o.features,o=hg(o),s(),_d(),La(t,o),$a(t,o),qa(t,o),mt(),ro(),o.colorScheme!==y&&fm();let Ot=vg.getForInstance(o.plugins);l.length=0,l.push(...Ot),mf(),ue=o.launcher?.enabled??!0,_e=o.launcher?.autoExpand??!1,Fn=o.features?.showReasoning??!0,Io=o.features?.showToolCalls??!0,Pr=o.features?.scrollToBottom??{};let Tt=In();yn=o.features?.scrollBehavior??{},Tt!==In()&&(io(),Sn()),Pm(),Dg(),Ut();let nn=It;if(It=o.features?.showEventStreamToggle??!1,It&&!nn){if(xt||(Z(),E.setSSEEventCallback((J,Ve)=>{o.onSSEEvent?.(J,Ve),U(J,Ve)})),!Ze&&Te){let J=o.features?.eventStream?.classNames,Ve="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J?.toggleButton?" "+J.toggleButton:"");Ze=k("button",Ve),Ze.style.width="28px",Ze.style.height="28px",Ze.style.color=mn.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let Ge=en(yC,"18px","currentColor",1.5);Ge&&Ze.appendChild(Ge);let tt=De.clearChatButtonWrapper,vt=De.closeButtonWrapper,Zt=tt||vt;Zt&&Zt.parentNode===Te?Te.insertBefore(Ze,Zt):Te.appendChild(Ze),Ze.addEventListener("click",()=>{ee?As():kd()})}}else!It&&nn&&(As(),Ze&&(Ze.remove(),Ze=null),xt?.clear(),ln?.destroy(),xt=null,ln=null,dt?.reset(),dt=null,eo=null);if(o.launcher?.enabled===!1&&Mt&&(Mt.destroy(),Mt=null),o.launcher?.enabled===!1&&pn&&(pn.remove(),pn=null),o.launcher?.enabled!==!1&&!Mt&&!pn){let{instance:J,element:Ve}=sg({config:o,plugins:l,onToggle:zf});Mt=J,J||(pn=Ve),t.appendChild(Ve)}Mt&&Mt.update(o),sa(),Hr&&o.launcher?.subtitle!==void 0&&(Hr.textContent=o.launcher.subtitle);let Je=o.layout?.header;if(Je?.layout!==Pe&&Te){let J=Je?Zc(o,Je,{showClose:Oe(),onClose:()=>at(!1,"user")}):ys({config:o,showClose:Oe(),onClose:()=>at(!1,"user")});Tn.replaceHeader(J),Te=Tn.header.element,At=Tn.header.iconHolder,nr=Tn.header.headerTitle,Hr=Tn.header.headerSubtitle,Ue=Tn.header.closeButton,Pe=Je?.layout,sa()}else if(Je){if(At&&(At.style.display=Je.showIcon===!1?"none":""),nr&&(nr.style.display=Je.showTitle===!1?"none":""),Hr&&(Hr.style.display=Je.showSubtitle===!1?"none":""),Ue){let J=Oe()&&Je.showCloseButton!==!1;Ue.style.display=J?"":"none"}if(De.clearChatButtonWrapper){let J=Je.showClearChat;if(J!==void 0){De.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:Ve}=De;Ve&&!Ve.classList.contains("persona-absolute")&&(J?Ve.classList.remove("persona-ml-auto"):Ve.classList.add("persona-ml-auto"))}}}let Vo=o.layout?.showHeader!==!1;Te&&(Te.style.display=Vo?"":"none");let So=o.layout?.showFooter!==!1;Le&&(Le.style.display=So?"":"none"),Wr(),Ut(),ue!==$?ue?at(_e,"auto"):(ye=!0,zi()):_e!==Ce&&at(_e,"auto"),Ce=_e,$=ue,la(),Zf();let Re=JSON.stringify(o.toolCall)!==JSON.stringify(a),Be=JSON.stringify(o.messageActions)!==JSON.stringify(d),fe=JSON.stringify(o.layout?.messages)!==JSON.stringify(m),pt=o.loadingIndicator?.render!==C?.render||o.loadingIndicator?.renderIdle!==C?.renderIdle||o.loadingIndicator?.showBubble!==C?.showBubble,$t=o.iterationDisplay!==B,rn=(o.features?.showReasoning??!0)!==(z??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(j)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(X);(Re||Be||fe||pt||$t||rn)&&E&&(jr++,qn(Ie,E.getMessages(),Jt));let kt=o.features?.streamAnimation?.type;if(kt!==se&&kt&&kt!=="none"){let J=Dd(kt,o.features?.streamAnimation?.plugins);J&&ya(J,t)}let ke=o.launcher??{},qt=ke.headerIconHidden??!1,zt=o.layout?.header?.showIcon,Qn=qt||zt===!1,He=ke.headerIconName,bt=ke.headerIconSize??"48px";if(At){let J=Te,Ve=J?.querySelector(".persona-flex-col");if(Qn)At.style.display="none",J&&Ve&&!J.contains(Ve)&&J.insertBefore(Ve,J.firstChild);else{if(At.style.display="",At.style.height=bt,At.style.width=bt,J&&Ve&&(J.contains(At)?At.nextSibling!==Ve&&(At.remove(),J.insertBefore(At,Ve)):J.insertBefore(At,Ve)),He){let tt=parseFloat(bt)||24,vt=he(He,tt*.6,"currentColor",1);vt?At.replaceChildren(vt):At.textContent=ke.agentIconText??"\u{1F4AC}"}else if(ke.iconUrl){let tt=At.querySelector("img");if(tt)tt.src=ke.iconUrl,tt.style.height=bt,tt.style.width=bt;else{let vt=document.createElement("img");vt.src=ke.iconUrl,vt.alt="",vt.className="persona-rounded-xl persona-object-cover",vt.style.height=bt,vt.style.width=bt,At.replaceChildren(vt)}}else{let tt=At.querySelector("svg"),vt=At.querySelector("img");(tt||vt)&&At.replaceChildren(),At.textContent=ke.agentIconText??"\u{1F4AC}"}let Ge=At.querySelector("img");Ge&&(Ge.style.height=bt,Ge.style.width=bt)}}let Ao=o.layout?.header?.showTitle,ao=o.layout?.header?.showSubtitle;if(nr&&(nr.style.display=Ao===!1?"none":""),Hr&&(Hr.style.display=ao===!1?"none":""),Ue){let J=Oe()&&o.layout?.header?.showCloseButton!==!1;if(Ue.style.display=J?"":"none",!xe()){let Gt=ke.closeButtonSize??"";Ue.style.height=Gt,Ue.style.width=Gt,Ue.style.minWidth=Gt,Ue.style.minHeight=Gt}let Ve=ke.closeButtonPlacement??"inline",{closeButtonWrapper:Ge}=De,tt=Ve==="top-right",vt=Ge?.classList.contains("persona-absolute");if(Ge&&tt!==vt)if(Ge.remove(),tt){Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Gt=Xi??pe;Gt.style.position="relative",Gt.appendChild(Ge)}else{let Gt=ke.clearChat?.placement??"inline",Qt=ke.clearChat?.enabled??!0;Ge.className=Qt&&Gt==="inline"?"":"persona-ml-auto",Te&&Te.appendChild(Ge)}if(Ue.style.color=ke.closeButtonColor||mn.actionIconColor,ke.closeButtonBackgroundColor?(Ue.style.backgroundColor=ke.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),ke.closeButtonBorderWidth||ke.closeButtonBorderColor){let Gt=ke.closeButtonBorderWidth||"0px",Qt=ke.closeButtonBorderColor||"transparent";Ue.style.border=`${Gt} solid ${Qt}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");ke.closeButtonBorderRadius?(Ue.style.borderRadius=ke.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),ke.closeButtonPaddingX?(Ue.style.paddingLeft=ke.closeButtonPaddingX,Ue.style.paddingRight=ke.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),ke.closeButtonPaddingY?(Ue.style.paddingTop=ke.closeButtonPaddingY,Ue.style.paddingBottom=ke.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom=""),Jc(Ue,ke.closeButtonIconName??"x",{iconSize:xe()?tg:void 0,iconText:ke.closeButtonIconText??"\xD7"});let Zt=ke.closeButtonTooltipText??"Close chat",lo=ke.closeButtonShowTooltip??!0;Ue.setAttribute("aria-label",Zt),Ge&&Yt({anchor:Ue,trigger:Ge,text:()=>Ue?.getAttribute("aria-label")??Zt,enabled:lo})}let{clearChatButton:We,clearChatButtonWrapper:ve}=De;if(We){let J=ke.clearChat??{},Ve=J.enabled??!0,Ge=o.layout?.header?.showClearChat,tt=Ge!==void 0?Ge:Ve,vt=J.placement??"inline";if(ve){ve.style.display=tt?"":"none";let{closeButtonWrapper:Zt}=De;!xe()&&Zt&&!Zt.classList.contains("persona-absolute")&&(tt?Zt.classList.remove("persona-ml-auto"):Zt.classList.add("persona-ml-auto"));let lo=vt==="top-right",Gt=ve.classList.contains("persona-absolute");if(!xe()&&lo!==Gt&&tt){if(ve.remove(),lo){ve.className="persona-absolute persona-top-4 persona-z-50",ve.style.right="48px";let Mo=Xi??pe;Mo.style.position="relative",Mo.appendChild(ve)}else{ve.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ve.style.right="";let Mo=De.closeButtonWrapper;Te&&Mo&&Mo.parentElement===Te?Te.insertBefore(ve,Mo):Te&&Te.appendChild(ve)}let Qt=De.closeButtonWrapper;Qt&&!Qt.classList.contains("persona-absolute")&&(lo?Qt.classList.add("persona-ml-auto"):Qt.classList.remove("persona-ml-auto"))}}if(tt){if(!xe()){let Qt=J.size??"";We.style.height=Qt,We.style.width=Qt,We.style.minWidth=Qt,We.style.minHeight=Qt}let Zt=J.iconColor??"";if(We.style.color=Zt||mn.actionIconColor,Jc(We,J.iconName??"refresh-cw",{iconSize:xe()?ng:void 0}),J.backgroundColor?(We.style.backgroundColor=J.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let Qt=J.borderWidth||"0px",Mo=J.borderColor||"transparent";We.style.border=`${Qt} solid ${Mo}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");J.borderRadius?(We.style.borderRadius=J.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),J.paddingX?(We.style.paddingLeft=J.paddingX,We.style.paddingRight=J.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),J.paddingY?(We.style.paddingTop=J.paddingY,We.style.paddingBottom=J.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let lo=J.tooltipText??"Clear chat",Gt=J.showTooltip??!0;We.setAttribute("aria-label",lo),ve&&Yt({anchor:We,trigger:ve,text:()=>We?.getAttribute("aria-label")??lo,enabled:Gt})}}let Fe=o.actionParsers&&o.actionParsers.length?o.actionParsers:[wg],ut=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[za.message,za.messageAndClick];we=Sg({parsers:Fe,handlers:ut,getSessionMetadata:V,updateSessionMetadata:ae,emit:w.emit,documentRef:typeof document<"u"?document:null}),Jt=wC(o,we,Cs),_w(),E.updateConfig(o),(o.features?.history?.enabled===!0!==ge||o.features?.history?.provider!==Ye||o.getIdentityProof!==it||o.clientToken!==lt)&&(An({restoreFocus:!1}),sf()),hr(),Fl(),qn(Ie,E.getMessages(),Jt),Ps(),Al(),Ww(),ji(E.isStreaming()),Kt!==o.contextMentions&&rh();let vr=o.voiceRecognition?.enabled===!0,jt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),_n=o.voiceRecognition?.provider?.type==="runtype";if(vr&&(jt||_n))if(!re||!Pn){let J=li(o);if(J){re=J.button,Pn=J.wrapper;let Ve=uo&&uo.parentElement===Ka?uo:null;Ka?Ka.insertBefore(Pn,Ve):to?.appendChild(Pn),et&&(et.micButton=re),et?.addListener(re,"click",Vp),re.disabled=E.isStreaming()}}else{let J=o.voiceRecognition??{},Ve=o.sendButton??{},Ge=J.iconName??"mic",tt=J.iconSize,vt=parseFloat(tt??"")||un;re.classList.add(Dn),re.classList.toggle(co,!tt),re.style.width=tt??"",re.style.height=tt??"",re.style.minWidth=tt??"",re.style.minHeight=tt??"";let Zt=J.iconColor??Ve.textColor;re.innerHTML="";let lo=he(Ge,vt,Zt||"currentColor",1.5);lo?re.appendChild(lo):re.textContent="\u{1F3A4}";let Gt=J.backgroundColor??Ve.backgroundColor;Gt?re.style.backgroundColor=Gt:re.style.backgroundColor="",Zt?re.style.color=Zt:re.style.color="var(--persona-text, #111827)",J.borderWidth?(re.style.borderWidth=J.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),J.borderColor?re.style.borderColor=J.borderColor:re.style.borderColor="",J.paddingX?(re.style.paddingLeft=J.paddingX,re.style.paddingRight=J.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),J.paddingY?(re.style.paddingTop=J.paddingY,re.style.paddingBottom=J.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let Qt=J.tooltipText??"Start voice recognition",Mo=J.showTooltip??!1;re.setAttribute("aria-label",Qt),Pn&&Yt({anchor:re,trigger:Pn,text:()=>re?.getAttribute("aria-label")??Qt,enabled:Mo}),Pn.style.display="",re.disabled=E.isStreaming()}else re&&Pn&&(Pn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?E.isVoiceActive()&&E.toggleVoice():wo&&yr());if(o.attachments?.enabled===!0){if(!vn||!wt){let J=o.attachments??{};Cn||(Cn=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Cn.style.display="none",(de.parentElement??to).insertBefore(Cn,de)),ft||(ft=document.createElement("input"),ft.type="file",ft.accept=(J.allowedTypes??Qo).join(","),ft.multiple=(J.maxFiles??4)>1,ft.style.display="none",ft.setAttribute("aria-label","Attach files"),(de.parentElement??to).insertBefore(ft,de)),vn=k("div","persona-send-button-wrapper"),wt=k("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Dn} ${co}`),wt.type="button",wt.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let Ve=J.buttonIconName??"paperclip";wt.style.fontSize="18px",wt.style.lineHeight="1";let Ge=he(Ve,un,"currentColor",1.5);Ge?wt.appendChild(Ge):wt.textContent="\u{1F4CE}",wt.addEventListener("click",vt=>{vt.preventDefault(),ft?.click()}),vn.appendChild(wt);let tt=J.buttonTooltipText??"Attach file";Yt({anchor:wt,trigger:vn,text:()=>wt?.getAttribute("aria-label")??tt}),vd?vd.append(vn):to.appendChild(vn),et&&(et.attachmentButton=wt,et.attachmentInput=ft??void 0,et.attachmentPreviews=Cn??void 0),!Xe&&ft&&Cn&&(Xe=Ea.fromConfig(J,Ng),Xe.setPreviewsContainer(Cn),et?.addListener(ft,"change",async()=>{Xe&&ft?.files&&(await Xe.handleFileSelect(ft.files),ft.value="")}))}else{vn.style.display="";let J=o.attachments??{};ft&&(ft.accept=(J.allowedTypes??Qo).join(","),ft.multiple=(J.maxFiles??4)>1),Xe&&Xe.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(pe.querySelector(".persona-attachment-drop-overlay")?.remove(),pe.appendChild(SC(o.attachments?.dropOverlay)),wt){let J=o.attachments??{},Ve=J.buttonTooltipText??"Attach file";wt.setAttribute("aria-label",Ve),wt.textContent="";let Ge=he(J.buttonIconName??"paperclip",un,"currentColor",1.5);Ge?wt.appendChild(Ge):wt.textContent="\u{1F4CE}",vn&&Yt({anchor:wt,trigger:vn,text:()=>wt?.getAttribute("aria-label")??Ve})}}else vn&&(vn.style.display="none"),Xe&&Xe.clearAttachments(),pe.querySelector(".persona-attachment-drop-overlay")?.remove();let St=o.sendButton??{},Qp=St.useIcon??!1,ps=St.iconText??"\u2191",oc=St.iconName,fh=St.tooltipText??"Send message",YS=St.showTooltip??!1,pa=St.size,XS=parseFloat(pa??"")||Tu,rc=St.backgroundColor,ua=St.textColor;if(Qp){if(Ee.style.width=pa??"",Ee.style.height=pa??"",Ee.style.minWidth=pa??"",Ee.style.minHeight=pa??"",Ee.style.fontSize="18px",Ee.style.lineHeight="1",ua?Ee.style.color=ua:Ee.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!E.isStreaming())if(Ee.innerHTML="",oc){let J=parseFloat(St.iconSize??"")||Math.round(XS*.5),Ve=ua?.trim()||"currentColor",Ge=St.iconStrokeWidth??2,tt=he(oc,J,Ve,Ge),vt=he(St.stopIconName??"square",J,Ve,Ge);tt&&vt?Ee.appendChild(ku(tt,vt)):tt?Ee.appendChild(tt):Ee.textContent=ps}else Ee.textContent=ps;Ee.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Dn}`,rc?(Ee.style.backgroundColor=rc,Ee.classList.remove("persona-bg-persona-primary")):(Ee.style.backgroundColor="",Ee.classList.add("persona-bg-persona-primary"))}else Ee.textContent=o.copy?.sendButtonLabel??"Send",Ee.style.width="",Ee.style.height="",Ee.style.minWidth="",Ee.style.minHeight="",Ee.style.fontSize="",Ee.style.lineHeight="",Ee.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",rc?(Ee.style.backgroundColor=rc,Ee.classList.remove("persona-bg-persona-accent")):Ee.classList.add("persona-bg-persona-accent"),ua?Ee.style.color=ua:Ee.classList.add("persona-text-white");St.borderWidth?(Ee.style.borderWidth=St.borderWidth,Ee.style.borderStyle="solid"):(Ee.style.borderWidth="",Ee.style.borderStyle=""),St.borderColor?Ee.style.borderColor=St.borderColor:Ee.style.borderColor="",St.paddingX?(Ee.style.paddingLeft=St.paddingX,Ee.style.paddingRight=St.paddingX):(Ee.style.paddingLeft="",Ee.style.paddingRight=""),St.paddingY?(Ee.style.paddingTop=St.paddingY,Ee.style.paddingBottom=St.paddingY):(Ee.style.paddingTop="",Ee.style.paddingBottom=""),E.isStreaming()||Ee.setAttribute("aria-label",fh),Sl(),uo&&Yt({anchor:Ee,trigger:uo,text:()=>Ee.getAttribute("aria-label")??fh,enabled:YS}),em();let hh=qc(Se.getState().activeModeIds,o.composer?.modes);Se.setActiveModeIds(hh),ws().length>0!==!!Ho&&Id(),Ho?.render(hh,ws());for(let J of[...Ss.keys()])$c(J,o.composer?.modeGroups)||Ss.delete(J);Ss.forEach(J=>J.repaint()),rr?.repaint(),fo?.resolve();let sc=Tr(o,xe());if(Od(),sc){Ie.style.maxWidth=sc,Ie.style.marginLeft="auto",Ie.style.marginRight="auto",Ie.style.width="100%",kn.style.maxWidth=sc,kn.style.marginLeft="auto",kn.style.marginRight="auto",kn.style.width="100%";for(let J of[to,tr,Cn,ot])J&&(J.style.maxWidth=sc,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{Ie.style.maxWidth="",Ie.style.marginLeft="",Ie.style.marginRight="",Ie.style.width="",kn.style.maxWidth="",kn.style.marginLeft="",kn.style.marginRight="",kn.style.width="";for(let J of[to,tr,Cn,ot])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let Cr=o.statusIndicator??{},JS=Cr.visible??!0;if(ot.style.display=JS?"":"none",E){let J=E.getStatus();tn(ot,(Ge=>Ge==="idle"?Cr.idleText??Dt.idle:Ge==="connecting"?Cr.connectingText??Dt.connecting:Ge==="connected"?Cr.connectedText??Dt.connected:Ge==="error"?Cr.errorText??Dt.error:Dt[Ge])(J),Cr,J)}ot.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ZS=Cr.align==="left"?"persona-text-left":Cr.align==="center"?"persona-text-center":"persona-text-right";ot.classList.add(ZS),Pd(),Yd(),no(),Ae()},open(){Oe()&&at(!0,"api")},close(){Oe()&&at(!1,"api")},toggle(){Oe()&&at(!ye,"api")},reconnect(){E.reconnectNow()},clearChat(){Ro=!1,E.clearMessages(),Bt.clear(),Sn();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),G?.clear&&ml(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ie={},we.syncFromMetadata(),Xe?.clearAttachments(),hl(),xs(void 0),mo(void 0),zr(),xt?.clear(),dt?.reset(),H?.update()},setMessage(r){return!de||E.isStreaming()||gr()?!1:(!ye&&Oe()&&at(!0,"system"),de.value=r,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(r){if(E.isStreaming()||Xr())return!1;let a=r?.trim()||de.value.trim();return a?(!ye&&Oe()&&at(!0,"system"),de.value="",de.style.height="auto",go(),Xl(a,{consumeDraft:!1}),!0):!1},getComposerState(){return Se.getState()},setQuote(r){let a=r?.text?.trim();a&&mo({...r,text:a})},clearQuote(){mo(void 0)},startVoiceRecognition(){return E.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(E.isVoiceActive()||(!ye&&Oe()&&at(!0,"system"),je.manuallyDeactivated=!1,so(),E.toggleVoice().then(()=>{je.active=E.isVoiceActive(),Oo("user"),E.isVoiceActive()&&Gs()})),!0):wo?!0:qf()?(!ye&&Oe()&&at(!0,"system"),je.manuallyDeactivated=!1,so(),Zl("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?E.isVoiceActive()?(E.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,so(),Oo("user"),jo()}),!0):!1:wo?(je.manuallyDeactivated=!0,so(),yr("user"),!0):!1},injectMessage(r){return!ye&&Oe()&&at(!0,"system"),E.injectMessage(r)},injectAssistantMessage(r){!ye&&Oe()&&at(!0,"system");let a=E.injectAssistantMessage(r);return gt&&(gt=!1,Zn&&(clearTimeout(Zn),Zn=null),setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)),a},injectUserMessage(r){return!ye&&Oe()&&at(!0,"system"),E.injectUserMessage(r)},injectSystemMessage(r){return!ye&&Oe()&&at(!0,"system"),E.injectSystemMessage(r)},injectMessageBatch(r){return!ye&&Oe()&&at(!0,"system"),E.injectMessageBatch(r)},injectComponentDirective(r){return!ye&&Oe()&&at(!0,"system"),E.injectComponentDirective(r)},injectTestMessage(r){!ye&&Oe()&&at(!0,"system"),E.injectTestEvent(r)},async connectStream(r,a){return E.connectStream(r,a)},__pushEventStreamEvent(r){It&&(Z(),U(r.type,r.payload))},showEventStream(){It&&kd()},hideEventStream(){ee&&As()},isEventStreamVisible(){return ee},listConversations(r){return E.listConversations(r)},getActiveConversationId(){return E.getActiveConversationId()},openConversation(r,a){return Lp(r,{focusComposer:a?.focus===!0})},startNewConversation(r){return Hp({focusComposer:r?.focus===!0})},deleteConversation(r){return Hf(r)},renameConversation(r,a){return Rp(r,{title:a})},setConversationStarred(r,a){return Rp(r,{starred:a})},clearConversationHistory(r){return Rf(r)},resetHistoryIdentity(){return Wf()},getHistoryIdentityStatus(){return Wn?Wn.getIdentityStatus():mp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(r){return ra({...r?.returnSurface?{returnSurface:r.returnSurface}:{},...r?.focus!==void 0?{focus:r.focus}:{}})},hideHistory(r){An(r?.restoreFocus!==void 0?{restoreFocus:r.restoreFocus}:void 0)},isHistoryVisible(){return te},showArtifacts(){hn(o)&&(Ro=!1,Es=!0,ro(),ze?.setMobileOpen(!0))},hideArtifacts(){hn(o)&&(Ro=!0,ro())},upsertArtifact(r){return hn(o)?(wr(o.features?.artifacts,{artifactType:r.artifactType,...r.artifactType==="markdown"&&r.file?{file:r.file}:{},...r.presentation?{presentation:r.presentation}:{}})==="panel"&&(Ro=!1,Es=!0),E.upsertArtifact(r)):null},selectArtifact(r){hn(o)&&E.selectArtifact(r)},clearArtifacts(){hn(o)&&E.clearArtifacts()},getArtifacts(){return E?.getArtifacts()??[]},getSelectedArtifactId(){return E?.getSelectedArtifactId()??null},focusInput(){return ue&&!ye&&!xe()||!de?!1:(de.focus(),!0)},async resolveApproval(r,a,d){let y=E.getMessages().find(C=>C.variant==="approval"&&C.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,d)},setFollowUpSuggestions(r){sw(r)},clearFollowUpSuggestions(){km()},getMessages(){return E.getMessages()},getStatus(){return E.getStatus()},getPersistentMetadata(){return{...ie}},updatePersistentMetadata(r){ae(r)},on(r,a){return w.on(r,a)},off(r,a){w.off(r,a)},isOpen(){return Oe()&&ye},isVoiceActive(){return je.active},toggleReadAloud(r){E.toggleReadAloud(r)},stopReadAloud(){E.stopSpeaking()},getReadAloudState(r){return E.getReadAloudState(r)},onReadAloudChange(r){return E.onReadAloudChange(r)},getState(){return{open:Oe()&&ye,launcherEnabled:ue,voiceActive:je.active,streaming:E.isStreaming()}},showCSATFeedback(r){!ye&&Oe()&&at(!0,"system");let a=Ie.querySelector(".persona-feedback-container");a&&a.remove();let d=fC({onSubmit:async(m,y)=>{E.isClientTokenMode()&&await E.submitCSATFeedback(m,y),r?.onSubmit?.(m,y)},onDismiss:r?.onDismiss,...r});Ie.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(r){!ye&&Oe()&&at(!0,"system");let a=Ie.querySelector(".persona-feedback-container");a&&a.remove();let d=hC({onSubmit:async(m,y)=>{E.isClientTokenMode()&&await E.submitNPSFeedback(m,y),r?.onSubmit?.(m,y)},onDismiss:r?.onDismiss,...r});Ie.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(r,a){return E.submitCSATFeedback(r,a)},async submitNPSFeedback(r,a){return E.submitNPSFeedback(r,a)},destroy(){ap(),ts!=null&&(clearInterval(ts),ts=null),be.forEach(r=>r()),Ke.remove(),Vt?.remove(),Mt?.destroy(),pn?.remove(),Fr&&Ue.removeEventListener("click",Fr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let r=window.AgentWidgetBrowser,a={controller:Et,getMessages:Et.getMessages,getStatus:Et.getStatus,getMetadata:Et.getPersistentMetadata,updateMetadata:Et.updatePersistentMetadata,clearHistory:()=>Et.clearChat(),setVoiceActive:d=>d?Et.startVoiceRecognition():Et.stopVoiceRecognition()};window.AgentWidgetBrowser=a,be.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=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.focusInput()};if(window.addEventListener("persona:focusInput",a),be.push(()=>{window.removeEventListener("persona:focusInput",a)}),It){let j=se=>{let ge=se.detail;(!ge?.instanceId||ge.instanceId===r)&&Et.showEventStream()},X=se=>{let ge=se.detail;(!ge?.instanceId||ge.instanceId===r)&&Et.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",X),be.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",X)})}let d=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.showHistory()},m=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.hideHistory()};window.addEventListener("persona:showHistory",d),window.addEventListener("persona:hideHistory",m),be.push(()=>{window.removeEventListener("persona:showHistory",d),window.removeEventListener("persona:hideHistory",m)});let y=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.showArtifacts()},C=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.hideArtifacts()},B=j=>{let X=j.detail;X?.instanceId&&X.instanceId!==r||X?.artifact&&Et.upsertArtifact(X.artifact)},z=j=>{let X=j.detail;X?.instanceId&&X.instanceId!==r||typeof X?.id=="string"&&Et.selectArtifact(X.id)},q=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",B),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",q),be.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",B),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",q)})}let Gn=pT(o.persistState);if(Gn&&Oe()){let r=uT(Gn.storage),a=`${Gn.keyPrefix}widget-open`,d=`${Gn.keyPrefix}widget-voice`,m=`${Gn.keyPrefix}widget-voice-mode`;if(r){let y=Gn.persist?.openState&&r.getItem(a)==="true",C=Gn.persist?.voiceState&&r.getItem(d)==="true",B=Gn.persist?.voiceState&&r.getItem(m)==="true";if(y&&(Mt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Et.open(),setTimeout(()=>{if(C||B)Et.startVoiceRecognition();else if(Gn.persist?.focusInput){let z=t.querySelector("textarea");z&&z.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",z=>{r.setItem(d,z.active?"true":"false")}),w.on("user:message",z=>{r.setItem(m,z.viaVoice?"true":"false")})),Gn.clearOnChatClear){let z=()=>{r.removeItem(a),r.removeItem(d),r.removeItem(m)},q=()=>z();window.addEventListener("persona:clear-chat",q),be.push(()=>{window.removeEventListener("persona:clear-chat",q)})}}}if(I&&Oe()&&(Mt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Et.open()},0)),Bs(),!iw){let r=ic(()=>{E&&(jr++,Bt.clear(),qn(Ie,E.getMessages(),Jt))});be.push(r)}A=()=>{E&&(jr++,Bt.clear(),qn(Ie,E.getMessages(),Jt))},E.getMessages().length>0&&wl(),x=()=>{E&&(jr++,Bt.clear(),qn(Ie,E.getMessages(),Jt))};let GS=Hh(()=>{E&&(jr++,Bt.clear(),qn(Ie,E.getMessages(),Jt))});be.push(GS);let QS=ug(()=>{E&&(jr++,Bt.clear(),qn(Ie,E.getMessages(),Jt),Jo()?.updateInlineArtifactBlocks(Ie,$n.artifacts,{suppressTransition:!0}),ro())});return be.push(QS),Et};var AC=(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},fT=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},hT=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},yT=(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.")},MC=(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"},Lg=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=""},EC=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Lg(t)},kg=t=>{t.style.transition=""},Pg=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=""},Ig=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=""},bT=(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))},vT=(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)},CT=t=>{let e=di(t),n=e.components?.panel,o=(s,i)=>s==null||s===""?i:gn(e,s)??s;return{inset:o(n?.inset,zc),canvasBackground:o(n?.canvasBackground,jc)}},TC=(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 p=Jn(i),u=p.reveal==="push",g=c!=null,f=c?.inset??"",v=c?.canvasBackground??"";bT(t,e,n,o,u),vT(t,e,n,o,p.side,u),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=p.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,M=i?.launcher?.mobileFullscreen??!0,A=i?.launcher?.mobileBreakpoint??640,T=h!=null?h.innerWidth<=A:!1;if(M&&T&&l){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Pg(e),kg(o),EC(o),Ig(n),yd(s,o),TC(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"),EC(o),fT(o,p.maxHeight),TC(o,g&&l,f,v),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Pg(e),kg(o),Ig(n),yd(s,o);let P=p.animate?"transform 180ms ease":"none",K=p.side==="right"?"translateX(100%)":"translateX(-100%)",x=l?"translateX(0)":K;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=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.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",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",kg(o),Lg(o),yd(s,o);let P=AC(p.width,t.clientWidth),K=Math.max(0,t.clientWidth),x=p.animate?"margin-left 180ms ease":"none",L=p.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=`${K+P}px`,e.style.transition=x,e.style.marginLeft=`${L}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${K}px`,n.style.maxWidth=`${K}px`,n.style.minWidth=`${K}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.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="",Pg(e),Lg(o),Ig(n),yd(s,o);let P=p.reveal==="emerge";P?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let K=l?p.width:"0px",x=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${g?", padding 180ms ease":""}`:"none",L=!l;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${K}`,o.style.width=K,o.style.maxWidth=K,o.style.minWidth=K,o.style.minHeight="0",hT(o,p.maxHeight),o.style.overflow=P||L?"hidden":"visible",o.style.transition=x,P){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let w=g?`calc(${AC(p.width,t.clientWidth)}px - (2 * ${f}))`:p.width;s.style.width=w,s.style.minWidth=w,s.style.maxWidth=w,s.style.boxSizing="border-box"}}},ST=(t,e)=>{let n=t.ownerDocument.createElement("div");return MC(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){MC(n,o)},destroy(){n.remove()}}},xT=(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"),p=n.createElement("div"),u=n.createElement("aside"),g=n.createElement("div"),f=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;c.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",u.appendChild(g),o.insertBefore(l,t),p.appendChild(t);let v=null,h=()=>{v?.disconnect(),v=null},M=null,A=()=>{M=e?.launcher?.detachedPanel===!0?CT(e):null};A();let T=()=>{wT(l,c,p,u,g,e,f,M)},F=null,P=()=>{F?.(),F=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(F=Vc(()=>{A(),T()}))},K=()=>{h(),Jn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(v=new ResizeObserver(()=>{T()}),v.observe(l)))},x=!1,L=()=>{T(),K(),f&&!x&&l.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,yT(l,Jn(e)))},w=l.ownerDocument.defaultView,_=()=>{L()};return w?.addEventListener("resize",_),Jn(e).reveal==="push"?(c.appendChild(p),c.appendChild(u),l.appendChild(c)):(l.appendChild(p),l.appendChild(u)),L(),P(),{mode:"docked",host:g,shell:l,syncWidgetState(G){let ie=G.launcherEnabled?G.open:!0;f!==ie&&(f=ie,L())},updateConfig(G){e=G,(e?.launcher?.enabled??!0)===!1&&(f=!0),A(),L(),P()},destroy(){w?.removeEventListener("resize",_),F?.(),F=null,h(),o.isConnected&&(i&&i.parentNode===o?o.insertBefore(t,i):o.appendChild(t)),l.remove()}}},kC=(t,e)=>Rt(e)?xT(t,e):ST(t,e);var ja={desktop:{w:1280,h:800},mobile:{w:390,h:844}},PC=.15,IC=1.5,Hg="persona-preview-shell-theme",AT={load:()=>null,save:()=>{},clear:()=>{}},MT=["How do I get started?","Pricing & plans","Talk to support"];function Rg(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function ET(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 LC(t){let e=ET(t);return`* { box-sizing: border-box; }
|
|
128
|
+
`)}if(!m&&!r){let ve="max-height: -moz-available !important; max-height: stretch !important;",Fe=a?"":"padding-top: 1.25em !important;",ut=a?"":`z-index: ${o.launcher?.zIndex??an} !important;`;Ke.style.cssText+=ve+Fe+ut}Ad(),Ao()},Dd=()=>{t.style.setProperty("--persona-content-max-width",Tr(o,xe()))},gm=!1,mm=()=>{let r=Nu(o,xe());xe()&&o.composer?.placement&&o.debug===!0&&!gm&&(gm=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let a=Xo(o);t.setAttribute("data-persona-composer-placement",r),t.setAttribute("data-persona-conversation-state",Ya),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",a.composerGap??Gc),Ja()},fm=()=>{if(xe())return;let r=Rt(o),a=o.launcher?.sidebarMode??!1;if(r||a||(o.launcher?.fullHeight??!1)||!ue)return;let m=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,C=o.launcher?.mobileBreakpoint??640;if(y&&m.innerWidth<=C)return;let B=m.innerHeight,z=64,q=o.launcher?.heightOffset??0,j=Math.max(200,B-z),X=Math.min(640,j);Me.style.height=`${Math.max(200,X-q)}px`};Od(),La(t,o),$a(t,o),qa(t,o),Dd(),mm(),_r=()=>{Od(),fm(),La(t,o),$a(t,o),qa(t,o),Dd(),mm(),tl?t.style.setProperty("--persona-artifact-welded-outer-radius",tl):t.style.removeProperty("--persona-artifact-welded-outer-radius"),mt(),Ae()};let be=[];be.push(()=>{am=!0}),be.push(()=>{p.forEach(r=>r()),c.destroy()}),be.push(()=>{document.removeEventListener("keydown",dm)}),be.push(()=>{Pi!==null&&clearTimeout(Pi)});let yo=null,bo=null;be.push(()=>{yo?.(),yo=null,bo?.(),bo=null}),Hi&&be.push(()=>{Hi?.disconnect(),Hi=null}),be.push(()=>{Bi?.(),Bi=null,_d(),ht&&(ht.remove(),ht=null),ze?.element.style.removeProperty("width"),ze?.element.style.removeProperty("maxWidth"),ze?.destroy()}),It&&be.push(()=>{Va=!0,eo=null,b!==null&&(cancelAnimationFrame(b),b=null),H?.destroy(),H=null,xt?.destroy(),xt=null,ln=null});let Dr=null,hm=()=>{Dr&&(Dr(),Dr=null),o.colorScheme==="auto"&&(Dr=Kc(()=>{La(t,o)}))};hm(),be.push(()=>{Dr&&(Dr(),Dr=null)}),be.push(()=>{M=!0,h?.()}),be.push(()=>{P=!0});let ym=!1;be.push(()=>{ym=!0});let Nd=(r,a)=>{let d=ma(r,a);return d||!jh.includes(r)?d:(cv().then(m=>{if(ym)return;eu(m.wipe),eu(m.glyphCycle);let y=ma(r,a);y&&ya(y,t)}).catch(()=>{}),null)},cl=o.features?.streamAnimation;if(cl?.type&&cl.type!=="none"){let r=Nd(cl.type,cl.plugins);r&&ya(r,t),be.push(()=>Vh(t))}let Wo=Oa(tr),bm=Oa(vd),vm=Oa(Mi),Nr=[Wo,bm,vm];be.push(()=>{Nr.forEach(r=>r.destroy())});let Fr=null,E,Ur=null,Cm=!1,wm=0,Sm=null,xm=r=>r.reduce((a,d)=>d.role==="user"?a+1:a,0),Am=r=>{for(let a=r.length-1;a>=0;a--)if(wa(r[a]))return r[a].id??null;return null},Mm=!1,sw=()=>{Mm||o.debug!==!0||(Mm=!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".'))},Em=!1,Tm=!1,km=(r,a)=>{Em||o.debug!==!0||!a.enabled||a.expose||Cm||Tm&&(E.isStreaming()||r.some(wa)||(Em=!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.")))},Ps=r=>{if(!E)return;let a=r??E.getMessages(),d=j=>{j.render([],E,de,a)},m=j=>{Nr.forEach(X=>{X!==j&&d(X)})};Ur&&(xm(a)>wm||Am(a)!==Sm)&&(Ur=null);let y=Mr(o);km(a,y);let C=y.enabled?Sy(a):null,B=Ur??C,z=Ur?"host":"agent";if(B){let j=o.suggestions?.followUps,X=j?.placement??(j?"auto":"composer"),ge=(X==="auto"?xe()?"composer":"after-message":X)==="after-message"?vm:Wo;m(ge),ge.render(B,E,de,a,o.suggestionChipsConfig,{source:z,surface:"followUp",variant:j?.variant??"chip",behavior:j?.behavior??"send",overflow:j?.overflow??"wrap",maxItems:j?.maxItems??4,config:o,plugins:l,submitPrompt:Yl});return}if(a.some(j=>j.role==="user")){Nr.forEach(d);return}let q=o.suggestions?.starters;if(q){let j=mi(Xo(o),a),X=q.placement??"auto",se=X==="auto"?j?"welcome":"composer":X;if(se==="welcome"&&!j){sw(),Nr.forEach(d);return}let ge=se==="welcome"?bm:Wo;m(ge),ge.render(q.items??o.suggestionChips,E,de,a,o.suggestionChipsConfig,{surface:"starter",variant:q.variant??"card",behavior:q.behavior??"send",overflow:q.overflow??"wrap",maxItems:q.maxItems??4,config:o,plugins:l,submitPrompt:Yl});return}m(Wo),Wo.render(o.suggestionChips,E,de,a,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:l,submitPrompt:Yl})},Pm=()=>{Ur&&(Ur=null,Ps())},iw=r=>{let a=Array.isArray(r)?[...r]:[];if(!a.length){Pm();return}let d=E?E.getMessages():[];Ur=a,Cm=!0,wm=xm(d),Sm=Am(d),Ps(d)},Ln=!1,Bt=sv(),Is=new Map,$r=new Map,ar=new Map,qr=null,lr=null;function zr(){if(!qr)return;let r=qr;qr=null,lr?.destroy(),lr=null,Bt.delete(r),pe.querySelector(`#wrapper-${r}`)?.removeAttribute("data-preserve-runtime"),E&&qn(Ie,E.getMessages(),Jt)}let jr=0,aw=Ys()!==null,Hn=Fh(),Rn=0,cr=null,wn=!1,dl=!1,dr=0,Ft=null,Vr=null,Fd=!1,Ls=!1,Kr=null,_i=!0,pl=!1,Hs=null,ul=!1,Gr=()=>{ul=!0,pw()},Ud=null,lw=4,Bo=24,cw=80,dw=1e3,_o=null,Im=()=>{t.setAttribute("data-persona-scrollbar",wd()),wd()!=="on-scroll"&&(_o!==null&&clearTimeout(_o),_o=null,ne.removeAttribute("data-persona-scrollbar-visible"))},pw=()=>{wd()==="on-scroll"&&(ne.setAttribute("data-persona-scrollbar-visible",""),_o!==null&&clearTimeout(_o),_o=setTimeout(()=>{_o=null,gs(ne,Bo)&&ne.removeAttribute("data-persona-scrollbar-visible")},dw))};Im(),be.push(()=>{_o!==null&&clearTimeout(_o)});let $d=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};em=()=>je.active,no();let Lm=o.voiceRecognition?.autoResume??!1,Oo=r=>{w.emit("voice:state",{active:je.active,source:r,timestamp:Date.now()})},so=()=>{ae(r=>({...r,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},uw=()=>{if(o.voiceRecognition?.enabled===!1)return;let r=kg(ie.voiceState),a=!!r.active,d=Number(r.timestamp??0);je.manuallyDeactivated=!!r.manuallyDeactivated,a&&Date.now()-d<pT&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?E.toggleVoice().then(()=>{je.active=E.isVoiceActive(),Oo("restore"),E.isVoiceActive()&&Gs()}):Zl("restore"))},1e3)},gw=()=>E?wC(E.getMessages()).filter(r=>!r.__skipPersist):[],gl=null,Hm=(r,a)=>{typeof console<"u"&&console.error(r,a)},ml=(r,a)=>{let d=()=>{try{let B=r();return!B||typeof B.then!="function"?null:Promise.resolve(B).catch(z=>{Hm(a,z)})}catch(B){return Hm(a,B),null}},m=gl,y=m?m.then(()=>d()??void 0):d();if(!y)return;let C=y.finally(()=>{gl===C&&(gl=null)});gl=C};function Oi(r){if(!G?.save)return;let d={messages:r?wC(r):E?gw():[],metadata:ie,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId,...Qr?{draft:Qr}:{}};ml(()=>G.save(d),"[AgentWidget] Failed to persist state:")}let Qr,fl=()=>!G?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Di=_b({write:()=>{if(!fl())return;let r=Se.getState(),a=Wb({text:r.text,mentionRefs:r.mentionRefs,contentSegments:_p(),selectedModelId:r.selectedModelId,activeModeIds:r.activeModeIds,quote:r.quote});JSON.stringify(a)!==JSON.stringify(Qr)&&(Qr=a,Oi())}});function Rm(){fl()&&Di.schedule()}function qd(){Di.flush()}function Wm(r){if(!fl())return;let a=Bb(r,{mentionSourceIds:(o.contextMentions?.sources??[]).map(d=>d.id),modelIds:(o.composer?.models??[]).map(d=>d.id),modes:o.composer?.modes??[]});a&&(Qr=r,de&&!de.value&&(de.value=a.text,de.dispatchEvent(new Event("input",{bubbles:!0})),go()),a.selectedModelId&&(Se.setSelectedModelId(a.selectedModelId),rr?.repaint()),Za(a.activeModeIds??[]),a.quote&&mo(a.quote),Di.cancel())}function hl(){Di.cancel(),Qr&&(Qr=void 0,fl()&&Oi())}let Rs=null,Bm=()=>Ke.querySelector("#persona-scroll-container")||ne,Ws=()=>{Rs!==null&&(cancelAnimationFrame(Rs),Rs=null),wn=!1},_m=()=>{cr!==null&&(cancelAnimationFrame(cr),cr=null),dl=!1,Ws()},mw=()=>Ln&&jd()&&(In()!=="anchor-top"||Og()),zd=()=>{let r=Ei()||"Jump to latest",a=mw();Wt.toggleAttribute("data-persona-scroll-to-bottom-streaming",a),dr>0?(Rr.textContent=String(dr),Rr.style.display="",Wt.setAttribute("aria-label",`${r} (${dr} new)`)):(Rr.textContent="",Rr.style.display="none",Wt.setAttribute("aria-label",a?`${r} (response streaming below)`:r))},Om=()=>{dr!==0&&(dr=0,zd())},fw=()=>{let r=Ft?.spacerHeight??0;return r<=0?gs(ne,Bo):Cl(r)-ne.scrollTop-ne.clientHeight<=Bo},jd=()=>or()?!Hn.isFollowing():!fw(),Vd=()=>!!E&&E.getMessages().length>0,Ut=()=>{if(!qC()||Lr()){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==pe&&pe.appendChild(Wt),Wr();let a=Ko(ne)>0&&jd()&&Vd();a?zd():Om(),Wt.style.display=a?"":"none"},Ni=()=>{Hn.pause()&&(_m(),Ut())},Sn=()=>{Hn.resume(),Om(),Ut()},pr=(r=!1)=>{or()&&Vd()&&Hn.isFollowing()&&(!r&&!Ln||(cr!==null&&(cancelAnimationFrame(cr),cr=null),dl=!0,cr=requestAnimationFrame(()=>{cr=null,dl=!1,Hn.isFollowing()&&hw(Bm(),r?220:140)})))},Dm=(r,a,d,m=()=>!0)=>{let y=r.scrollTop,C=a(),B=C-y;if(Ws(),Math.abs(B)<1){wn=!0,r.scrollTop=C,Rn=r.scrollTop,wn=!1;return}let z=performance.now();wn=!0;let q=X=>1-Math.pow(1-X,3),j=X=>{if(!m()){Ws();return}let se=a();se!==C&&(C=se,B=C-y);let ge=X-z,Ye=Math.min(ge/d,1),it=q(Ye),lt=y+B*it;r.scrollTop=lt,Rn=r.scrollTop,Ye<1?Rs=requestAnimationFrame(j):(r.scrollTop=C,Rn=r.scrollTop,Rs=null,wn=!1)};Rs=requestAnimationFrame(j)},hw=(r,a=500)=>{let d=Ko(r)-r.scrollTop;if(Math.abs(d)<1){Rn=r.scrollTop;return}if(Math.abs(d)>=cw){Ws(),wn=!0,r.scrollTop=Ko(r),Rn=r.scrollTop,wn=!1;return}Dm(r,()=>Ko(r),a,()=>Hn.isFollowing())},yl=()=>{if(!Vd()){Ut();return}let r=Bm();wn=!0,r.scrollTop=Ko(r),Rn=r.scrollTop,wn=!1,Ut()},Yr=r=>{let a=0,d=r;for(;d&&d!==ne;)a+=d.offsetTop,d=d.offsetParent;return a},yw=()=>{let r=ne.getRootNode();return(typeof r.getSelection=="function"?r.getSelection():null)??ne.ownerDocument.getSelection()},bl=()=>qh(yw(),ne),Kd=()=>{if(zC()!=="last-user-turn")return!1;let r=E?.getMessages()??[];if(r.length<2)return!1;let a=[...r].reverse().find(C=>C.role==="user");if(!a)return!1;let d=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a.id):a.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=ne.querySelector(`[data-message-id="${d}"]`);if(!m)return!1;let y=Math.min(Math.max(0,Yr(m)-Ti()),Ko(ne));return wn=!0,ne.scrollTop=y,Rn=ne.scrollTop,wn=!1,In()==="follow"&&!gs(ne,Bo)&&Hn.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(ne).paddingBottom)||0,d=0;for(let y of Array.from(ne.children)){if(y===Un||y.offsetHeight===0)continue;let C=Yr(y)+y.offsetHeight;C>d&&(d=C)}let m=ne.scrollHeight-r;return d>0?Math.min(d+a,m):m},bw=()=>{if(!Ft||Ft.spacerHeight<=0)return;let r=Cl(Ft.spacerHeight),a=Math.max(0,Math.round(ne.scrollTop)+ne.clientHeight-r+Bo);a<Ft.spacerHeight&&(vl(a),Ut())},io=()=>{Vr!==null&&(cancelAnimationFrame(Vr),Vr=null),Ws(),Ft=null,Un.style.height="0px",Un.style.display="none"},Nm=r=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Gd=r=>ne.querySelector(`[data-message-id="${Nm(r)}"]`),Fm=r=>{Vr!==null&&cancelAnimationFrame(Vr),Vr=requestAnimationFrame(()=>{Vr=null;let a=Nm(r),d=ne.querySelector(`[data-message-id="${a}"]`);if(!d)return;let m=Yr(d),y=Ft?.spacerHeight??0,C=Cl(y),{targetScrollTop:B,spacerHeight:z}=Zp({anchorOffsetTop:m,topOffset:Ti(),viewportHeight:ne.clientHeight,contentHeight:C,slack:Bo});Ft={initialSpacerHeight:z,contentHeightAtAnchor:C,spacerHeight:z},vl(z),Dm(ne,()=>d.isConnected?Math.max(0,Yr(d)-Ti()):B,220)})},xn=()=>{if(In()!=="anchor-top"||!Ft||!Hs)return;let r=Gd(Hs);if(!r)return;Ws();let a=Ft.spacerHeight,d=Cl(a),{targetScrollTop:m,spacerHeight:y}=Zp({anchorOffsetTop:Yr(r),topOffset:Ti(),viewportHeight:ne.clientHeight,contentHeight:d,slack:Bo});Ft={initialSpacerHeight:y,contentHeightAtAnchor:d,spacerHeight:y},vl(y),wn=!0,ne.scrollTop=m,Rn=ne.scrollTop,wn=!1,Ut()},vw=()=>{if(or()){if(!Hn.isFollowing()||gs(ne,1))return;pr(!Ln);return}if(Ft&&Ft.initialSpacerHeight>0){let r=ne.scrollHeight-Ft.spacerHeight,a=zh({initialSpacerHeight:Ft.initialSpacerHeight,contentHeightAtAnchor:Ft.contentHeightAtAnchor,currentContentHeight:r});a!==Ft.spacerHeight&&vl(a)}Ut()},Cw=r=>{let a=In();a==="follow"?(Sn(),pr(!0)):a==="anchor-top"&&(_i=!1,pl=!0,ul=!1,Hs=r,Fm(r))},ww=()=>{if(In()==="anchor-top"){if(pl){_i=!1;return}_i=!0,io(),Sn(),pr(!0)}},Sw=96,xw=r=>{if(Kr===null)return!0;let a=Gd(Kr),d=Gd(r);if(!a||!d)return!0;let m=Yr(d)-Yr(a);return Ti()+m>ne.clientHeight-Sw},Aw=r=>{if(In()!=="anchor-top"||!pl||ul||bl())return;let a=Kr===null;for(let d of r){if(!a){d.id===Kr&&(a=!0);continue}if(Nh(d)){if(d.id===Hs||!xw(d.id))return;Hs=d.id,Fm(d.id);return}}},Mw=r=>{let a=new Map;r.forEach(d=>{let m=$d.get(d.id);a.set(d.id,{streaming:d.streaming,role:d.role}),!m&&d.role==="assistant"&&(w.emit("assistant:message",d),!Ls&&(In()!=="anchor-top"||Og())&&jd()&&(dr+=1,zd(),Ut(),Qa(dr===1?"1 new message below.":`${dr} new messages below.`))),d.role==="assistant"&&m?.streaming&&d.streaming===!1&&w.emit("assistant:complete",d),d.variant==="approval"&&d.approval&&(m?d.approval.status!=="pending"&&w.emit("approval:resolved",{approval:d.approval,decision:d.approval.status}):w.emit("approval:requested",{approval:d.approval,message:d}))}),$d.clear(),a.forEach((d,m)=>{$d.set(m,d)})},Fi=(r,a)=>{let d=a==="user"?"user":"assistant",m=o.layout?.messages?.[d],y=m?.width??"content",C=m?.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),C?r.style.setProperty("--persona-message-row-max-width",C):r.style.removeProperty("--persona-message-row-max-width")},Do=(r,a)=>{let d=document.createElement("div");return d.className="persona-flex",d.id=`wrapper-${r}`,d.setAttribute("data-wrapper-id",r),Fi(d,a),d},Ew=(r,a,d)=>{let m=document.createElement("div"),C=(()=>{let W=l.find(Re=>Re.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),B=(W,Re)=>Re==null?!1:typeof Re=="string"?(W.textContent=Re,!0):(W.appendChild(Re),!0),z=new Set,q=new Map,j=new Set,X=l.some(W=>W.renderAskUserQuestion),se=[],ge=[],Ye=o.enableComponentStreaming!==!1,it=o.approval!==!1,lt=[],Kt=o.messageActions,Ot=Kt?.showRegenerate===!0&&Kt.enabled!==!1&&st.current?.isStreaming()!==!0?jy(a):null,Tt=Kt?.showEdit===!0&&Kt.enabled!==!1,nn=Kt?.showQuote===!0&&Kt.enabled!==!1,Je=null,on=o.features?.reasoningDisplay?.completedVisibility==="removed";if(a.forEach(W=>{if(on&&W.variant==="reasoning"&&W.reasoning?.status==="complete")return;if(z.add(W.id),q.set(W.id,W.role),qr===W.id&&lr){let He=Do(W.id,W.role);He.setAttribute("data-persona-message-edit-stub","true"),He.setAttribute("data-preserve-runtime","true"),m.appendChild(He),Je={messageId:W.id,element:lr.element};return}let Re=X&&ms(W),Be=it&&W.variant==="approval"&&!!W.approval,fe=!Re&&W.role==="assistant"&&!W.variant&&Ye&&Tg(W);!Be&&ar.has(W.id)&&(r.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),ar.delete(W.id)),!fe&&$r.has(W.id)&&(r.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),$r.delete(W.id));let pt=ms(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",$t={canRegenerate:Ot===W.id,canEdit:Tt&&gu(W),canQuote:nn&&!W.variant&&(W.content?.trim().length??0)>0},rn=`${$t.canRegenerate?"r":""}${$t.canEdit?"e":""}${$t.canQuote?"q":""}`,sn=rv(W,jr)+pt+`:${rn}`,kt=Re||Be||fe?null:iv(Bt,W.id,sn);if(kt){m.appendChild(kt.cloneNode(!0)),ms(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(j.add(W.toolCall.id),wc(W,o,De.composerOverlay));return}let ke=null,qt=l.find(He=>!!(W.variant==="reasoning"&&He.renderReasoning||W.variant==="tool"&&He.renderToolCall||!W.variant&&He.renderMessage)),zt=o.layout?.messages;if(ms(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){Is.delete(W.id),r.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(wa(W)&&Mr(o).enabled)return;if(ms(W)&&o.features?.askUserQuestion?.enabled!==!1){let He=l.find(bt=>typeof bt.renderAskUserQuestion=="function");if(He&&st.current){let bt=Is.get(W.id),Ao=bt!==sn,ao=null;if(Ao){let{payload:Fe,complete:ut}=ni(W),vr=W.id,jt=()=>st.current?.getMessages().find(_n=>_n.id===vr);ao=He.renderAskUserQuestion({message:W,payload:Fe,complete:ut,resolve:_n=>{let ds=jt();ds&&st.current?.resolveAskUserQuestion(ds,_n)},dismiss:()=>{let _n=jt();_n?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(_n),st.current?.resolveAskUserQuestion(_n,"(dismissed)"))},config:o})}let We=bt!=null;if(Ao&&ao===null&&!We){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(j.add(W.toolCall.id),wc(W,o,De.composerOverlay));return}let ve=Do(W.id,W.role);ve.setAttribute("data-ask-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),m.appendChild(ve),se.push({messageId:W.id,fingerprint:sn,bubble:ao});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(j.add(W.toolCall.id),wc(W,o,De.composerOverlay));return}}else if(Be){let He=F();if(!He){m.appendChild(Do(W.id,W.role));return}let bt=l.find(ve=>typeof ve.renderApproval=="function")??v,ao=ar.get(W.id)!==sn,We=null;if(ao&&bt?.renderApproval){let ve=W.id,Fe=(ut,vr)=>{let jt=st.current?.getMessages().find(_n=>_n.id===ve);jt?.approval&&(jt.approval.toolType==="webmcp"?st.current?.resolveWebMcpApproval(jt.id,ut):st.current?.resolveApproval(jt.approval,ut,vr))};We=bt.renderApproval({message:W,defaultRenderer:()=>He.createApprovalBubble(W,o),config:o,approve:ut=>Fe("approved",ut),deny:ut=>Fe("denied",ut)})}if(ao&&We===null)r.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),ar.delete(W.id),ke=He.createApprovalBubble(W,o);else{let ve=Do(W.id,W.role);ve.setAttribute("data-approval-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),m.appendChild(ve),lt.push({messageId:W.id,fingerprint:sn,bubble:We});return}}else if(qt)if(W.variant==="reasoning"&&W.reasoning&&qt.renderReasoning){if(!Fn)return;ke=qt.renderReasoning({message:W,defaultRenderer:()=>lg(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&qt.renderToolCall){if(!Io)return;ke=qt.renderToolCall({message:W,defaultRenderer:()=>dg(W,o),config:o})}else qt.renderMessage&&(ke=qt.renderMessage({message:W,defaultRenderer:()=>{let He=Xu(W,d,zt,o.messageActions,En,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:$t});return W.role!=="user"&&L(He,W,o,E),He},config:o}));if(!ke&&fe){let He=fC(W);if(He){let bt=$r.get(W.id),Ao=bt!==sn,ao=o.wrapComponentDirectiveInBubble!==!1&&Go.getOptions(He.component)?.bubbleChrome!==!1,We=null;if(Ao){let ve=gC(He,{config:o,message:W,transform:d});if(ve&&He.component==="PersonaArtifactInline"){let Fe=ve.hasAttribute("data-artifact-inline")?ve:ve.querySelector("[data-artifact-inline]"),ut=Fe?.getAttribute("data-artifact-inline")??"",vr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(ut):ut,jt=ut?r.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${vr}"]`)??null:null;Fe&&jt&&jt!==Fe&&Jo()?.hasLiveInlineArtifactBlock(jt)&&(Fe===ve?ve=jt:Fe.replaceWith(jt))}if(ve)if(ao){let Fe=document.createElement("div");if(Fe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Fe.id=`bubble-${W.id}`,Fe.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let ut=document.createElement("div");ut.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ut.innerHTML=d({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Fe.appendChild(ut)}Fe.appendChild(ve),We=Fe}else{let Fe=document.createElement("div");if(Fe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Fe.id=`bubble-${W.id}`,Fe.setAttribute("data-message-id",W.id),Fe.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let ut=document.createElement("div");ut.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ut.innerHTML=d({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Fe.appendChild(ut)}Fe.appendChild(ve),We=Fe}}if(We||bt!=null){let ve=Do(W.id,W.role);ve.setAttribute("data-component-directive-stub","true"),ve.setAttribute("data-preserve-runtime","true"),m.appendChild(ve),ge.push({messageId:W.id,fingerprint:sn,bubble:We});return}}}if(!ke)if(W.variant==="reasoning"&&W.reasoning){if(!Fn)return;ke=lg(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!Io)return;ke=dg(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;let He=F();if(!He)return;ke=He.createApprovalBubble(W,o)}else{let He=o.layout?.messages;He?.renderUserMessage&&W.role==="user"?ke=He.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):He?.renderAssistantMessage&&W.role==="assistant"?ke=He.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):ke=Xu(W,d,He,o.messageActions,En,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:$t}),W.role!=="user"&&ke&&L(ke,W,o,E)}let Qn=Do(W.id,W.role);Qn.appendChild(ke),av(Bt,W.id,sn,Qn),m.appendChild(Qn)}),De.composerOverlay&&De.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Be=Re.getAttribute("data-persona-ask-sheet-for");Be&&!j.has(Be)&&ri(De.composerOverlay,Be)}),o.features?.toolCallDisplay?.grouped){let W=[],Re=[],Be=o.features.toolCallDisplay.groupedMode==="summary";a.forEach(fe=>{if(fe.variant==="tool"&&fe.toolCall&&Io){Re.push(fe);return}fe.variant==="reasoning"&&(!Fn||on&&fe.reasoning?.status==="complete")||((Re.length>1||Be&&Re.length>0)&&W.push(Re),Re=[])}),(Re.length>1||Be&&Re.length>0)&&W.push(Re),W.forEach(fe=>{let pt=fe.map(zt=>Array.from(m.children).find(Qn=>Qn instanceof HTMLElement&&Qn.getAttribute("data-wrapper-id")===zt.id)).filter(zt=>!!zt);if(pt.length<(Be?1:2))return;let $t=Do(`tool-group-${fe[0].id}`,"assistant");$t.setAttribute("data-persona-tool-group-row","true");let rn=document.createElement("div");rn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",rn.setAttribute("data-persona-tool-group","true");let sn=document.createElement("div");sn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",sn.id=`tool-group-summary-${fe[0].id}`;let kt=`Called ${fe.length} ${fe.length===1?"tool":"tools"}`,ke=o.toolCall?.renderGroupedSummary?.({messages:fe,toolCalls:fe.map(zt=>zt.toolCall).filter(zt=>!!zt),defaultSummary:kt,config:o});B(sn,ke)||(sn.textContent=kt);let qt=document.createElement("div");qt.className="persona-tool-group-stack persona-flex persona-flex-col",qt.id=`tool-group-stack-${fe[0].id}`,qt.setAttribute("data-persona-tool-group-stack","true"),rn.appendChild(sn),Be||rn.appendChild(qt),$t.appendChild(rn),pt[0].before($t),pt.forEach((zt,Qn)=>{if(Be){zt.remove();return}zt.style.setProperty("--persona-message-row-max-width","100%");let He=document.createElement("div");He.className="persona-tool-group-item persona-relative",He.setAttribute("data-persona-tool-group-item","true"),Qn<pt.length-1&&He.setAttribute("data-persona-tool-group-connector","true"),He.appendChild(zt),qt.appendChild(He)})})}lv(Bt,z);let Vo=a.some(W=>W.role==="assistant"&&W.streaming),So=a[a.length-1],xo=So?.role==="assistant"&&!So.streaming&&So.variant!=="approval";if(Ln&&a.some(W=>W.role==="user")&&!Vo&&!xo){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:Fa},Re=l.find(fe=>fe.renderLoadingIndicator),Be=null;if(Re?.renderLoadingIndicator&&(Be=Re.renderLoadingIndicator(W)),Be===null&&o.loadingIndicator?.render&&(Be=o.loadingIndicator.render(W)),Be===null&&(Be=Fa()),Be){let fe=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1,$t=o.layout?.messages?.layout??"bubble";fe.className=pt?Ua("assistant",$t).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),fe.setAttribute("data-typing-indicator","true"),pt&&(fe.style.color="var(--persona-message-assistant-text, var(--persona-text))",$t!=="flat"&&(fe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),fe.appendChild(Be);let rn=Do("typing-indicator","assistant");rn.appendChild(fe),m.appendChild(rn)}}if(!Ln&&a.length>0){let W=a[a.length-1],Re={config:o,lastMessage:W,messageCount:a.length},Be=l.find(pt=>pt.renderIdleIndicator),fe=null;if(Be?.renderIdleIndicator&&(fe=Be.renderIdleIndicator(Re)),fe===null&&o.loadingIndicator?.renderIdle&&(fe=o.loadingIndicator.renderIdle(Re)),fe){let pt=document.createElement("div"),$t=o.loadingIndicator?.showBubble!==!1;pt.className=$t?["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(" "),pt.setAttribute("data-idle-indicator","true"),pt.appendChild(fe);let rn=Do("idle-indicator","assistant");rn.appendChild(pt),m.appendChild(rn)}}if(oy(m),Jc(r,m),nu(r),Je){let{messageId:W,element:Re}=Je,Be=r.querySelector(`#wrapper-${W}`);Be&&Re.parentElement!==Be&&(Fi(Be,q.get(W)??"user"),Be.replaceChildren(Re))}if(se.length>0)for(let{messageId:W,fingerprint:Re,bubble:Be}of se){let fe=r.querySelector(`#wrapper-${W}`);fe&&(Fi(fe,q.get(W)??"assistant"),Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Re),Is.set(W,Re)))}if(Is.size>0)for(let W of Is.keys())z.has(W)||Is.delete(W);if(ge.length>0)for(let{messageId:W,fingerprint:Re,bubble:Be}of ge){let fe=r.querySelector(`#wrapper-${W}`);fe&&(Fi(fe,q.get(W)??"assistant"),Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Re),$r.set(W,Re)))}if($r.size>0)for(let W of $r.keys())z.has(W)||$r.delete(W);if(lt.length>0)for(let{messageId:W,fingerprint:Re,bubble:Be}of lt){let fe=r.querySelector(`#wrapper-${W}`);fe&&(Fi(fe,q.get(W)??"assistant"),Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Re),ar.set(W,Re)))}if(ar.size>0)for(let W of ar.keys())z.has(W)||ar.delete(W)},Qd=!1,wl=()=>{Qd||(Qd=!0,bh().catch(()=>{Qd=!1}))},qn=(r,a,d)=>{a.length>0&&wl(),Ew(r,a,d),im()},Ui=null,Tw=()=>{if(Ui)return;let r=d=>{let m=d.composedPath();m.includes(Ke)||Vt&&m.includes(Vt)||at(!1,"user")};Ui=r,(t.ownerDocument??document).addEventListener("pointerdown",r,!0)},Um=()=>{if(!Ui)return;(t.ownerDocument??document).removeEventListener("pointerdown",Ui,!0),Ui=null};be.push(()=>Um());let $i=null,kw=()=>{if($i)return;let r=d=>{d.key==="Escape"&&(d.isComposing||at(!1,"user"))};$i=r,(t.ownerDocument??document).addEventListener("keydown",r,!0)},$m=()=>{if(!$i)return;(t.ownerDocument??document).removeEventListener("keydown",$i,!0),$i=null};be.push(()=>$m());let qi=!1,qm=new Set,Pw=()=>{let r=o.launcher?.composerBar?.peek?.streamAnimation;return r||o.features?.streamAnimation},Bs=()=>{if(!xe())return;let r=De.peekBanner,a=De.peekTextNode;if(!r||!a)return;if(ye){r.classList.remove("persona-pill-peek--visible");return}let d=E?.getMessages()??[],m;for(let Ot=d.length-1;Ot>=0;Ot--){let Tt=d[Ot];if(Tt.role==="assistant"&&Tt.content){m=Tt;break}}if(!m){r.classList.remove("persona-pill-peek--visible");return}let y=m.content,C=!!m.streaming,B=Pw(),z=hc(B),q=z.type!=="none"?Nd(z.type,B?.plugins):null,j=q?.isAnimating?.(m)===!0,X=q!==null&&(C||j);X&&q&&!qm.has(q.name)&&(ya(q,t),qm.add(q.name));let se=X&&q?.containerClass?q.containerClass:null,ge=a.dataset.personaPeekStreamClass??null;ge&&ge!==se&&(a.classList.remove(ge),delete a.dataset.personaPeekStreamClass),se&&ge!==se&&(a.classList.add(se),a.dataset.personaPeekStreamClass=se),X?(a.style.setProperty("--persona-stream-step",`${z.speed}ms`),a.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(a.style.removeProperty("--persona-stream-step"),a.style.removeProperty("--persona-stream-duration"));let Ye=X?yc(y,z.buffer,q,m,C):y;if(X&&z.placeholder==="skeleton"&&C&&(!Ye||!Ye.trim())){let Ot=document.createElement("div"),Tt=ha();Tt.classList.add("persona-pill-peek__skeleton"),Ot.appendChild(Tt),Jc(a,Ot)}else{let Ot=Math.max(0,Ye.length-100),Tt=Ye.length>100?Ye.slice(-100):Ye,nn=ac(Tt);if(!X||!q){let Je=Ye.length>100?`\u2026${Tt}`:Tt;a.textContent!==Je&&(a.textContent=Je)}else{let Je=nn;(q.wrap==="char"||q.wrap==="word")&&(Je=fa(nn,q.wrap,`peek-${m.id}`,{skipTags:q.skipTags,startIndex:Ot}));let on=document.createElement("div");if(on.innerHTML=Je,q.useCaret&&Tt.length>0){let Vo=bc(),So=on.querySelectorAll(".persona-stream-char, .persona-stream-word"),xo=So[So.length-1];xo?.parentNode?xo.parentNode.insertBefore(Vo,xo.nextSibling):on.appendChild(Vo)}Jc(a,on),q.onAfterRender?.({container:a,bubble:r,messageId:m.id,message:m,speed:z.speed,duration:z.duration})}}let Kt=Ln||qi;r.classList.toggle("persona-pill-peek--visible",Kt)};if(xe()){let r=De.peekBanner;if(r){let m=y=>{y.preventDefault(),y.stopPropagation(),at(!0,"user")};r.addEventListener("pointerdown",m),be.push(()=>{r.removeEventListener("pointerdown",m)})}let a=()=>{qi||(qi=!0,Bs())},d=()=>{qi&&(qi=!1,Bs())};Me.addEventListener("pointerenter",a),Me.addEventListener("pointerleave",d),be.push(()=>{Me.removeEventListener("pointerenter",a),Me.removeEventListener("pointerleave",d)}),Vt&&(Vt.addEventListener("pointerenter",a),Vt.addEventListener("pointerleave",d),be.push(()=>{Vt.removeEventListener("pointerenter",a),Vt.removeEventListener("pointerleave",d)}))}let Iw=r=>{let a=o.launcher?.composerBar??{},d=a.expandedSize??"anchored",m=a.bottomOffset??"16px",y=a.collapsedMaxWidth,C=a.expandedMaxWidth??"880px",B=a.expandedTopOffset??"5vh",z=a.modalMaxWidth??"880px",q=a.modalMaxHeight??"min(90vh, 800px)",j="calc(100vw - 32px)",X="var(--persona-pill-area-height, 80px)",se=Ke.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",Vt){let ge=Vt.style;ge.bottom=m,ge.width=y??""}if(r&&d!=="fullscreen"){if(d==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=z,se.maxWidth=j,se.maxHeight=q,se.height=q;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${m} + ${X})`,se.top=B,se.width=C,se.maxWidth=j}},zi=()=>{if(ye&&wl(),!Oe())return;if(xe()){let j=(o.launcher?.composerBar??{}).expandedSize??"anchored",X=ye?"expanded":"collapsed";Ke.dataset.state=X,Ke.dataset.expandedSize=j,Vt&&(Vt.dataset.state=X,Vt.dataset.expandedSize=j),Ke.style.removeProperty("display"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Iw(ye),pe.style.display=ye?"flex":"none",_r(),ye?(Tw(),kw()):(Um(),$m()),Bs();return}let r=Rt(o),a=t.ownerDocument.defaultView??window,d=o.launcher?.mobileBreakpoint??640,m=o.launcher?.mobileFullscreen??!0,y=a.innerWidth<=d,C=m&&y&&ue,B=Jn(o).reveal;ye?(Ke.style.removeProperty("display"),Ke.style.display=r?"flex":"",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-95","persona-opacity-0"),Me.classList.add("persona-scale-100","persona-opacity-100"),Mt?(Mt.setPanelOpen(!0),Mt.element.style.display="none"):pn&&(pn.style.display="none")):(r?r&&(B==="overlay"||B==="push")&&!C?(Ke.style.removeProperty("display"),Ke.style.display="flex",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.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"),Me.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"),Me.classList.remove("persona-scale-100","persona-opacity-100"),Me.classList.add("persona-scale-95","persona-opacity-0")),Mt?(Mt.setPanelOpen(!1),Mt.element.style.display=r?"none":""):pn&&(pn.style.display=r?"none":""))},at=(r,a="user")=>{if(!Oe()||ye===r)return;let d=ye;ye=r,zi();let m=(()=>{let C=o.launcher?.sidebarMode??!1,B=t.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640,j=B.innerWidth<=q,X=Rt(o)&&z&&j,se=xe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return C||z&&j&&ue||X||se})();if(ye&&m){if(!yo){let C=t.getRootNode(),B=C instanceof ShadowRoot?C.host:t.closest(".persona-host");B&&(yo=$u(B,o.launcher?.zIndex??an))}bo||(bo=qu(t.ownerDocument))}else ye||(yo?.(),yo=null,bo?.(),bo=null);ye&&(la(),Kd()||(In()==="follow"?pr(!0):yl()));let y={open:ye,source:a,timestamp:Date.now()};ye&&!d?w.emit("widget:opened",y):!ye&&d&&w.emit("widget:closed",y),w.emit("widget:state",{open:ye,launcherEnabled:ue,voiceActive:je.active,streaming:E.isStreaming()})},ur={inputDisabled:!1,sendDisabled:!1},gr=()=>ur.inputDisabled,Xr=()=>ur.inputDisabled||ur.sendDisabled,Lw=()=>(ur.inputDisabled?ur.inputReason:void 0)??(ur.sendDisabled?ur.sendReason:void 0);function Yd(){if(!Ee)return;if(Se.getState().phase==="streaming"){Ee.disabled=!1;return}let r=Xe?!Xe.isReady():!1;Ee.disabled=Xr()||r}function Sl(){if(!uo)return;let r=Se.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 Hw(){let r=Lw();if(xe()){let a=to??Le;r?a.setAttribute("title",r):a.removeAttribute("title"),Le.toggleAttribute(wi,!!r);return}if(r){ot.setAttribute("role","status"),ot.setAttribute("aria-live","polite"),ot.setAttribute(wi,""),ot.textContent=r;return}if(ot.hasAttribute(wi)&&(ot.removeAttribute("role"),ot.removeAttribute("aria-live"),ot.removeAttribute(wi),u)){let a=E.getStatus();tn(ot,cn(a),o.statusIndicator??{},a)}}function Xd(){let r=Eu(o.composer?.inputDisabled),a=Eu(o.composer?.sendDisabled);ur={inputDisabled:r.disabled,inputReason:r.reason,sendDisabled:a.disabled,sendReason:a.reason},Se.setInputDisabled(r.disabled),Se.setSendDisabled(a.disabled);let d=Se.getState().phase==="streaming",m=r.disabled,y=d||m;de&&(de instanceof HTMLTextAreaElement?de.disabled=m:de.setAttribute("contenteditable",m?"false":"true"),de.setAttribute("aria-disabled",m?"true":"false")),wt&&(wt.disabled=m),ft&&(ft.disabled=m);for(let C of Ht?.affordanceButtons??[])C.querySelectorAll("button").forEach(B=>{B.disabled=m});re&&(re.disabled=y),Nr.forEach(C=>{C.elements.forEach(B=>{B.toggleAttribute("data-disabled",y),B instanceof HTMLButtonElement||B.setAttribute("aria-disabled",y?"true":"false")}),C.buttons.forEach(B=>{B.disabled=y})}),np.forEach(C=>{C.toggleAttribute("data-disabled",y),C instanceof HTMLButtonElement?C.disabled=y:C.setAttribute("aria-disabled",y?"true":"false"),C.querySelectorAll("button").forEach(B=>{B.disabled=y})}),Le.dataset.personaComposerStreaming=d?"true":"false",Le.dataset.personaComposerInputDisabled=m?"true":"false",Le.dataset.personaComposerSendDisabled=Xr()?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(C=>{(C instanceof HTMLButtonElement||C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement||C instanceof HTMLSelectElement)&&(C.disabled=d)}),Yd(),Hw()}let ji=r=>{Se.setStreaming(r),Bg(r?"stop":"send"),Xd()},Jr=()=>{je.active||de&&de.focus()};w.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Jr(),200)});let Zr=null,Vi=!1,Jd=!bn.hidden,mr=null,Zd=!oe,xl=null;be.push(()=>{xl?.cancel(),xl=null});let Rw=r=>{let a=Tv(r);if(a===Ya)return;Ya=a,t.setAttribute("data-persona-conversation-state",a);let d=xd();Ja(),Zd&&(xl?.cancel(),xl=Mv(Le,a==="active"?d:xd(),a==="active"?"drop":"rise")),xn()},zm=null,jm,Vm=null,_s=null,ep=!1,Ki=r=>{let a=Xo(o),d=`${a.variant}|${a.dismiss}|${a.anchor??"bottom"}|${a.align??""}|${a.iconPlacement}|${a.kicker??""}|${a.title}|${a.subtitle}`;(d!==zm||a.icon!==jm)&&(zm=d,jm=a.icon,rd({host:bn,iconHolder:_C,kicker:OC,title:DC,subtitle:NC,starterSuggestions:vd},a));let m=a.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${a.message}`;m!==Vm&&(Vm=m,sd(kn,a.message,o));let y=r??(E?E.getMessages():o.initialMessages);Rw(y);let C=Vi,B=!C&&mi(a,y),z=B!==Jd;if(Jd=B,_s){mr?.cancel(),mr=null,C!==ep&&(ep=C,C?eg(ne,bn,null):Zu(ne,bn,_s)),gi(ne,bn,!C);return}if(z&&!B&&!C&&a.dismiss==="on-first-message"&&Zd){mr=Av(bn,j=>{mr===j&&(mr=null),!Jd&&!_s&&(gi(ne,bn,!1),xn()),j?.cancel()});return}if(mr){if(!B&&!C)return;mr.cancel(),mr=null}let q=!bn.hidden;gi(ne,bn,B),!B&&q&&xn()},tp=[],np=[],op=!1,Km=null,Gm,Qm=()=>{np.length=0;let r=tp.splice(0,tp.length);for(let a of r)try{a()}catch(d){console.warn("[persona] renderWelcome cleanup threw",d)}};be.push(Qm);let Ww=(r,a)=>{let d=ju(r,a);if(!d)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),k("span");let m=o.suggestions?.starters,y=Vu({item:{...d,behavior:d.behavior??m?.behavior??"send"},index:a,surface:"starter",source:"config",variant:m?.variant??"card",streaming:u?E.isStreaming():!1,config:o,plugins:l,chipsConfig:o.suggestionChipsConfig,session:E,getTextarea:()=>de,eventTarget:bn,submitPrompt:Yl});return np.push(y),y},rp=()=>{if(op)return;op=!0;let r=Xo(o);Km=`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`,Gm=r.icon;try{Qm(),eg(ne,bn,_s),_s=null,ep=!1;let a=E?E.getMessages():o.initialMessages,d=mi(r,a),m=0,y=null;for(let C of l)if(C.renderWelcome&&(y=C.renderWelcome({config:r,variant:r.variant,visible:d,defaultRenderer:()=>bn,sendMessage:B=>{if(!E||E.isStreaming())return;let z=B.trim();z&&E.sendMessage(z)},requestRender:()=>rp(),renderStarter:B=>Ww(B,m++),storage:g(C.id),onCleanup:B=>{tp.push(B)}}),y))break;y&&y!==bn&&(_s=y,Zu(ne,bn,y))}finally{op=!1}Ki()},Bw=()=>{let r=Xo(o);`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`===Km&&r.icon===Gm||rp()},Al=()=>{Ki(),Ms||(de.placeholder=Pb(Se.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!E?.isStreaming()&&(Ee.textContent=o.copy?.sendButtonLabel??"Send")),de.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',de.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},_w=!!o.setStoredConversationId,Gi=r=>ae(a=>{let d={...a};return delete d[r],d}),Ml=r=>{let a=ie[r];return typeof a=="string"?a:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Ml("sessionId"),setStoredSessionId:r=>{ae(a=>({...a,sessionId:r}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Gi("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ml("conversationId")),setStoredConversationId:o.setStoredConversationId??(r=>{ae(a=>({...a,conversationId:r}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Gi("conversationId"))});let Ym=()=>o.features?.history?.enabled===!0?o.clientToken??null:null,Xm=r=>aC(r,po(),o.persistState===!1),Jm=Ym(),No=Jm?Xm(Jm):null,es={...No?{visitorStore:No}:{},historyBootstrapReady:_,getStoredMessageCursor:()=>Ml("historyMessageCursor"),setStoredMessageCursor:r=>{if(r===null){Gi("historyMessageCursor");return}ae(a=>({...a,historyMessageCursor:r}))},getPendingDisplayProjections:()=>{let r=ie.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(d=>typeof d=="string")}},setPendingDisplayProjections:r=>{if(!r){Gi("pendingDisplayProjections");return}ae(a=>({...a,pendingDisplayProjections:r}))},..._w?{}:{getStoredConversationRevision:()=>Ml("conversationRevision"),setStoredConversationRevision:r=>{if(r===null){Gi("conversationRevision");return}ae(a=>({...a,conversationRevision:r}))}}},Ow=()=>{let r=Ym();if(r&&No?.matches(r,po(),o.persistState===!1)||!r&&!No)return;No?.destroy(),No=r?Xm(r):null;let a={...es};No?a.visitorStore=No:delete a.visitorStore,es=a,E.setHistoryInternals(es)},ts=null,Dw=()=>{ts==null&&(ts=setInterval(()=>{let r=Ie.querySelectorAll("[data-tool-elapsed]");if(r.length===0){clearInterval(ts),ts=null;return}let a=Date.now();r.forEach(d=>{let m=Number(d.getAttribute("data-tool-elapsed"));m&&(d.textContent=Eh(a-m))})},100))},sp=(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,z)=>sp(B,a[z]));let d=r,m=a,y=Object.keys(d),C=Object.keys(m);return y.length===C.length&&y.every(B=>Object.prototype.hasOwnProperty.call(m,B)&&sp(d[B],m[B]))},Zm=r=>{let{content:a,rawContent:d,llmContent:m,...y}=r;return y},ip=r=>r.role==="assistant"&&r.streaming===!0&&!r.variant&&!r.toolCall&&!r.tools&&!r.approval&&!r.reasoning&&!r.contentParts&&!r.stopReason&&!Tg(r),Nw=(r,a,d)=>{if(r.length!==a.length)return!1;let m=r[d.index],y=a[d.index];return!m||!y||m.id!==d.id||y.id!==d.id?!1:(!Object.is(m.content,y.content)||!Object.is(m.rawContent,y.rawContent)||!Object.is(m.llmContent,y.llmContent))&&ip(m)&&ip(y)&&sp(Zm(m),Zm(y))},ap=null,Os=null,ns=null,Fo=null,El=r=>{ap=r;let a,d;Os=null;for(let y=r.length-1;y>=0;y-=1){let C=r[y];if(!a&&C.role==="user"&&(a=C),!d&&C.role==="assistant"&&(d=C),!Os&&ip(C)&&(Os={index:y,id:C.id}),a&&d&&Os)break}qn(Ie,r,Jt),Jo()?.updateInlineArtifactBlocks(Ie,$n.artifacts,{suppressTransition:Ln}),Dw(),Ki(r),Ps(r),pr(!Ln),Mw(r),r.length===0&&(io(),_i=!0,pl=!1,Hs=null,ul=!1),!Fd||Ls?(Fd=!0,Kr=a?.id??null,Ud=d?.id??null):a&&a.id!==Kr?(Kr=a.id,Cw(a.id)):d&&d.id!==Ud&&ww(),d&&(Ud=d.id),Aw(r);let m=je.lastUserMessageId;a&&a.id!==m&&(je.lastUserMessageId=a.id,w.emit("user:message",a)),je.lastUserMessageWasVoice=!!a?.viaVoice,Oi(r),Bs()},lp=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null);let r=ns;ns=null,r&&El(r)},ef=()=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=null,ns=null},Fw=r=>{let a=ns??ap;if(Ln&&a&&Os&&Nw(a,r,Os)){ns=r,Fo===null&&(Fo=requestAnimationFrame(()=>{Fo=null;let d=ns;ns=null,d&&El(d)}));return}if(r.length===0){ef(),El(r);return}lp(),El(r)};E=new Pc(o,{onMessagesChanged(r){Fw(r)},onStatusChanged(r){let a=o.statusIndicator??{};tn(ot,(m=>m==="idle"?a.idleText??Dt.idle:m==="connecting"?a.connectingText??Dt.connecting:m==="connected"?a.connectedText??Dt.connected:m==="error"?a.errorText??Dt.error:m==="paused"?a.pausedText??Dt.paused:m==="resuming"?a.resumingText??Dt.resuming:Dt[m])(r),a,r),Ct()},onStreamingChanged(r){r||(E?.getMessages().length===0?ef():lp()),Ln=r,ji(r),Ct(),E&&qn(Ie,E.getMessages(),Jt),r||(pr(!0),bw(),Tm=!0,E&&km(E.getMessages(),Mr(o))),Ut(),Qa(r?"Responding\u2026":"Response complete."),Bs()},onVoiceStatusChanged(r){if(w.emit("voice:status",{status:r,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(r){case"listening":jo(),Gs();break;case"processing":jo(),$S();break;case"speaking":jo(),qS();break;default:r==="idle"&&E.isBargeInActive()?(jo(),Gs(),re?.setAttribute("aria-label","End voice session")):(je.active=!1,jo(),Oo("system"),so());break}},onArtifactsState(r){$n=r,r.artifacts.length===0&&(Es=!1),Jo()?.updateInlineArtifactBlocks(Ie,r.artifacts,{suppressTransition:Ln}),ro(),Oi()},onHistoryStateChanged(r){qe(r)},onHistoryNotice(r){Lt(r)},onReconnect(r){let{executionId:a,lastEventId:d}=r.handle;r.phase==="paused"?w.emit("stream:paused",{executionId:a,after:d}):r.phase==="resuming"?w.emit("stream:resuming",{executionId:a,after:d,attempt:r.attempt??1}):w.emit("stream:resumed",{executionId:a,after:d})}},es),st.current=E,be.push(()=>E.cancel()),be.push(()=>{E.destroy(),No?.destroy()});let cp=null;if(E.onReadAloudChange((r,a)=>{rm=r,sm=a,im();let d=r??cp;r&&(cp=r);let m=d?E.getMessages().find(y=>y.id===d)??null:null;w.emit("message:read-aloud",{messageId:d,message:m,state:a,timestamp:Date.now()}),a==="idle"&&(cp=null)}),u=!0,Fd=!0,o.voiceRecognition?.provider?.type==="runtype")try{E.setupVoice()}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",r)}let Uw=720,$w=250,Qe=tu(o.features?.history?.copy),Wn=null,dp=!1,rt=null,Tl=null,kl="conversation",pp=null,dn=null,vo=null,Pl=E.getHistoryState(),up=null,Qi=0,gp=null,Il=null,Ll=null,mp=`persona-history-${Math.random().toString(36).slice(2,8)}`,fp=()=>o.features?.history?.enabled===!0,Co=()=>fp()&&!!Wn&&!dp,tf=()=>{let r=E.getStatus();return Ln||r==="paused"||r==="resuming"},hp=()=>{let r=o.features?.history?.scope;if(r)return r;let a=o.getIdentityProof?"verified-user":"browser",d=Wn?.capabilities.scopes;return!d||d.includes(a)?a:d[0]??a},Ds=()=>Tl?.scope??hp(),nf=()=>E.getClientSession()?.targetId??null,of=r=>`${r.state}:${"reason"in r?r.reason:""}`,qw=r=>{let a=of(r);a!==up&&(up=a,w.emit("history:identityStatusChanged",{status:r,timestamp:Date.now()}))},Hl=r=>{r&&(Lo.textContent="",Lo.textContent=r)},rf=null,sf=null,zw=()=>{if(!fp())return null;let r=pC();if(r)return r();let a=o.features?.history?.provider;return a?typeof a!="function"?a:(rf!==a&&(rf=a,sf=a()),sf):E.isClientTokenMode()?uC({client:E.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:d=>E.bindActivatedSession(d),getClient:()=>E.getClient()}):null},af=()=>{Il?.(),Il=null,Ll?.(),Ll=null,dp=!1,Wn=zw();let r={...es};Wn?r.historyProvider=Wn:delete r.historyProvider,es=r,E.setHistoryInternals(es),Wn&&(Il=Wn.subscribeAvailability?.(a=>{dp=!a,a||An({restoreFocus:!1}),hr()})??null,Ll=Wn.subscribeIdentityStatus(a=>qw(a)),up=of(Wn.getIdentityStatus()))},yp=()=>{let r=o.features?.history?.presentation??"panel";if(r==="panel"||r==="auto"&&!(!ue||Rt(o)))return"panel";let a=ho??pe;return(a.getBoundingClientRect().width||a.clientWidth)>=Uw?"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",Bn=null,fr=null,os=null,Yi=null,bp=null,lf="",cf=()=>Te===bp?lf:o.layout?.showHeader===!1?"none":"",jw=()=>le==="panel"&&!!os&&Yi===os.element&&o.layout?.showHeader!==!1&&cf()!=="none",Vw=()=>{for(let r of Array.from(Te.children))r!==Bn&&r.setAttribute(Rl,"")},Kw=()=>{for(let r of Array.from(pe.querySelectorAll(`[${Rl}]`)))r.removeAttribute(Rl)},Gw=()=>{let r=os;if(!r)return;if(Array.from(Te.children).some(m=>m!==Bn&&!m.hasAttribute(Rl))){fr&&fr!==Te&&(fr.style.removeProperty("min-height"),fr=null);let m=Te.offsetHeight;m>0&&(Te.style.minHeight=`${m}px`,fr=Te)}Bn||(Bn=k("div","persona-history-header-host")),r.setHeaderPlacement("external");let d=r.getHeaderElement();d.parentNode!==Bn&&Bn.replaceChildren(d),Bn.parentNode!==Te&&Te.appendChild(Bn),Vw()},df=()=>{fr&&(fr.style.removeProperty("min-height"),fr=null),Bn&&(os?.setHeaderPlacement("inline"),Bn.remove(),Bn=null,Kw())},Wl=null,vp=()=>{if(Wl){if(ne.style.display="none",zn(ne,!0),Le.hidden=!0,zn(Le,!0),jw()){Gw(),Te.style.display=cf(),zn(Te,!1);return}df(),Te.style.display="none",zn(Te,!0)}};Ae=vp;let Qw=r=>{let a=ne.style.display,d=Le.hidden,m=Le,y=Te,C=Te.style.display;bp=y,lf=C,Wl=()=>{Wl=null,df(),bp=null,ne.style.display=a,zn(ne,!1),m.hidden=d,zn(m,!1),Le!==m&&(Le.hidden=!1,zn(Le,!1)),y.style.display=C,zn(y,!1),Te!==y&&(Te.style.display=o.layout?.showHeader===!1?"none":"",zn(Te,!1))},Le.parentNode?.insertBefore(r,Le),vp()},Ns=null,rs=null,Xi=null,Fs=null,pf=()=>[Te,De.closeButtonWrapper,De.clearChatButtonWrapper,ne,Le],Yw=52,Bl=()=>o.features?.history?.rail?.collapsible!==!1,Us=()=>o.features?.history?.rail?.side==="right"?"right":"left",Cp=200,wp=400,Sp=r=>Math.min(wp,Math.max(Cp,Math.round(r))),Xw=()=>o.features?.history?.rail?.resizable===!0,Ji,Jw=()=>{if(Ji===void 0&&(Ji=null,o.persistState!==!1))try{let r=Number(window.localStorage.getItem(`${po()}rail-width`));r&&(Ji=r)}catch{}return Ji},Zi=()=>Sp(Jw()??o.features?.history?.rail?.width??260),Zw=r=>{if(Ji=r,o.persistState!==!1)try{window.localStorage.setItem(`${po()}rail-width`,String(r))}catch{}},_l=()=>Bl()&&o.features?.history?.rail?.collapsedBehavior==="overlay",_t=!1,uf=r=>{let a=k("img");return a.src=r,a.alt="",a.setAttribute("aria-hidden","true"),a},eS=()=>{let r=o.features?.history?.rail?.brand;if(!r)return;let a=!1,d;return m=>{if(r.render)try{return r.render({collapsed:m})??null}catch(y){return a||(a=!0,console.warn("[persona] history rail brand threw",y)),null}return d===void 0&&(r.iconUrl?d=uf(r.iconUrl):d=r.icon?he(r.icon,20):null),d?d.cloneNode(!0):null}},tS=()=>o.features?.history?.rail?.sections?.map(r=>{let a=!1,d=m=>{a||(a=!0,console.warn("[persona] history rail section threw",r.id,m))};return{id:r.id,title:r.title,placement:r.placement??"above-conversations",items:r.items.map(m=>{let y;return{id:m.id,label:m.label,badge:m.badge,iconNode:()=>{if(y!==void 0)return y;try{m.renderIcon?y=m.renderIcon()??null:m.iconUrl?y=uf(m.iconUrl):y=m.icon?he(m.icon,20):null}catch(C){d(C),y=null}return y},onSelect:()=>{try{m.onSelect()}catch(C){d(C)}}}})}})??[],nS=r=>{let a=tS();for(let d of r)a.some(m=>m.id===d.id)?console.warn("[persona] duplicate history rail section id",d.id):a.push(d);return a.length?a:void 0},ea=null,gf=()=>`${po()}rail-collapsed`,xp=()=>{if(ea===null&&(ea=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let r=window.localStorage.getItem(gf());r&&(ea=r==="1")}catch{}return ea},Ap=r=>{if(ea=r,o.persistState!==!1)try{window.localStorage.setItem(gf(),r?"1":"0")}catch{}},ta=()=>le==="rail"&&Bl()&&!_l()&&xp(),Mp=()=>{},mf=()=>{if(_l()){Mp();return}Ap(!xp()),rt?.view.setCollapsed(ta()),mt(),xn()},Ep=()=>{let r=o.features?.history?.rail?.collapseShortcut;return!r||!Yc(r)?null:{combo:r,hint:Xc(r),aria:Ra(r)}},ff=()=>{p.forEach(a=>a()),p=[];let r=Ep();r&&p.push(c.register({id:"history-rail-collapse",combo:r.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>te&&le==="rail"&&Bl()||qs(),run:()=>_l()?Mp():mf()}));for(let a of o.layout?.header?.trailingActions??[])a.shortcut&&p.push(c.register({id:`header-action-${a.id}`,combo:a.shortcut,run:()=>{let d=t.querySelector(`[data-persona-header-action="${a.id}"]`);d?d.click():o.layout?.header?.onAction?.(a.id)}}));for(let a of l)for(let d of a.shortcuts??[])p.push(c.register({...d,id:`${a.id}:${d.id}`}))};ff();let oS=300,Ol="var(--persona-history-overlay-margin,8px)",jn=null,Uo=null,Dl=0,$o=null,$s=null,ss=!1,Tp=0,hf=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,qs=()=>Co()&&_l()&&(le??yp())==="rail",rS=()=>te&&!_t,na=()=>{$s!==null&&clearTimeout($s),$s=null},sS=()=>{Ag().catch(()=>{})},yf=()=>{na(),_t&&($s=setTimeout(()=>{$s=null,!(ss||!_t)&&($o?.contains(document.activeElement)||An({restoreFocus:!1}))},oS))},iS=(r,a)=>{let d=$o?.getBoundingClientRect();if(!d)return!1;let m=jn?.getBoundingClientRect(),y=m?Math.min(m.top,d.top):d.top;return r>=d.left&&r<=d.right&&a>=y&&a<=d.bottom||!!m&&r>=m.left&&r<=m.right&&a>=m.top&&a<=m.bottom},kp=r=>{_t&&(ss=iS(r.clientX,r.clientY),ss?na():$s===null&&yf())},bf=r=>{te||!qs()||(_t=!0,ra({invoker:jn,keyboard:r?.keyboard===!0}).then(()=>{te?!ss&&document.activeElement!==jn&&An():_t=!1}))},vf=()=>{let r=Yi?.querySelector('[data-persona-history-focus="collapse"]');r&&(r.setAttribute("aria-label",_t?Qe.expandLabel:Qe.collapseLabel),r.setAttribute("aria-expanded",_t?"false":"true"))},Cf=()=>{Ap(!1);let r=rt;if(!_t||!r){ra({invoker:jn});return}let a=document.activeElement===jn;_t=!1,Nl(),r.element.remove(),Ip(r.element),vf(),a&&Ul(),xn(),hr()},aS=()=>{Ap(!0),An()};Mp=()=>{!te||_t?Cf():aS()};let lS=()=>{let r=Ep(),a=hs({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":mp,...r?{"aria-keyshortcuts":r.aria}:{}}}),d=a.button;d.addEventListener("mouseenter",()=>{ss=!0,na(),!(hf()||Date.now()<Tp)&&bf()}),d.addEventListener("mouseleave",()=>{ss=!1,Tp=0,yf()}),d.addEventListener("focus",()=>{te||sS()}),d.addEventListener("click",m=>{Co()&&(m.detail!==0&&hf()&&!te?bf():Cf())}),jn=d,Uo=a.wrapper},oa=()=>{if(Uo&&!Uo.isConnected&&(Uo=null,jn=null),!qs()){Uo?.remove(),Uo=null,jn=null;return}jn||lS();let r=Uo,a=jn;if(!r||!a)return;let d=Us()!=="right"?Te.firstChild:null;(d??Te.lastChild)!==r&&Te.insertBefore(r,d),r.style.display=rS()||Dl>0?"none":"",a.setAttribute("aria-label",Qe.expandLabel),a.setAttribute("aria-expanded",te?"true":"false"),$o&&mt()},wf=r=>{if(!_t)return;let a=r.target;a instanceof Node&&($o?.contains(a)||Uo?.contains(a)||a instanceof Element&&a.closest('.persona-dropdown-menu,[role="alertdialog"]')||An({restoreFocus:!1}))};document.addEventListener("pointerdown",wf,!0),be.push(()=>{document.removeEventListener("pointerdown",wf,!0),document.removeEventListener("pointermove",kp),zs?.(),na()});let Pp=null,zs=null,Sf=16,xf=r=>{Zw(Sp(r)),mt(),xn()},cS=()=>{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(Cp)),r.setAttribute("aria-valuemax",String(wp)),r.addEventListener("pointerdown",a=>{let d=rs;if(!d||a.button!==0)return;a.preventDefault(),zs?.();let m=a.clientX,y=d.getBoundingClientRect().width||Zi(),C=Us()==="right"?-1:1,B=y,z=t.ownerDocument;d.style.transition="none";let q=X=>{B=Sp(y+C*(X.clientX-m)),d.style.flex=`0 0 ${B}px`,r.setAttribute("aria-valuenow",String(B))},j=()=>{zs=null,z.removeEventListener("pointermove",q),z.removeEventListener("pointerup",j),z.removeEventListener("pointercancel",j),d.style.removeProperty("transition");try{r.releasePointerCapture(a.pointerId)}catch{}xf(B)};zs=j,z.addEventListener("pointermove",q),z.addEventListener("pointerup",j),z.addEventListener("pointercancel",j);try{r.setPointerCapture(a.pointerId)}catch{}}),r.addEventListener("keydown",a=>{let d=Us()==="right"?-Sf:Sf,m=Zi(),y=a.key==="ArrowRight"?m+d:a.key==="ArrowLeft"?m-d:a.key==="Home"?Cp:a.key==="End"?wp:null;y!==null&&(a.preventDefault(),xf(y))}),r},dS=(r,a)=>{if(!Xw()||ta()){zs?.(),Pp?.remove();return}let d=Pp??cS();Pp=d,d.setAttribute("aria-label",Qe.resizeLabel),d.setAttribute("aria-valuenow",String(Zi())),d.nextElementSibling!==a&&r.insertBefore(d,a)};mt=()=>{rt?.view.setRailSide(Us());let r=Us()==="right",a=$o;if(a){let z=jn?jn.getBoundingClientRect().bottom-pe.getBoundingClientRect().top:0;a.style.top=`calc(${Math.max(0,Math.round(z))}px + ${Ol})`,a.style.width=`${Zi()}px`,a.style.left=r?"":Ol,a.style.right=r?Ol:""}let d=rs,m=Ns,y=Xi;if(!d||!m||!y)return;d.style.flex=`0 0 ${ta()?Yw:Zi()}px`;let C="1px solid var(--persona-divider,#e5e7eb)";d.style.borderRight=r?"":C,d.style.borderLeft=r?C:"";let B=r?y:d;m.firstElementChild!==B&&m.append(B,r?d:y),dS(m,r?d:y)};let Af=r=>{if(Fs&&rs){Fs.replaceWith(r),Fs=null,mt();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 d=k("div","persona-history-rail-conversation");d.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let m=k("div","persona-history-rail-host");m.style.cssText="display:flex;min-height:0;overflow:hidden",pe.insertBefore(a,Te.parentNode===pe?Te:ne);for(let y of pf())y?.parentNode===pe&&d.appendChild(y);a.append(m,d),m.appendChild(r),Ns=a,rs=m,Xi=d,mt()},pS=()=>{if(Ns)return;let r=k("div","persona-history-rail-placeholder");r.style.cssText="flex:1 1 auto;min-height:0",Fs=r,Af(r),xn()},Mf=()=>{Fs&&(Nl(),xn())},uS=r=>{let a=k("div","persona-history-rail-overlay");a.style.cssText=`position:absolute;bottom:${Ol};display:flex;overflow:hidden;z-index:${gc-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))`,pe.style.position="relative",pe.appendChild(a),a.appendChild(r),document.addEventListener("pointermove",kp),$o=a,mt(),vf()},Nl=()=>{Wl?.(),$o&&(ss&&(Tp=Date.now()+150),document.removeEventListener("pointermove",kp),$o.remove(),$o=null);let r=Ns;if(r){zs?.();for(let a of pf())a&&r.contains(a)&&pe.insertBefore(a,r);r.remove(),Ns=null,rs=null,Xi=null,Fs=null}},Ef=r=>{Yi=r,r.id=mp,r.style.flex="1 1 auto",r.style.minHeight="0"},Ip=r=>{Ef(r),(le!=="rail"||_t)&&Mf(),le!=="rail"?Qw(r):_t?uS(r):Af(r)},Fl=()=>{if(oa(),Of(),!te||!rt)return;let r=yp();if(r===le)return;let a=document.activeElement,d=a instanceof HTMLElement&&(rt.element.contains(a)||Bn?.contains(a)===!0)?a:null;Nl(),rt.element.remove(),rt.view.setHeaderPlacement("inline"),le=r,rt.view.setPresentation(r),rt.view.setCollapsed(ta()),rt.requestRender(),rt.element.isConnected||Ip(rt.element),d?.isConnected?d.focus():Ul(),Ut(),xn(),hr()},Tf=(r,a)=>Bn?.querySelector(a)??r.querySelector(a),Ul=()=>{let r=rt?.element??Yi;if(!r)return;let a=Tf(r,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(a){a.focus();return}let d=Tf(r,".persona-history-title")??r;d.tabIndex=-1,d.focus()},ra=async r=>{if(!Co()||te)return;let a=Wn;if(!a)return;if(!_t&&qs()&&xp()){oa();return}$l();let d=++Qi;kl=r?.returnSurface??"conversation",pp=r?.invoker??dn;let m=qs()&&!_t;m&&(Dl+=1,oa(),pS());let y;try{y=await Ag()}catch{Hl(Qe.openHistoryLabel),m&&(Dl-=1,d===Qi&&(Mf(),oa()));return}if(m&&(Dl-=1),d!==Qi||te)return;Tl={scope:hp()},le=yp(),te=!0;let C=le==="panel"&&o.layout?.showHeader!==!1&&Te.style.display!=="none"?"external":"inline",B=o.features?.history?.rowAvatar,z=Ep(),q=z?{hint:z.hint,aria:z.aria}:null,j={provider:a,context:Tl,targetId:nf(),presentation:le,collapsible:Bl(),collapsed:ta(),railSide:Us(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:eS(),onToggleCollapse:mf,...q?{collapseShortcut:q}:{},headerPlacement:C,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=>Hp(X,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:X=>is(X),attachTooltip:Yt,onStartNew:()=>Rp({focusComposer:!0}),onClose:()=>An(),onRequestDeleteConversation:X=>_f(X),onRequestClearHistory:()=>bS(),...a.resetDevice?{onRequestResetIdentity:()=>vS()}:{}};rt=dC({plugins:l,config:o,getPresentation:()=>le??"panel",getReturnSurface:()=>kl,close:()=>An(),createView:({slots:X,renderDom:se,onModelChange:ge,railSections:Ye})=>(os=y.createHistoryView({...j,railSections:nS(Ye),slots:X,renderDom:se,onModelChange:ge,onAnnounce:Hl}),os),onElementChanged:(X,se)=>{if(!se?.isConnected)return Ip(X);Ef(X),se.replaceWith(X),vp()}}),rt.view.setNewConversationRequired(Pl.recovery==="new_conversation_required"),r?.focus!==!1&&(le!=="rail"||r?.keyboard===!0)&&Ul(),Ut(),xn(),hr(),w.emit("history:opened",{presentation:le,returnSurface:kl,timestamp:Date.now()})},$l=()=>{},An=r=>{if(!te)return;Qi+=1;let a=kl,d=pp,m=rt,y=r?.restoreFocus!==!1;te=!1;let C=!1,B=null,z=()=>{if(!C){if(C=!0,$l=()=>{},B!==null&&clearTimeout(B),_t=!1,na(),Nl(),m?.dispose(),m?.view.destroy(),m?.element.remove(),rt===m&&(rt=null,os=null,Yi=null,le=null,Tl=null,pp=null),Ut(),xn(),hr(),y){let j=d??dn;j?.isConnected?j.focus():Jr()}w.emit("history:closed",{returnSurface:a,timestamp:Date.now()})}},q=m&&m.element===m.view.element?m.view.playExit():null;if(!q){z();return}$l=z,B=setTimeout(z,$w),q.then(z)},kf=r=>{if(!(r.key!=="Escape"||!te||!rt)){if(le==="rail"){let a=r.target;if(!(a instanceof Node)||!(rt.element.contains(a)||_t&&Uo?.contains(a)===!0))return}r.preventDefault(),r.stopPropagation(),An()}};pe.addEventListener("keydown",kf),be.push(()=>pe.removeEventListener("keydown",kf));let ql=null,Pf=!1,sa=()=>{if(!nr)return;let r=o.layout?.header?.titleSource==="conversation",a=r&&ql?.trim()||null;nr.textContent=a??o.launcher?.title??"Chat Assistant";let d=nr.closest(".persona-combo-btn");if(!d)return;let m=!r||E.getActiveConversationId()!==null;d.setAttribute("data-persona-menu-locked",m?"false":"true"),d.setAttribute("aria-haspopup",m?"true":"false"),m||d.setAttribute("aria-expanded","false"),d.style.cursor=m?"pointer":"default";let y=d.querySelector("svg");y&&(y.style.display=m?"":"none")},gS=r=>{r!==ql&&(ql=r,sa())},is=r=>{Pf=r?.starred===!0,gS(r&&r.title.trim()||null),sa()};sa(),pe.addEventListener("persona:title-menu-builtin",r=>{let a=r.detail?.actionId,d=E.getActiveConversationId();d&&(a==="delete"?_f(d):a==="star"&&E.canUpdateConversations()&&Wp(d,{starred:!Pf}).catch(()=>{}))});let zl=0,mS=250,jl=null,Vl=()=>{jl&&clearTimeout(jl),jl=null};be.push(Vl);let If=()=>{Vl();let r=Zr;r&&(Vi=!0,r.hidden=!1,Ie.style.display="none",Ki())},Kl=()=>{zl+=1,Vl(),Zr&&(Zr.remove(),Zr=null,Vi=!1,Ie.style.removeProperty("display"),zn(Le,!1),Ki())},fS=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Ie.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Lp=(r,a)=>Q("div",{className:On("persona-conversation-loading-bubble",a&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:r}}),Lf=()=>Q("div",{className:"persona-conversation-loading-body"},Lp("58%",!1),Lp("72%",!0),Lp("44%",!1)),Hf=r=>{Zr?.remove(),Zr=r,r.hidden=!Vi,ne.insertBefore(r,Ie),Vl(),Vi||(jl=setTimeout(If,mS)),zn(Le,!0)},hS=()=>{let r={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Lf},a=null,d=l.find(m=>m.renderLoadingIndicator);d?.renderLoadingIndicator&&(a=d.renderLoadingIndicator(r)),a===null&&o.loadingIndicator?.render&&(a=o.loadingIndicator.render(r)),Hf(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},a??Lf()))},yS=r=>{let a=()=>{Hp(r,{focusComposer:!0}).catch(()=>{})},d=Co()?()=>{Kl(),ra()}:void 0,m=(z,q)=>{let j=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:z});return j.addEventListener("click",q),j},y=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},m(Qe.openConversationRetryLabel,a),d?m(Qe.openConversationBackLabel,d):null)),C=Object.freeze({conversationId:r,config:o,copy:Object.freeze({title:Qe.openConversationErrorTitle,retryLabel:Qe.openConversationRetryLabel,backLabel:Qe.openConversationBackLabel}),retry:a,...d?{back:d}:{},defaultRenderer:y}),B=null;for(let z of l)if(z.renderHistoryOpenError){try{B=z.renderHistoryOpenError(C)}catch(q){console.warn("[persona] renderHistoryOpenError threw",q),B=null}if(B)break}Hf(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},B??y())),If()};w.on("history:closed",()=>{Zr&&zn(Le,!0)});let Hp=async(r,{focusComposer:a=!1}={})=>{let d=Ds(),m=!!rt;rt?.view.setActiveConversationId(r),Kl();let y=zl;hS(),te&&(le==="panel"||_t)&&An({restoreFocus:!1}),Ls=!0;try{await E.openConversation(r,{scope:d})}catch(C){throw y===zl&&yS(r),C}finally{Ls=!1}y===zl&&(Kl(),Bt.clear(),io(),Sn(),Kd()||yl(),fS(),qo(),m||is(null),w.emit("history:conversationOpened",{conversationId:r,title:ql,scope:d,timestamp:Date.now()}),a&&Jr())},Rp=async({focusComposer:r=!1}={})=>{Kl(),await E.startNewConversation({scope:Ds()}),is(null),Bt.clear(),io(),Sn(),yl(),qo();let a=E.getActiveConversationId();rt?.view.setActiveConversationId(a),w.emit("history:conversationStarted",{conversationId:a,timestamp:Date.now()}),te&&(le==="panel"||_t)&&An({restoreFocus:!1}),r&&Jr()},Wp=async(r,a)=>{let d=await E.updateConversation(r,{...a,...a.title!==void 0?{title:a.title.trim()}:{}});return rt?.view.applyConversationSummary(d),!rt&&r===E.getActiveConversationId()&&is(d),d},Rf=async r=>{let a=Ds(),d=E.getActiveConversationId()===r;await E.deleteConversation(r,{scope:a}),rt?.view.removeConversationSummary(r),d&&(is(null),Bt.clear(),io(),Sn(),qo()),w.emit("history:conversationDeleted",{conversationId:r,scope:a,wasActive:d,timestamp:Date.now()})},Wf=async r=>{let a=r?.scope??Ds(),d=r?.allTargets?null:r?.targetId??nf(),m=await E.clearConversationHistory({...d?{targetId:d}:{},scope:a});return is(null),Bt.clear(),io(),Sn(),qo(),w.emit("history:cleared",{deleted:m.deleted,scope:a,targetId:d,timestamp:Date.now()}),m},Bf=async()=>{if(!Wn?.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{is(null),E.clearArtifacts(),Bt.clear(),ap=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),ie={},Ce.syncFromMetadata(),G?.clear&&ml(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),io(),Sn(),qo(),An({restoreFocus:!1}),Jr(),ye||Mt?.launcher.element.focus()}return Hl(r?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),w.emit("history:identityReset",{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},Bp=()=>ho?Me:pe,_f=async r=>await hd({host:Bp(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Rf(r),"deleted"):"cancelled",bS=async()=>{let r=Ds()==="verified-user";return await hd({host:Bp(),title:Qe.clearHistoryConfirmTitle,description:r?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Wf(),"cleared"):"cancelled"},vS=async()=>{if(!await hd({host:Bp(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:a}=await Bf();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 qo=()=>{if(!(Co()&&!!Pl.nextMessageCursor&&!!E.getActiveConversationId())){Vn.remove();return}Vn.textContent=Qe.showEarlierMessagesLabel,Vn.parentNode!==ne&&ne.insertBefore(Vn,ne.firstChild)};Vn.addEventListener("click",()=>{let r=E.getActiveConversationId(),a=Pl.nextMessageCursor;if(!r||!a||Vn.disabled)return;Vn.disabled=!0;let d=ne.scrollHeight,m=ne.scrollTop;E.loadOlderMessages(r,a,{scope:Ds()}).then(()=>{ne.scrollTop=m+(ne.scrollHeight-d),xn()}).catch(()=>{}).finally(()=>{Vn.disabled=!1,qo()})});let CS=()=>{let r=hs({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()||tf())){if(te){An();return}ra({invoker:r.button,keyboard:a.detail===0})}}),r},Of=()=>{if(!Co()){vo?.remove(),dn=null,vo=null;return}if(vo&&!vo.isConnected&&(dn=null,vo=null),!dn&&Te){let m=CS();dn=m.button,vo=m.wrapper;let y=De.clearChatButtonWrapper||De.closeButtonWrapper;y?.parentNode&&Te.contains(y)?y.parentNode.insertBefore(vo,y):Te.appendChild(vo)}if(!dn||!vo)return;let r=qs()||te&&le==="rail";if(vo.style.display=r?"none":"",r){document.activeElement===dn&&Ul();return}let a=tf();dn.disabled=a,dn.setAttribute("aria-disabled",a?"true":"false");let d=a?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;dn.setAttribute("aria-label",d),(o.features?.history?.presentation??"panel")==="panel"?(dn.removeAttribute("aria-expanded"),dn.removeAttribute("aria-controls")):(dn.setAttribute("aria-expanded",te?"true":"false"),dn.setAttribute("aria-controls",mp))},Gl=!1,wS=()=>{let r=De.clearChatButton;if(r){if(Co()){Gl||(gp=r.getAttribute("aria-label")??"",Gl=!0),r.setAttribute("aria-label",Qe.newConversationLabel),r.removeAttribute("title");return}Gl&&(Gl=!1,gp&&r.setAttribute("aria-label",gp))}},hr=()=>{Qe=tu(o.features?.history?.copy),Of(),oa(),wS(),qo()};Ct=hr,qe=r=>{Pl=r,rt?.view.setNewConversationRequired(r.recovery==="new_conversation_required"),ji(r.sendBlocked||Ln),qo()},Lt=r=>{(r.code==="history_continuity_reset"||r.code==="conversation_deleted_recovered")&&(Bt.clear(),io(),Sn()),Hl(r.message),rt?.view.refresh()},af(),hr(),be.push(()=>{Il?.(),Ll?.(),Qi+=1,$l(),rt?.dispose(),rt?.view.destroy(),rt=null}),o.clientToken&&E.initClientSession().then(()=>{if(Co())return E.reconcileBootConversation({scope:hp()})}).then(()=>{qo()}).catch(r=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",r)}),(It||o.onSSEEvent)&&E.setSSEEventCallback((r,a)=>{o.onSSEEvent?.(r,a),U(r,a)});let Df=()=>{o.resume&&typeof o.reconnectStream=="function"&&E.resumeFromHandle(o.resume)};oe?oe.then(r=>{if(r){if(r.metadata&&(ie=kg(r.metadata),Ce.syncFromMetadata()),r.messages?.length){Ls=!0;try{E.hydrateMessages(r.messages)}finally{Ls=!1}wl()}r.artifacts?.length&&E.hydrateArtifacts(r.artifacts,r.selectedArtifactId??null),Wm(r.draft)}}).catch(r=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",r)}).finally(()=>{Zd=!0,S(),Df()}):(Wm(R),Df());let SS=()=>{!xe()||ye||!(o.launcher?.composerBar?.expandOnSubmit??!0)||at(!0,"auto")},xS=(r,a)=>r?a?{refs:[...r.refs,...a.refs],finalize:async()=>{let[d,m]=await Promise.allSettled([r.finalize(),a.finalize()]),y=[];return d.status==="fulfilled"?y.push(d.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",d.reason),m.status==="fulfilled"?y.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),bT(y)}}:r:a,_p=()=>{let a=de.getInlineMessageFields?.();return a&&a.contentSegments.some(m=>m.kind==="mention")?a.contentSegments:void 0},zo=!1,as=null,Ql=()=>{de.value="",de.style.height="auto",go(),aa()},Op="data-persona-composer-notice",js=null;function AS(r){Qa(r),!(xe()||!ot)&&(ot.hasAttribute(wi)||(ot.setAttribute(Op,""),ot.setAttribute("role","status"),ot.setAttribute("aria-live","polite"),ot.textContent=r,js&&clearTimeout(js),js=setTimeout(()=>{if(js=null,!!ot?.hasAttribute(Op)&&(ot.removeAttribute(Op),ot.removeAttribute("role"),ot.removeAttribute("aria-live"),u)){let a=E.getStatus();tn(ot,cn(a),o.statusIndicator??{},a)}},4e3)))}function MS(){let r=Se.getState().pendingSubmission;r&&(xs(void 0),de&&(de.value=r.text,de.dispatchEvent(new Event("input",{bubbles:!0})),go()),r.options.selectedModelId&&(Se.setSelectedModelId(r.options.selectedModelId),rr?.repaint()),r.options.activeModeIds?.length&&Za(r.options.activeModeIds),r.options.quote&&mo(r.options.quote),de?.focus())}let ES=r=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",r)},Nf=(r={})=>{let a=(r.overrideText??de?.value??"").trim();return r.resolveInlineCommand&&a?(Ht?.takeInlineCommand(a)??Promise.resolve(null)).then(d=>Ff(r,a,d)):Ff(r,a,null)},Ff=(r,a,d)=>{if(d?.kind==="action"){Ql(),Ht?.clear(),Br();return}let m=d?.kind==="server"?d.mentions:null,y=d?.kind==="prompt"?d.sendText:a,C=r.pending?.contentParts,B=(Xe?.hasAttachments()??!1)||(C?.length??0)>0;if(!Ub({text:y,hasAttachments:B,attachmentsReady:Xe?.isReady()??!0,hasMentions:Ht?.hasMentions()??!1,hasServerMentions:!!m,inputDisabled:gr(),sendDisabled:Xr()}))return;let z=E.isStreaming()?Td():"block";if(z==="defer-one"&&!r.pending){if(Se.getState().pendingSubmission){AS("One message is already queued. Edit or remove it first.");return}TS({intent:r,sendText:y,serverMentions:m});return}let q={text:y,mentionRefs:[...Ht?.getMentionRefs()??[],...m?.refs??[]],contentSegments:d?.kind==="prompt"?void 0:_p(),options:{...Se.getState().selectedModelId&&{selectedModelId:Se.getState().selectedModelId},...Se.getState().activeModeIds.length>0&&{activeModeIds:[...Se.getState().activeModeIds]},...Se.getState().quote&&{quote:{...Se.getState().quote}}},viaVoice:r.viaVoice};r.pending&&(q.options={...r.pending.options},q.contentSegments=r.pending.contentSegments,q.mentionRefs=[...r.pending.mentionRefs],q.viaVoice=r.pending.viaVoice);let j=()=>{if(C?.length)return[...C];if(!Xe?.hasAttachments())return;let lt=[...Xe.getContentParts()];return q.text&<.push(Eo(q.text)),lt};q.contentParts=j();let X=()=>{zr(),SS();let lt=Ht?.collectForSubmit()??null,Kt=xS(lt,m),Ot=j();r.consumeDraft!==!1&&Ql();let Tt={selectedModelId:q.options.selectedModelId,activeModeIds:q.options.activeModeIds},nn=z==="interrupt";nn&&E.cancel(),E.sendMessage(q.text,{contentParts:Ot,mentions:Kt??void 0,contentSegments:q.contentSegments,viaVoice:q.viaVoice,composerOptions:Tt,...q.options.quote&&{quote:q.options.quote},...nn&&{interrupt:!0}}),Xe?.hasAttachments()&&Xe.clearAttachments(),lt&&Ht?.clear(),Br();let Je=Se.getState().activeModeIds,on=kb(Je,o.composer?.modes);on.length!==Je.length&&Za(on),Se.getState().quote&&mo(void 0),hl(),Hd.release(),no()},se=o.composer?.onBeforeSend;if(!se){X();return}let ge=new AbortController;as=ge;let Ye=lt=>{if(as=null,lt.status==="error"){ES(lt.error);return}lt.status==="proceed"&&X()},it=$b(se,q,ge.signal);if(!(it instanceof Promise)){Ye(it);return}return Se.setPreparing(!0),it.then(Ye).finally(()=>Se.setPreparing(!1))};function TS(r){let a=Se.getState(),d=Xe?.hasAttachments()??!1,m=d?[...Xe.getContentParts()]:[];d&&r.sendText&&m.push(Eo(r.sendText));let y=Bu({text:r.sendText,contentParts:m.length?m:void 0,mentionRefs:[...Ht?.getMentionRefs()??[],...r.serverMentions?.refs??[]],contentSegments:_p(),options:{...a.selectedModelId&&{selectedModelId:a.selectedModelId},...a.activeModeIds.length>0&&{activeModeIds:[...a.activeModeIds]},...a.quote&&{quote:{...a.quote}}},viaVoice:r.intent.viaVoice});xs(y),r.intent.consumeDraft!==!1&&Ql(),d&&Xe.clearAttachments(),Ht?.clear(),Br(),a.quote&&mo(void 0),hl(),Hd.release(),no(),Qa("Message queued. It sends when the response finishes.")}function kS(){let r=Se.getState().pendingSubmission;r&&(xs(void 0),Xl(r.text,{consumeDraft:!1,pending:r}))}function PS(r){if(o.messageActions?.showEdit!==!0)return;let a=E.getMessages().find(d=>d.id===r);!a||!gu(a)||qr!==r&&(zr(),qr=r,lr=Rb({messageId:r,initialText:a.content,onSave:d=>IS(r,d),onCancel:()=>zr()}),Bt.delete(r),qn(Ie,E.getMessages(),Jt),lr.focus())}function IS(r,a){let d=lr;if(qr=null,lr=null,d?.destroy(),Bt.delete(r),!E.resubmitFrom(r,{reason:"edit",replacement:{text:a,mentionRefs:[],options:{}}})){qn(Ie,E.getMessages(),Jt);return}xn()}function LS(r){if(E.isStreaming())return;let a=uu(E.getMessages(),r);a&&(zr(),E.resubmitFrom(a,{reason:"retry"})&&xn())}el={regenerate:LS,edit:PS,quote:r=>{let d=E.getMessages().find(m=>m.id===r)?.content?.trim();d&&(mo({text:d,messageId:r}),de?.focus())}};let ia=async r=>{if(!zo){zo=!0;try{await Nf({resolveInlineCommand:!0,...r})}finally{zo=!1}}};function Yl(r){Xr()||(Ql(),Xl(r,{consumeDraft:!1}))}let Xl=(r,a)=>{if(zo)return;zo=!0;let d=()=>{zo=!1};try{let m=Nf({...a,overrideText:r});m instanceof Promise?m.finally(d):d()}catch(m){throw d(),m}},HS=r=>{if(r.preventDefault(),E.isStreaming()){E.cancel(),dt?.reset(),H?.update();return}zo||ia()},RS=()=>o.features?.composerHistory!==!1,Dp={...Uu},Np=!1,aa=()=>{Dp={...Uu}},WS=()=>E.getMessages().filter(r=>r.role==="user").map(r=>r.content??"").filter(r=>r.length>0),BS=r=>{if(!de)return;Np=!0,de.value=r,de.dispatchEvent(new Event("input",{bubbles:!0})),Np=!1;let a=de.value.length;de.setSelectionRange(a,a)},_S=r=>{Np||(r.isComposing||Ht?.handleInput(r.inputType??void 0),aa())},OS=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Pa(de)}),DS=r=>{if(de&&!gr()&&!(!r.isComposing&&Ht?.handleKeydown(r))){if(RS()&&(r.key==="ArrowUp"||r.key==="ArrowDown")&&!r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.isComposing){let a=de.selectionStart===0&&de.selectionEnd===0,d=ov({direction:r.key==="ArrowUp"?"up":"down",history:WS(),currentValue:de.value,atStart:a,state:Dp});if(Dp=d.state,d.handled){r.preventDefault(),d.value!==void 0&&BS(d.value);return}}if(ub(r,OS())){if(E.isStreaming()){if(r.preventDefault(),Td()==="block"||zo||Xr())return;aa(),ia();return}if(zo){r.preventDefault();return}if(Xr()){r.preventDefault();return}aa(),r.preventDefault(),Ee.click()}}},Uf=r=>{if(!(r.key!=="Escape"||r.isComposing)&&r.composedPath().includes(pe)){if(as){as.abort(),as=null,r.preventDefault(),r.stopImmediatePropagation();return}E.isStreaming()&&(E.cancel(),dt?.reset(),H?.update(),aa(),r.preventDefault(),r.stopImmediatePropagation())}},NS=async r=>{if(o.attachments?.enabled!==!0||!Xe||gr())return;let a=mT(r.clipboardData);a.length!==0&&(r.preventDefault(),await Xe.handleFiles(a))},Kn=null,wo=!1,Vs=null,yt=null,Fp=()=>o.voiceRecognition?.completionBehavior==="review";function ls(r){re?.setAttribute("data-state",r),r==="recording"?US():zp()}let $f="--persona-voice-level",Up=.5,Ks=null,$p=-1,Jl=0,qf=()=>{let r=[],a=Pn??re?.parentElement??null;return a&&r.push(a),Le&&r.push(Le),r},qp=r=>{let a=Math.round(Math.max(0,Math.min(1,r))*100)/100;if(a!==$p){$p=a;for(let d of qf())d.style.setProperty($f,String(a))}},FS=()=>{$p=-1,Jl=0;for(let r of qf())r.style.removeProperty($f)};function US(){if(Ks!==null)return;if(typeof requestAnimationFrame!="function"){qp(u?E.getVoiceLevel()??Up:Up);return}let r=()=>{Ks=requestAnimationFrame(r);let a=u?E.getVoiceLevel():null;if(a===null){qp(Up);return}Jl+=(a-Jl)*.3,qp(Jl)};Ks=requestAnimationFrame(r)}function zp(){Ks!==null&&(cancelAnimationFrame(Ks),Ks=null),FS()}let zf=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Zl=(r="user")=>{if(wo||E.isStreaming())return;let a=zf();if(!a)return;Kn=new a;let d=o.voiceRecognition??{},m=d.pauseDuration??2e3;Kn.continuous=d.provider?.browser?.continuous??!0,Kn.interimResults=!0,Kn.lang=d.provider?.browser?.language??"en-US";let y=de.value;Kn.onresult=C=>{let B="",z="";for(let j=0;j<C.results.length;j++){let X=C.results[j],se=X[0].transcript;X.isFinal?B+=se+" ":z=se}let q=y+B+z;de.value=q,go(),Vs&&clearTimeout(Vs),(B||z)&&(Vs=window.setTimeout(()=>{if(de.value.trim()&&Kn&&wo){if(yr(),Fp())return;ia({viaVoice:!0})}},m))},Kn.onerror=C=>{C.error!=="no-speech"&&yr()},Kn.onend=()=>{if(wo){let C=de.value.trim();!Fp()&&C&&C!==y.trim()&&ia({viaVoice:!0}),yr()}};try{if(Kn.start(),wo=!0,je.active=!0,r!=="system"&&(je.manuallyDeactivated=!1),Oo(r),so(),no(),re){let C=o.voiceRecognition??{};yt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:C.iconName??"mic",iconSize:parseFloat(C.iconSize??"")||un};let B=C.recordingBackgroundColor,z=C.recordingIconColor,q=C.recordingBorderColor;if(re.classList.add("persona-voice-recording"),ls("recording"),re.style.backgroundColor=B??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let j=re.querySelector("svg");j&&j.setAttribute("stroke",z)}q&&(re.style.borderColor=q),re.setAttribute("aria-label","Stop voice recognition")}}catch{yr("system")}},yr=(r="user")=>{if(wo){if(wo=!1,Vs&&(clearTimeout(Vs),Vs=null),Kn){try{Kn.stop()}catch{}Kn=null}if(je.active=!1,Oo(r),so(),no(),re){if(re.classList.remove("persona-voice-recording"),ls("idle"),yt){re.style.backgroundColor=yt.backgroundColor,re.style.color=yt.color,re.style.borderColor=yt.borderColor;let a=re.querySelector("svg");a&&a.setAttribute("stroke",yt.color||"currentColor"),yt=null}re.setAttribute("aria-label","Start voice recognition")}}},jp=()=>{if(!re||yt)return;let r=o.voiceRecognition??{};yt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:r.iconName??"mic",iconSize:parseFloat(r.iconSize??"")||un}},Vp=(r,a)=>{if(!re)return;let d=re.querySelector("svg");d&&d.remove();let m=yt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||un),y=he(r,m,a,1.5);y&&re.appendChild(y)},ec=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Gs=()=>{if(!re)return;jp();let r=o.voiceRecognition??{},a=r.recordingBackgroundColor,d=r.recordingIconColor,m=r.recordingBorderColor;if(ec(),re.classList.add("persona-voice-recording"),ls("recording"),re.style.backgroundColor=a??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=d??"var(--persona-voice-recording-indicator, #ffffff)",d){let y=re.querySelector("svg");y&&y.setAttribute("stroke",d)}m&&(re.style.borderColor=m),re.setAttribute("aria-label","Stop voice recognition")},$S=()=>{if(!re)return;jp();let r=o.voiceRecognition??{},a=E.getVoiceInterruptionMode(),d=r.processingIconName??"loader",m=r.processingIconColor??yt?.color??"",y=r.processingBackgroundColor??yt?.backgroundColor??"",C=r.processingBorderColor??yt?.borderColor??"";ec(),re.classList.add("persona-voice-processing"),ls("processing"),re.style.backgroundColor=y,re.style.borderColor=C;let B=m||"currentColor";re.style.color=B,Vp(d,B),re.setAttribute("aria-label","Processing voice input"),a==="none"&&(re.style.cursor="default")},qS=()=>{if(!re)return;jp();let r=o.voiceRecognition??{},a=E.getVoiceInterruptionMode(),d=a==="cancel"?"square":a==="barge-in"?"mic":"volume-2",m=r.speakingIconName??d,y=r.speakingIconColor??(a==="barge-in"?r.recordingIconColor??yt?.color??"":yt?.color??""),C=r.speakingBackgroundColor??(a==="barge-in"?r.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":yt?.backgroundColor??""),B=r.speakingBorderColor??(a==="barge-in"?r.recordingBorderColor??"":yt?.borderColor??"");ec(),re.classList.add("persona-voice-speaking"),ls("speaking"),re.style.backgroundColor=C,re.style.borderColor=B;let z=y||"currentColor";re.style.color=z,Vp(m,z);let q=a==="cancel"?"Stop playback and re-record":a==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",q),a==="none"&&(re.style.cursor="default"),a==="barge-in"&&re.classList.add("persona-voice-recording")},jo=()=>{re&&(ec(),ls("idle"),yt&&(re.style.backgroundColor=yt.backgroundColor??"",re.style.color=yt.color??"",re.style.borderColor=yt.borderColor??"",Vp(yt.iconName,yt.color||"currentColor"),yt=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},Kp=()=>{if(!gr()){if(o.voiceRecognition?.provider?.type==="runtype"){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(()=>{je.active=!1,je.manuallyDeactivated=!0,so(),Oo("user"),jo()});return}E.toggleVoice().then(()=>{je.active=E.isVoiceActive(),je.manuallyDeactivated=!E.isVoiceActive(),so(),Oo("user"),E.isVoiceActive()?Gs():jo()});return}if(wo){let r=de.value.trim();je.manuallyDeactivated=!0,so(),yr("user"),r&&!Fp()&&ia()}else je.manuallyDeactivated=!1,so(),Zl("user")}};kd=Kp,re&&be.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(E.isVoiceActive()&&E.toggleVoice(),jo()):yr("system")});let zS=w.on("assistant:complete",()=>{Se.getState().pendingSubmission&&setTimeout(()=>{E.isStreaming()||kS()},0)});be.push(zS);let jS=w.on("assistant:complete",()=>{Lm&&(je.active||je.manuallyDeactivated||Lm==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?E.toggleVoice().then(()=>{je.active=E.isVoiceActive(),Oo("auto"),E.isVoiceActive()&&Gs()}):Zl("auto"))},600))});be.push(jS);let VS=w.on("action:resubmit",()=>{setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)});be.push(VS);let jf=()=>{at(!ye,"user")},Mt=null,pn=null;if(ue&&!xe()){let{instance:r,element:a}=ig({config:o,plugins:l,onToggle:jf});Mt=r,r||(pn=a)}Mt?t.appendChild(Mt.element):pn&&t.appendChild(pn),zi(),Ps(),Al(),rp(),ji(E.isStreaming()),Kd()||(In()==="follow"?pr(!0):yl()),uw(),ct&&(!ue||xe()?setTimeout(()=>Jr(),0):ye&&setTimeout(()=>Jr(),200));let cs=null,Vf=()=>{cs&&(cs.disconnect(),cs.observe(Le),cs.observe(pe))},la=()=>{if(xe()){Wr(),zi();return}let r=Rt(o),a=o.launcher?.sidebarMode??!1,d=t.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640,C=d.innerWidth<=y,B=m&&C&&ue;try{if(B){_r(),Ri=ll();return}let z=!1;Ne&&(Ne=!1,_r(),z=!0);let q=ll();if(!z&&q!==Ri&&(_r(),z=!0),Ri=q,z&&rl(),!ue&&!r){Me.style.height="",Me.style.width="";return}if(!a&&!r){let X=o?.launcher?.width??o?.launcherWidth??Yo;Me.style.width=X,Me.style.maxWidth=X}al(),fm()}finally{if(Wr(),Ja(),zi(),ye&&ue){let q=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),j=o.launcher?.sidebarMode??!1,X=o.launcher?.mobileFullscreen??!0,se=Rt(o)&&X&&q,ge=j||X&&q&&ue||se;if(ge&&!bo){let Ye=t.getRootNode(),it=Ye instanceof ShadowRoot?Ye.host:t.closest(".persona-host");it&&!yo&&(yo=$u(it,o.launcher?.zIndex??an)),bo=qu(t.ownerDocument)}else ge||(yo?.(),yo=null,bo?.(),bo=null)}}};la();let tc=t.ownerDocument.defaultView??window;if(tc.addEventListener("resize",la),be.push(()=>tc.removeEventListener("resize",la)),typeof ResizeObserver<"u"){cs=new ResizeObserver(()=>{Ja()}),Vf(),be.push(()=>{cs?.disconnect(),cs=null});let r=new ResizeObserver(()=>{Fl()});r.observe(pe),be.push(()=>r.disconnect())}tc.addEventListener("resize",Fl),be.push(()=>tc.removeEventListener("resize",Fl)),Rn=ne.scrollTop;let Kf=Ko(ne),Gf=()=>{let r=ne.scrollTop,a=Ko(ne),d=a<Kf;if(Kf=a,!or()){Rn=r,Ut();return}let{action:m,nextLastScrollTop:y}=Uh({following:Hn.isFollowing(),currentScrollTop:r,lastScrollTop:Rn,nearBottom:gs(ne,Bo),userScrollThreshold:lw,isAutoScrolling:wn||dl||d,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Rn=y,m==="resume"){bl()||Sn();return}m==="pause"&&Ni()};if(ne.addEventListener("scroll",Gf,{passive:!0}),be.push(()=>ne.removeEventListener("scroll",Gf)),typeof ResizeObserver<"u"){let r=new ResizeObserver(()=>{vw(),nu(Ie)});r.observe(Ie),r.observe(ne),be.push(()=>r.disconnect())}let Qf=()=>{or()&&Hn.isFollowing()&&bl()&&Ni()},Yf=ne.ownerDocument;Yf.addEventListener("selectionchange",Qf),be.push(()=>{Yf.removeEventListener("selectionchange",Qf)});let KS=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Xf=r=>{KS.has(r.key)&&(Gr(),_g()&&or()&&Hn.isFollowing()&&Ni())},Jf=r=>{r.target?.closest("a, button, [tabindex], input, textarea, select")&&(Gr(),_g()&&or()&&Hn.isFollowing()&&Ni())};ne.addEventListener("keydown",Xf),ne.addEventListener("focusin",Jf),be.push(()=>{ne.removeEventListener("keydown",Xf),ne.removeEventListener("focusin",Jf)});let Zf=r=>{if(r.deltaY!==0&&Gr(),!or())return;let a=$h({following:Hn.isFollowing(),deltaY:r.deltaY,nearBottom:gs(ne,Bo),resumeWhenNearBottom:!0});a==="pause"?Ni():a==="resume"&&!bl()&&Sn()};ne.addEventListener("wheel",Zf,{passive:!0}),ne.addEventListener("touchmove",Gr,{passive:!0}),ne.addEventListener("pointerdown",Gr,{passive:!0}),be.push(()=>{ne.removeEventListener("touchmove",Gr),ne.removeEventListener("pointerdown",Gr)}),be.push(()=>ne.removeEventListener("wheel",Zf)),Wt.addEventListener("click",()=>{io(),ne.scrollTop=ne.scrollHeight,Rn=ne.scrollTop,Sn(),pr(!0),Ut()}),be.push(()=>Wt.remove()),be.push(()=>{_m(),io()});let eh=()=>{Ue&&(Fr&&(Ue.removeEventListener("click",Fr),Fr=null),Oe()?(Ue.style.display="",Fr=()=>{at(!1,"user")},Ue.addEventListener("click",Fr)):Ue.style.display="none")};eh(),(()=>{let{clearChatButton:r}=De;r&&r.addEventListener("click",()=>{if(Co()){Rp({focusComposer:!0}).catch(d=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",d)});return}E.clearMessages(),Bt.clear(),Sn(),ri(De.composerOverlay);try{localStorage.removeItem(Ci),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ci}`)}catch(d){console.error("[AgentWidget] Failed to clear default localStorage:",d)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ci)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(d){console.error("[AgentWidget] Failed to clear custom localStorage:",d)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),G?.clear&&ml(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ie={},Ce.syncFromMetadata(),Xe?.clearAttachments(),hl(),xs(void 0),mo(void 0),zr(),xt?.clear(),dt?.reset(),H?.update()})})();let th=[["keydown",DS],["input",_S],["input",go],["input",Br],["keyup",Br],["paste",NS],["focus",YC]],nh=r=>{if(r)for(let[a,d]of th)et?.addListener(r,a,d)},GS=r=>{if(r)for(let[a,d]of th)et?.removeListener(r,a,d)},oh=()=>{et&&(et.addListener(et.form,"submit",HS),et.addListener(et.footer,"click",Br),nh(de),re&&et.addListener(re,"click",Kp))};oh();let rh=()=>{Ht?.onComposerSwap((r,a)=>{GS(a),de=r,et&&(et.input=r),nh(r),Id(),Xd(),go()})};rh();let Gp=!1;function sh(){if(!Gp){Gp=!0;try{let r=de?.value??"",a=Le.ownerDocument??document,d=de?a.activeElement===de:!1;zp(),et?.destroy(),et=null,Ht?.destroy(),Ht=null;let m=null,y=()=>(m=xe()?td({config:o}):Na({config:o}),m.footer),C=Vg(y)??y();Tn.replaceComposer(C),Le=Tn.composer.footer;let B=m!==null&&C===m.footer;Ms=!B,Bg=B?m.setSendButtonMode:()=>{},jg(Le),Gg(Le),Qg(),Yg(),Xg(),rh(),Jg(),Ld(),Zg(),oh();let z=Nr.indexOf(Wo);Wo.destroy(),Wo=Oa(tr),z>=0&&(Nr[z]=Wo),de&&(de.value=r),go(),Br(),Al(),Ps(),ji(E.isStreaming()),je.active&&ls("recording"),_r(),Vf(),Wr(),no(),Sl(),d&&de?.focus()}finally{Gp=!1}}}let ca=t.ownerDocument??document;ca.addEventListener("keydown",Uf,!0);let ih=()=>{qd()},ah=()=>{ca.visibilityState==="hidden"&&qd()};typeof window<"u"&&(window.addEventListener("pagehide",ih),ca.addEventListener("visibilitychange",ah),be.push(()=>{window.removeEventListener("pagehide",ih),ca.removeEventListener("visibilitychange",ah)}));let lh="persona-attachment-drop-active",da=0,Qp=()=>{da=0,pe.classList.remove(lh)},Qs=()=>o.attachments?.enabled===!0&&Xe!==null&&!gr(),ch=r=>{!yd(r.dataTransfer)||!Qs()||(da++,da===1&&pe.classList.add(lh))},dh=r=>{!yd(r.dataTransfer)||!Qs()||(da--,da<=0&&Qp())},ph=r=>{!yd(r.dataTransfer)||!Qs()||(r.preventDefault(),r.dataTransfer.dropEffect="copy")},uh=r=>{if(!yd(r.dataTransfer)||!Qs())return;r.preventDefault(),r.stopPropagation(),Qp();let a=Array.from(r.dataTransfer.files??[]);a.length!==0&&Xe.handleFiles(a)},br=!0;pe.addEventListener("dragenter",ch,br),pe.addEventListener("dragleave",dh,br),t.addEventListener("dragover",ph,br),t.addEventListener("drop",uh,br);let nc=t.ownerDocument,gh=r=>{Qs()&&r.preventDefault()},mh=r=>{Qs()&&r.preventDefault()};nc.addEventListener("dragover",gh),nc.addEventListener("drop",mh),be.push(()=>{et?.destroy(),et=null,zp(),fo?.destroy(),fo=null,Ho?.destroy(),Ho=null,sr?.destroy(),sr=null,ir?.destroy(),ir=null,rr=null,Ed=null,qd(),Di.destroy(),js&&clearTimeout(js),zr(),as?.abort(),as=null,Xe?.destroy(),Xe=null,Se.destroy(),ca.removeEventListener("keydown",Uf,!0),Ht?.destroy()}),be.push(()=>{pe.removeEventListener("dragenter",ch,br),pe.removeEventListener("dragleave",dh,br),t.removeEventListener("dragover",ph,br),t.removeEventListener("drop",uh,br),nc.removeEventListener("dragover",gh),nc.removeEventListener("drop",mh),Qp()}),be.push(()=>{E.cancel()}),Mt?be.push(()=>{Mt?.destroy()}):pn&&be.push(()=>{pn?.remove()});let Et={update(r){let a=o.toolCall,d=o.messageActions,m=o.layout?.messages,y=o.colorScheme,C=o.loadingIndicator,B=o.iterationDisplay,z=o.features?.showReasoning,q=o.features?.showToolCalls,j=o.features?.toolCallDisplay,X=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type,ge=o.features?.history?.enabled===!0,Ye=o.features?.history?.provider,it=o.getIdentityProof,lt=o.clientToken,Kt=o.contextMentions;o=nC({...o,features:i},r),i=o.features,o=yg(o),s(),Od(),La(t,o),$a(t,o),qa(t,o),mt(),ro(),o.colorScheme!==y&&hm();let Ot=Cg.getForInstance(o.plugins);l.length=0,l.push(...Ot),ff(),ue=o.launcher?.enabled??!0,_e=o.launcher?.autoExpand??!1,Fn=o.features?.showReasoning??!0,Io=o.features?.showToolCalls??!0,Pr=o.features?.scrollToBottom??{};let Tt=In();yn=o.features?.scrollBehavior??{},Tt!==In()&&(io(),Sn()),Im(),Ng(),Ut();let nn=It;if(It=o.features?.showEventStreamToggle??!1,It&&!nn){if(xt||(Z(),E.setSSEEventCallback((J,Ve)=>{o.onSSEEvent?.(J,Ve),U(J,Ve)})),!Ze&&Te){let J=o.features?.eventStream?.classNames,Ve="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J?.toggleButton?" "+J.toggleButton:"");Ze=k("button",Ve),Ze.style.width="28px",Ze.style.height="28px",Ze.style.color=mn.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let Ge=en(bC,"18px","currentColor",1.5);Ge&&Ze.appendChild(Ge);let tt=De.clearChatButtonWrapper,vt=De.closeButtonWrapper,Zt=tt||vt;Zt&&Zt.parentNode===Te?Te.insertBefore(Ze,Zt):Te.appendChild(Ze),Ze.addEventListener("click",()=>{ee?As():Pd()})}}else!It&&nn&&(As(),Ze&&(Ze.remove(),Ze=null),xt?.clear(),ln?.destroy(),xt=null,ln=null,dt?.reset(),dt=null,eo=null);if(o.launcher?.enabled===!1&&Mt&&(Mt.destroy(),Mt=null),o.launcher?.enabled===!1&&pn&&(pn.remove(),pn=null),o.launcher?.enabled!==!1&&!Mt&&!pn){let{instance:J,element:Ve}=ig({config:o,plugins:l,onToggle:jf});Mt=J,J||(pn=Ve),t.appendChild(Ve)}Mt&&Mt.update(o),sa(),Hr&&o.launcher?.subtitle!==void 0&&(Hr.textContent=o.launcher.subtitle);let Je=o.layout?.header;if(Je?.layout!==Pe&&Te){let J=Je?ed(o,Je,{showClose:Oe(),onClose:()=>at(!1,"user")}):ys({config:o,showClose:Oe(),onClose:()=>at(!1,"user")});Tn.replaceHeader(J),Te=Tn.header.element,At=Tn.header.iconHolder,nr=Tn.header.headerTitle,Hr=Tn.header.headerSubtitle,Ue=Tn.header.closeButton,Pe=Je?.layout,sa()}else if(Je){if(At&&(At.style.display=Je.showIcon===!1?"none":""),nr&&(nr.style.display=Je.showTitle===!1?"none":""),Hr&&(Hr.style.display=Je.showSubtitle===!1?"none":""),Ue){let J=Oe()&&Je.showCloseButton!==!1;Ue.style.display=J?"":"none"}if(De.clearChatButtonWrapper){let J=Je.showClearChat;if(J!==void 0){De.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:Ve}=De;Ve&&!Ve.classList.contains("persona-absolute")&&(J?Ve.classList.remove("persona-ml-auto"):Ve.classList.add("persona-ml-auto"))}}}let Vo=o.layout?.showHeader!==!1;Te&&(Te.style.display=Vo?"":"none");let So=o.layout?.showFooter!==!1;Le&&(Le.style.display=So?"":"none"),Wr(),Ut(),ue!==$?ue?at(_e,"auto"):(ye=!0,zi()):_e!==we&&at(_e,"auto"),we=_e,$=ue,la(),eh();let Re=JSON.stringify(o.toolCall)!==JSON.stringify(a),Be=JSON.stringify(o.messageActions)!==JSON.stringify(d),fe=JSON.stringify(o.layout?.messages)!==JSON.stringify(m),pt=o.loadingIndicator?.render!==C?.render||o.loadingIndicator?.renderIdle!==C?.renderIdle||o.loadingIndicator?.showBubble!==C?.showBubble,$t=o.iterationDisplay!==B,rn=(o.features?.showReasoning??!0)!==(z??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(j)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(X);(Re||Be||fe||pt||$t||rn)&&E&&(jr++,qn(Ie,E.getMessages(),Jt));let kt=o.features?.streamAnimation?.type;if(kt!==se&&kt&&kt!=="none"){let J=Nd(kt,o.features?.streamAnimation?.plugins);J&&ya(J,t)}let ke=o.launcher??{},qt=ke.headerIconHidden??!1,zt=o.layout?.header?.showIcon,Qn=qt||zt===!1,He=ke.headerIconName,bt=ke.headerIconSize??"48px";if(At){let J=Te,Ve=J?.querySelector(".persona-flex-col");if(Qn)At.style.display="none",J&&Ve&&!J.contains(Ve)&&J.insertBefore(Ve,J.firstChild);else{if(At.style.display="",At.style.height=bt,At.style.width=bt,J&&Ve&&(J.contains(At)?At.nextSibling!==Ve&&(At.remove(),J.insertBefore(At,Ve)):J.insertBefore(At,Ve)),He){let tt=parseFloat(bt)||24,vt=he(He,tt*.6,"currentColor",1);vt?At.replaceChildren(vt):At.textContent=ke.agentIconText??"\u{1F4AC}"}else if(ke.iconUrl){let tt=At.querySelector("img");if(tt)tt.src=ke.iconUrl,tt.style.height=bt,tt.style.width=bt;else{let vt=document.createElement("img");vt.src=ke.iconUrl,vt.alt="",vt.className="persona-rounded-xl persona-object-cover",vt.style.height=bt,vt.style.width=bt,At.replaceChildren(vt)}}else{let tt=At.querySelector("svg"),vt=At.querySelector("img");(tt||vt)&&At.replaceChildren(),At.textContent=ke.agentIconText??"\u{1F4AC}"}let Ge=At.querySelector("img");Ge&&(Ge.style.height=bt,Ge.style.width=bt)}}let Ao=o.layout?.header?.showTitle,ao=o.layout?.header?.showSubtitle;if(nr&&(nr.style.display=Ao===!1?"none":""),Hr&&(Hr.style.display=ao===!1?"none":""),Ue){let J=Oe()&&o.layout?.header?.showCloseButton!==!1;if(Ue.style.display=J?"":"none",!xe()){let Gt=ke.closeButtonSize??"";Ue.style.height=Gt,Ue.style.width=Gt,Ue.style.minWidth=Gt,Ue.style.minHeight=Gt}let Ve=ke.closeButtonPlacement??"inline",{closeButtonWrapper:Ge}=De,tt=Ve==="top-right",vt=Ge?.classList.contains("persona-absolute");if(Ge&&tt!==vt)if(Ge.remove(),tt){Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Gt=Xi??pe;Gt.style.position="relative",Gt.appendChild(Ge)}else{let Gt=ke.clearChat?.placement??"inline",Qt=ke.clearChat?.enabled??!0;Ge.className=Qt&&Gt==="inline"?"":"persona-ml-auto",Te&&Te.appendChild(Ge)}if(Ue.style.color=ke.closeButtonColor||mn.actionIconColor,ke.closeButtonBackgroundColor?(Ue.style.backgroundColor=ke.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),ke.closeButtonBorderWidth||ke.closeButtonBorderColor){let Gt=ke.closeButtonBorderWidth||"0px",Qt=ke.closeButtonBorderColor||"transparent";Ue.style.border=`${Gt} solid ${Qt}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");ke.closeButtonBorderRadius?(Ue.style.borderRadius=ke.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),ke.closeButtonPaddingX?(Ue.style.paddingLeft=ke.closeButtonPaddingX,Ue.style.paddingRight=ke.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),ke.closeButtonPaddingY?(Ue.style.paddingTop=ke.closeButtonPaddingY,Ue.style.paddingBottom=ke.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom=""),Zc(Ue,ke.closeButtonIconName??"x",{iconSize:xe()?ng:void 0,iconText:ke.closeButtonIconText??"\xD7"});let Zt=ke.closeButtonTooltipText??"Close chat",lo=ke.closeButtonShowTooltip??!0;Ue.setAttribute("aria-label",Zt),Ge&&Yt({anchor:Ue,trigger:Ge,text:()=>Ue?.getAttribute("aria-label")??Zt,enabled:lo})}let{clearChatButton:We,clearChatButtonWrapper:ve}=De;if(We){let J=ke.clearChat??{},Ve=J.enabled??!0,Ge=o.layout?.header?.showClearChat,tt=Ge!==void 0?Ge:Ve,vt=J.placement??"inline";if(ve){ve.style.display=tt?"":"none";let{closeButtonWrapper:Zt}=De;!xe()&&Zt&&!Zt.classList.contains("persona-absolute")&&(tt?Zt.classList.remove("persona-ml-auto"):Zt.classList.add("persona-ml-auto"));let lo=vt==="top-right",Gt=ve.classList.contains("persona-absolute");if(!xe()&&lo!==Gt&&tt){if(ve.remove(),lo){ve.className="persona-absolute persona-top-4 persona-z-50",ve.style.right="48px";let Mo=Xi??pe;Mo.style.position="relative",Mo.appendChild(ve)}else{ve.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ve.style.right="";let Mo=De.closeButtonWrapper;Te&&Mo&&Mo.parentElement===Te?Te.insertBefore(ve,Mo):Te&&Te.appendChild(ve)}let Qt=De.closeButtonWrapper;Qt&&!Qt.classList.contains("persona-absolute")&&(lo?Qt.classList.add("persona-ml-auto"):Qt.classList.remove("persona-ml-auto"))}}if(tt){if(!xe()){let Qt=J.size??"";We.style.height=Qt,We.style.width=Qt,We.style.minWidth=Qt,We.style.minHeight=Qt}let Zt=J.iconColor??"";if(We.style.color=Zt||mn.actionIconColor,Zc(We,J.iconName??"refresh-cw",{iconSize:xe()?og:void 0}),J.backgroundColor?(We.style.backgroundColor=J.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let Qt=J.borderWidth||"0px",Mo=J.borderColor||"transparent";We.style.border=`${Qt} solid ${Mo}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");J.borderRadius?(We.style.borderRadius=J.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),J.paddingX?(We.style.paddingLeft=J.paddingX,We.style.paddingRight=J.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),J.paddingY?(We.style.paddingTop=J.paddingY,We.style.paddingBottom=J.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let lo=J.tooltipText??"Clear chat",Gt=J.showTooltip??!0;We.setAttribute("aria-label",lo),ve&&Yt({anchor:We,trigger:ve,text:()=>We?.getAttribute("aria-label")??lo,enabled:Gt})}}let Fe=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Sg],ut=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[za.message,za.messageAndClick];Ce=xg({parsers:Fe,handlers:ut,getSessionMetadata:V,updateSessionMetadata:ae,emit:w.emit,documentRef:typeof document<"u"?document:null}),Jt=SC(o,Ce,Cs),Ow(),E.updateConfig(o),(o.features?.history?.enabled===!0!==ge||o.features?.history?.provider!==Ye||o.getIdentityProof!==it||o.clientToken!==lt)&&(An({restoreFocus:!1}),af()),hr(),Fl(),qn(Ie,E.getMessages(),Jt),Ps(),Al(),Bw(),ji(E.isStreaming()),Kt!==o.contextMentions&&sh();let vr=o.voiceRecognition?.enabled===!0,jt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),_n=o.voiceRecognition?.provider?.type==="runtype";if(vr&&(jt||_n))if(!re||!Pn){let J=li(o);if(J){re=J.button,Pn=J.wrapper;let Ve=uo&&uo.parentElement===Ka?uo:null;Ka?Ka.insertBefore(Pn,Ve):to?.appendChild(Pn),et&&(et.micButton=re),et?.addListener(re,"click",Kp),re.disabled=E.isStreaming()}}else{let J=o.voiceRecognition??{},Ve=o.sendButton??{},Ge=J.iconName??"mic",tt=J.iconSize,vt=parseFloat(tt??"")||un;re.classList.add(Dn),re.classList.toggle(co,!tt),re.style.width=tt??"",re.style.height=tt??"",re.style.minWidth=tt??"",re.style.minHeight=tt??"";let Zt=J.iconColor??Ve.textColor;re.innerHTML="";let lo=he(Ge,vt,Zt||"currentColor",1.5);lo?re.appendChild(lo):re.textContent="\u{1F3A4}";let Gt=J.backgroundColor??Ve.backgroundColor;Gt?re.style.backgroundColor=Gt:re.style.backgroundColor="",Zt?re.style.color=Zt:re.style.color="var(--persona-text, #111827)",J.borderWidth?(re.style.borderWidth=J.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),J.borderColor?re.style.borderColor=J.borderColor:re.style.borderColor="",J.paddingX?(re.style.paddingLeft=J.paddingX,re.style.paddingRight=J.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),J.paddingY?(re.style.paddingTop=J.paddingY,re.style.paddingBottom=J.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let Qt=J.tooltipText??"Start voice recognition",Mo=J.showTooltip??!1;re.setAttribute("aria-label",Qt),Pn&&Yt({anchor:re,trigger:Pn,text:()=>re?.getAttribute("aria-label")??Qt,enabled:Mo}),Pn.style.display="",re.disabled=E.isStreaming()}else re&&Pn&&(Pn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?E.isVoiceActive()&&E.toggleVoice():wo&&yr());if(o.attachments?.enabled===!0){if(!vn||!wt){let J=o.attachments??{};Cn||(Cn=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Cn.style.display="none",(de.parentElement??to).insertBefore(Cn,de)),ft||(ft=document.createElement("input"),ft.type="file",ft.accept=(J.allowedTypes??Qo).join(","),ft.multiple=(J.maxFiles??4)>1,ft.style.display="none",ft.setAttribute("aria-label","Attach files"),(de.parentElement??to).insertBefore(ft,de)),vn=k("div","persona-send-button-wrapper"),wt=k("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Dn} ${co}`),wt.type="button",wt.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let Ve=J.buttonIconName??"paperclip";wt.style.fontSize="18px",wt.style.lineHeight="1";let Ge=he(Ve,un,"currentColor",1.5);Ge?wt.appendChild(Ge):wt.textContent="\u{1F4CE}",wt.addEventListener("click",vt=>{vt.preventDefault(),ft?.click()}),vn.appendChild(wt);let tt=J.buttonTooltipText??"Attach file";Yt({anchor:wt,trigger:vn,text:()=>wt?.getAttribute("aria-label")??tt}),Cd?Cd.append(vn):to.appendChild(vn),et&&(et.attachmentButton=wt,et.attachmentInput=ft??void 0,et.attachmentPreviews=Cn??void 0),!Xe&&ft&&Cn&&(Xe=Ea.fromConfig(J,Fg),Xe.setPreviewsContainer(Cn),et?.addListener(ft,"change",async()=>{Xe&&ft?.files&&(await Xe.handleFileSelect(ft.files),ft.value="")}))}else{vn.style.display="";let J=o.attachments??{};ft&&(ft.accept=(J.allowedTypes??Qo).join(","),ft.multiple=(J.maxFiles??4)>1),Xe&&Xe.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(pe.querySelector(".persona-attachment-drop-overlay")?.remove(),pe.appendChild(xC(o.attachments?.dropOverlay)),wt){let J=o.attachments??{},Ve=J.buttonTooltipText??"Attach file";wt.setAttribute("aria-label",Ve),wt.textContent="";let Ge=he(J.buttonIconName??"paperclip",un,"currentColor",1.5);Ge?wt.appendChild(Ge):wt.textContent="\u{1F4CE}",vn&&Yt({anchor:wt,trigger:vn,text:()=>wt?.getAttribute("aria-label")??Ve})}}else vn&&(vn.style.display="none"),Xe&&Xe.clearAttachments(),pe.querySelector(".persona-attachment-drop-overlay")?.remove();let St=o.sendButton??{},Yp=St.useIcon??!1,ps=St.iconText??"\u2191",oc=St.iconName,hh=St.tooltipText??"Send message",XS=St.showTooltip??!1,pa=St.size,JS=parseFloat(pa??"")||ku,rc=St.backgroundColor,ua=St.textColor;if(Yp){if(Ee.style.width=pa??"",Ee.style.height=pa??"",Ee.style.minWidth=pa??"",Ee.style.minHeight=pa??"",Ee.style.fontSize="18px",Ee.style.lineHeight="1",ua?Ee.style.color=ua:Ee.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!E.isStreaming())if(Ee.innerHTML="",oc){let J=parseFloat(St.iconSize??"")||Math.round(JS*.5),Ve=ua?.trim()||"currentColor",Ge=St.iconStrokeWidth??2,tt=he(oc,J,Ve,Ge),vt=he(St.stopIconName??"square",J,Ve,Ge);tt&&vt?Ee.appendChild(Pu(tt,vt)):tt?Ee.appendChild(tt):Ee.textContent=ps}else Ee.textContent=ps;Ee.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Dn}`,rc?(Ee.style.backgroundColor=rc,Ee.classList.remove("persona-bg-persona-primary")):(Ee.style.backgroundColor="",Ee.classList.add("persona-bg-persona-primary"))}else Ee.textContent=o.copy?.sendButtonLabel??"Send",Ee.style.width="",Ee.style.height="",Ee.style.minWidth="",Ee.style.minHeight="",Ee.style.fontSize="",Ee.style.lineHeight="",Ee.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",rc?(Ee.style.backgroundColor=rc,Ee.classList.remove("persona-bg-persona-accent")):Ee.classList.add("persona-bg-persona-accent"),ua?Ee.style.color=ua:Ee.classList.add("persona-text-white");St.borderWidth?(Ee.style.borderWidth=St.borderWidth,Ee.style.borderStyle="solid"):(Ee.style.borderWidth="",Ee.style.borderStyle=""),St.borderColor?Ee.style.borderColor=St.borderColor:Ee.style.borderColor="",St.paddingX?(Ee.style.paddingLeft=St.paddingX,Ee.style.paddingRight=St.paddingX):(Ee.style.paddingLeft="",Ee.style.paddingRight=""),St.paddingY?(Ee.style.paddingTop=St.paddingY,Ee.style.paddingBottom=St.paddingY):(Ee.style.paddingTop="",Ee.style.paddingBottom=""),E.isStreaming()||Ee.setAttribute("aria-label",hh),Sl(),uo&&Yt({anchor:Ee,trigger:uo,text:()=>Ee.getAttribute("aria-label")??hh,enabled:XS}),tm();let yh=zc(Se.getState().activeModeIds,o.composer?.modes);Se.setActiveModeIds(yh),ws().length>0!==!!Ho&&Ld(),Ho?.render(yh,ws());for(let J of[...Ss.keys()])qc(J,o.composer?.modeGroups)||Ss.delete(J);Ss.forEach(J=>J.repaint()),rr?.repaint(),fo?.resolve();let sc=Tr(o,xe());if(Dd(),sc){Ie.style.maxWidth=sc,Ie.style.marginLeft="auto",Ie.style.marginRight="auto",Ie.style.width="100%",kn.style.maxWidth=sc,kn.style.marginLeft="auto",kn.style.marginRight="auto",kn.style.width="100%";for(let J of[to,tr,Cn,ot])J&&(J.style.maxWidth=sc,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{Ie.style.maxWidth="",Ie.style.marginLeft="",Ie.style.marginRight="",Ie.style.width="",kn.style.maxWidth="",kn.style.marginLeft="",kn.style.marginRight="",kn.style.width="";for(let J of[to,tr,Cn,ot])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let Cr=o.statusIndicator??{},ZS=Cr.visible??!0;if(ot.style.display=ZS?"":"none",E){let J=E.getStatus();tn(ot,(Ge=>Ge==="idle"?Cr.idleText??Dt.idle:Ge==="connecting"?Cr.connectingText??Dt.connecting:Ge==="connected"?Cr.connectedText??Dt.connected:Ge==="error"?Cr.errorText??Dt.error:Dt[Ge])(J),Cr,J)}ot.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ex=Cr.align==="left"?"persona-text-left":Cr.align==="center"?"persona-text-center":"persona-text-right";ot.classList.add(ex),Id(),Xd(),no(),Ae()},open(){Oe()&&at(!0,"api")},close(){Oe()&&at(!1,"api")},toggle(){Oe()&&at(!ye,"api")},reconnect(){E.reconnectNow()},clearChat(){Ro=!1,E.clearMessages(),Bt.clear(),Sn();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),G?.clear&&ml(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ie={},Ce.syncFromMetadata(),Xe?.clearAttachments(),hl(),xs(void 0),mo(void 0),zr(),xt?.clear(),dt?.reset(),H?.update()},setMessage(r){return!de||E.isStreaming()||gr()?!1:(!ye&&Oe()&&at(!0,"system"),de.value=r,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(r){if(E.isStreaming()||Xr())return!1;let a=r?.trim()||de.value.trim();return a?(!ye&&Oe()&&at(!0,"system"),de.value="",de.style.height="auto",go(),Xl(a,{consumeDraft:!1}),!0):!1},getComposerState(){return Se.getState()},setQuote(r){let a=r?.text?.trim();a&&mo({...r,text:a})},clearQuote(){mo(void 0)},startVoiceRecognition(){return E.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(E.isVoiceActive()||(!ye&&Oe()&&at(!0,"system"),je.manuallyDeactivated=!1,so(),E.toggleVoice().then(()=>{je.active=E.isVoiceActive(),Oo("user"),E.isVoiceActive()&&Gs()})),!0):wo?!0:zf()?(!ye&&Oe()&&at(!0,"system"),je.manuallyDeactivated=!1,so(),Zl("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?E.isVoiceActive()?(E.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,so(),Oo("user"),jo()}),!0):!1:wo?(je.manuallyDeactivated=!0,so(),yr("user"),!0):!1},injectMessage(r){return!ye&&Oe()&&at(!0,"system"),E.injectMessage(r)},injectAssistantMessage(r){!ye&&Oe()&&at(!0,"system");let a=E.injectAssistantMessage(r);return gt&&(gt=!1,Zn&&(clearTimeout(Zn),Zn=null),setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)),a},injectUserMessage(r){return!ye&&Oe()&&at(!0,"system"),E.injectUserMessage(r)},injectSystemMessage(r){return!ye&&Oe()&&at(!0,"system"),E.injectSystemMessage(r)},injectMessageBatch(r){return!ye&&Oe()&&at(!0,"system"),E.injectMessageBatch(r)},injectComponentDirective(r){return!ye&&Oe()&&at(!0,"system"),E.injectComponentDirective(r)},injectTestMessage(r){!ye&&Oe()&&at(!0,"system"),E.injectTestEvent(r)},async connectStream(r,a){return E.connectStream(r,a)},__pushEventStreamEvent(r){It&&(Z(),U(r.type,r.payload))},showEventStream(){It&&Pd()},hideEventStream(){ee&&As()},isEventStreamVisible(){return ee},listConversations(r){return E.listConversations(r)},getActiveConversationId(){return E.getActiveConversationId()},openConversation(r,a){return Hp(r,{focusComposer:a?.focus===!0})},startNewConversation(r){return Rp({focusComposer:r?.focus===!0})},deleteConversation(r){return Rf(r)},renameConversation(r,a){return Wp(r,{title:a})},setConversationStarred(r,a){return Wp(r,{starred:a})},clearConversationHistory(r){return Wf(r)},resetHistoryIdentity(){return Bf()},getHistoryIdentityStatus(){return Wn?Wn.getIdentityStatus():fp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(r){return ra({...r?.returnSurface?{returnSurface:r.returnSurface}:{},...r?.focus!==void 0?{focus:r.focus}:{}})},hideHistory(r){An(r?.restoreFocus!==void 0?{restoreFocus:r.restoreFocus}:void 0)},isHistoryVisible(){return te},showArtifacts(){hn(o)&&(Ro=!1,Es=!0,ro(),ze?.setMobileOpen(!0))},hideArtifacts(){hn(o)&&(Ro=!0,ro())},upsertArtifact(r){return hn(o)?(wr(o.features?.artifacts,{artifactType:r.artifactType,...r.artifactType==="markdown"&&r.file?{file:r.file}:{},...r.presentation?{presentation:r.presentation}:{}})==="panel"&&(Ro=!1,Es=!0),E.upsertArtifact(r)):null},selectArtifact(r){hn(o)&&E.selectArtifact(r)},clearArtifacts(){hn(o)&&E.clearArtifacts()},getArtifacts(){return E?.getArtifacts()??[]},getSelectedArtifactId(){return E?.getSelectedArtifactId()??null},focusInput(){return ue&&!ye&&!xe()||!de?!1:(de.focus(),!0)},async resolveApproval(r,a,d){let y=E.getMessages().find(C=>C.variant==="approval"&&C.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,d)},setFollowUpSuggestions(r){iw(r)},clearFollowUpSuggestions(){Pm()},getMessages(){return E.getMessages()},getStatus(){return E.getStatus()},getPersistentMetadata(){return{...ie}},updatePersistentMetadata(r){ae(r)},on(r,a){return w.on(r,a)},off(r,a){w.off(r,a)},isOpen(){return Oe()&&ye},isVoiceActive(){return je.active},toggleReadAloud(r){E.toggleReadAloud(r)},stopReadAloud(){E.stopSpeaking()},getReadAloudState(r){return E.getReadAloudState(r)},onReadAloudChange(r){return E.onReadAloudChange(r)},getState(){return{open:Oe()&&ye,launcherEnabled:ue,voiceActive:je.active,streaming:E.isStreaming()}},showCSATFeedback(r){!ye&&Oe()&&at(!0,"system");let a=Ie.querySelector(".persona-feedback-container");a&&a.remove();let d=hC({onSubmit:async(m,y)=>{E.isClientTokenMode()&&await E.submitCSATFeedback(m,y),r?.onSubmit?.(m,y)},onDismiss:r?.onDismiss,...r});Ie.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(r){!ye&&Oe()&&at(!0,"system");let a=Ie.querySelector(".persona-feedback-container");a&&a.remove();let d=yC({onSubmit:async(m,y)=>{E.isClientTokenMode()&&await E.submitNPSFeedback(m,y),r?.onSubmit?.(m,y)},onDismiss:r?.onDismiss,...r});Ie.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(r,a){return E.submitCSATFeedback(r,a)},async submitNPSFeedback(r,a){return E.submitNPSFeedback(r,a)},destroy(){lp(),ts!=null&&(clearInterval(ts),ts=null),be.forEach(r=>r()),Ke.remove(),Vt?.remove(),Mt?.destroy(),pn?.remove(),Fr&&Ue.removeEventListener("click",Fr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let r=window.AgentWidgetBrowser,a={controller:Et,getMessages:Et.getMessages,getStatus:Et.getStatus,getMetadata:Et.getPersistentMetadata,updateMetadata:Et.updatePersistentMetadata,clearHistory:()=>Et.clearChat(),setVoiceActive:d=>d?Et.startVoiceRecognition():Et.stopVoiceRecognition()};window.AgentWidgetBrowser=a,be.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=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.focusInput()};if(window.addEventListener("persona:focusInput",a),be.push(()=>{window.removeEventListener("persona:focusInput",a)}),It){let j=se=>{let ge=se.detail;(!ge?.instanceId||ge.instanceId===r)&&Et.showEventStream()},X=se=>{let ge=se.detail;(!ge?.instanceId||ge.instanceId===r)&&Et.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",X),be.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",X)})}let d=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.showHistory()},m=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.hideHistory()};window.addEventListener("persona:showHistory",d),window.addEventListener("persona:hideHistory",m),be.push(()=>{window.removeEventListener("persona:showHistory",d),window.removeEventListener("persona:hideHistory",m)});let y=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.showArtifacts()},C=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.hideArtifacts()},B=j=>{let X=j.detail;X?.instanceId&&X.instanceId!==r||X?.artifact&&Et.upsertArtifact(X.artifact)},z=j=>{let X=j.detail;X?.instanceId&&X.instanceId!==r||typeof X?.id=="string"&&Et.selectArtifact(X.id)},q=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===r)&&Et.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",B),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",q),be.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",B),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",q)})}let Gn=fT(o.persistState);if(Gn&&Oe()){let r=hT(Gn.storage),a=`${Gn.keyPrefix}widget-open`,d=`${Gn.keyPrefix}widget-voice`,m=`${Gn.keyPrefix}widget-voice-mode`;if(r){let y=Gn.persist?.openState&&r.getItem(a)==="true",C=Gn.persist?.voiceState&&r.getItem(d)==="true",B=Gn.persist?.voiceState&&r.getItem(m)==="true";if(y&&(Mt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Et.open(),setTimeout(()=>{if(C||B)Et.startVoiceRecognition();else if(Gn.persist?.focusInput){let z=t.querySelector("textarea");z&&z.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",z=>{r.setItem(d,z.active?"true":"false")}),w.on("user:message",z=>{r.setItem(m,z.viaVoice?"true":"false")})),Gn.clearOnChatClear){let z=()=>{r.removeItem(a),r.removeItem(d),r.removeItem(m)},q=()=>z();window.addEventListener("persona:clear-chat",q),be.push(()=>{window.removeEventListener("persona:clear-chat",q)})}}}if(I&&Oe()&&(Mt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Et.open()},0)),Bs(),!aw){let r=ic(()=>{E&&(jr++,Bt.clear(),qn(Ie,E.getMessages(),Jt))});be.push(r)}A=()=>{E&&(jr++,Bt.clear(),qn(Ie,E.getMessages(),Jt))},E.getMessages().length>0&&wl(),x=()=>{E&&(jr++,Bt.clear(),qn(Ie,E.getMessages(),Jt))};let QS=Rh(()=>{E&&(jr++,Bt.clear(),qn(Ie,E.getMessages(),Jt))});be.push(QS);let YS=gg(()=>{E&&(jr++,Bt.clear(),qn(Ie,E.getMessages(),Jt),Jo()?.updateInlineArtifactBlocks(Ie,$n.artifacts,{suppressTransition:!0}),ro())});return be.push(YS),Et};var MC=(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},vT=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},CT=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},wT=(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.")},EC=(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"},Hg=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=""},TC=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Hg(t)},Pg=t=>{t.style.transition=""},Ig=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=""},Lg=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},bd=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},ST=(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))},xT=(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)},AT=t=>{let e=di(t),n=e.components?.panel,o=(s,i)=>s==null||s===""?i:gn(e,s)??s;return{inset:o(n?.inset,jc),canvasBackground:o(n?.canvasBackground,Vc)}},kC=(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},MT=(t,e,n,o,s,i,l,c)=>{let p=Jn(i),u=p.reveal==="push",g=c!=null,f=c?.inset??"",v=c?.canvasBackground??"";ST(t,e,n,o,u),xT(t,e,n,o,p.side,u),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=p.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,M=i?.launcher?.mobileFullscreen??!0,A=i?.launcher?.mobileBreakpoint??640,T=h!=null?h.innerWidth<=A:!1;if(M&&T&&l){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Ig(e),Pg(o),TC(o),Lg(n),bd(s,o),kC(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"),TC(o),vT(o,p.maxHeight),kC(o,g&&l,f,v),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Ig(e),Pg(o),Lg(n),bd(s,o);let P=p.animate?"transform 180ms ease":"none",K=p.side==="right"?"translateX(100%)":"translateX(-100%)",x=l?"translateX(0)":K;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=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.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",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Pg(o),Hg(o),bd(s,o);let P=MC(p.width,t.clientWidth),K=Math.max(0,t.clientWidth),x=p.animate?"margin-left 180ms ease":"none",L=p.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=`${K+P}px`,e.style.transition=x,e.style.marginLeft=`${L}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${K}px`,n.style.maxWidth=`${K}px`,n.style.minWidth=`${K}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.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="",Ig(e),Hg(o),Lg(n),bd(s,o);let P=p.reveal==="emerge";P?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let K=l?p.width:"0px",x=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${g?", padding 180ms ease":""}`:"none",L=!l;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${K}`,o.style.width=K,o.style.maxWidth=K,o.style.minWidth=K,o.style.minHeight="0",CT(o,p.maxHeight),o.style.overflow=P||L?"hidden":"visible",o.style.transition=x,P){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let w=g?`calc(${MC(p.width,t.clientWidth)}px - (2 * ${f}))`:p.width;s.style.width=w,s.style.minWidth=w,s.style.maxWidth=w,s.style.boxSizing="border-box"}}},ET=(t,e)=>{let n=t.ownerDocument.createElement("div");return EC(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){EC(n,o)},destroy(){n.remove()}}},TT=(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"),p=n.createElement("div"),u=n.createElement("aside"),g=n.createElement("div"),f=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;c.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",u.appendChild(g),o.insertBefore(l,t),p.appendChild(t);let v=null,h=()=>{v?.disconnect(),v=null},M=null,A=()=>{M=e?.launcher?.detachedPanel===!0?AT(e):null};A();let T=()=>{MT(l,c,p,u,g,e,f,M)},F=null,P=()=>{F?.(),F=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(F=Kc(()=>{A(),T()}))},K=()=>{h(),Jn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(v=new ResizeObserver(()=>{T()}),v.observe(l)))},x=!1,L=()=>{T(),K(),f&&!x&&l.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,wT(l,Jn(e)))},w=l.ownerDocument.defaultView,O=()=>{L()};return w?.addEventListener("resize",O),Jn(e).reveal==="push"?(c.appendChild(p),c.appendChild(u),l.appendChild(c)):(l.appendChild(p),l.appendChild(u)),L(),P(),{mode:"docked",host:g,shell:l,syncWidgetState(G){let ie=G.launcherEnabled?G.open:!0;f!==ie&&(f=ie,L())},updateConfig(G){e=G,(e?.launcher?.enabled??!0)===!1&&(f=!0),A(),L(),P()},destroy(){w?.removeEventListener("resize",O),F?.(),F=null,h(),o.isConnected&&(i&&i.parentNode===o?o.insertBefore(t,i):o.appendChild(t)),l.remove()}}},PC=(t,e)=>Rt(e)?TT(t,e):ET(t,e);var ja={desktop:{w:1280,h:800},mobile:{w:390,h:844}},IC=.15,LC=1.5,Rg="persona-preview-shell-theme",kT={load:()=>null,save:()=>{},clear:()=>{}},PT=["How do I get started?","Pricing & plans","Talk to support"];function Wg(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function IT(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 HC(t){let e=IT(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}; }
|
|
@@ -149,7 +149,7 @@ _Details: ${n.message}_`:o}var bu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
149
149
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
150
150
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
151
151
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
152
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
152
|
+
.preview-workspace-card.short { height: 96px; }`}function RC(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Rg);o||(o=n.createElement("style"),o.id=Rg,n.head.appendChild(o)),o.textContent=HC(e)}var LT=`
|
|
153
153
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
154
154
|
<div class="preview-iframe-chrome">
|
|
155
155
|
<span class="preview-iframe-dot"></span>
|
|
@@ -168,7 +168,7 @@ _Details: ${n.message}_`:o}var bu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
168
168
|
<div class="preview-iframe-line body"></div>
|
|
169
169
|
<div class="preview-iframe-line body"></div>
|
|
170
170
|
</div>
|
|
171
|
-
</div>`,
|
|
171
|
+
</div>`,HT=`
|
|
172
172
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
173
173
|
<div class="preview-iframe-line hero"></div>
|
|
174
174
|
<div class="preview-iframe-line body"></div>
|
|
@@ -181,8 +181,8 @@ _Details: ${n.message}_`:o}var bu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
181
181
|
<div class="preview-workspace-card short"></div>
|
|
182
182
|
<div class="preview-workspace-card short"></div>
|
|
183
183
|
</div>
|
|
184
|
-
</div>`;function
|
|
185
|
-
${
|
|
184
|
+
</div>`;function WC(t,e,n,o){let s=`
|
|
185
|
+
${LT}
|
|
186
186
|
<div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,i=`
|
|
187
187
|
<div class="preview-workspace-shell">
|
|
188
188
|
<div class="preview-workspace-topbar">
|
|
@@ -194,7 +194,7 @@ _Details: ${n.message}_`:o}var bu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
194
194
|
</div>
|
|
195
195
|
<div class="preview-workspace-body">
|
|
196
196
|
<div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
|
|
197
|
-
${
|
|
197
|
+
${HT}
|
|
198
198
|
</div>
|
|
199
199
|
</div>
|
|
200
200
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -202,16 +202,16 @@ _Details: ${n.message}_`:o}var bu=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
202
202
|
<head>
|
|
203
203
|
<meta charset="UTF-8">
|
|
204
204
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
205
|
-
<link rel="stylesheet" href="${
|
|
206
|
-
<style id="${
|
|
205
|
+
<link rel="stylesheet" href="${Wg(o)}">
|
|
206
|
+
<style id="${Rg}">${HC(e)}</style>
|
|
207
207
|
</head>
|
|
208
208
|
<body>
|
|
209
209
|
${n?i:s}
|
|
210
210
|
</body>
|
|
211
|
-
</html>`}var
|
|
212
|
-
${L?`<div class="preview-frame-meta"><span class="preview-frame-label">${
|
|
211
|
+
</html>`}var RT=()=>[{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()}],WT=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function BT(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"&&WT(e)?[...RT(),...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 _T(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},s={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:PT:t.suggestionChips,initialMessages:BT(e,t,n),storageAdapter:kT};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 OT(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 _T(OT(t,e),n,t.appendedMessages??[])}function BC(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 DT(t,e){let n={...e},o=[],s=[],i=null,l=!1,c=1,p=1,u=0;function g(){return n.device??"desktop"}function f(){return n.zoom??c}function v(){let P=getComputedStyle(t),K=parseFloat(P.paddingLeft)+parseFloat(P.paddingRight),x=parseFloat(P.paddingTop)+parseFloat(P.paddingBottom),L=40,w=(n.compareMode??"off")!=="off",O=(t.clientWidth-K-L)/(w?2:1),G=t.clientHeight-x-L;if(O<=0||G<=0)return 1;let ie=ja[g()]??ja.desktop;return Math.min(O/ie.w,G/ie.h,1)}function h(){c=v();let P=Math.max(IC,Math.min(LC,f()));p=P;let K=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let x of K){let L=x.dataset.device??"desktop",w=ja[L]??ja.desktop;x.style.width=`${w.w*P}px`,x.style.height=`${w.h*P}px`,L==="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 M(){n.onBeforeDestroy?.();for(let P of o)P.destroy();for(let P of s)P();o=[],s=[]}function A(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function T(){if(l)return;M();let P=++u,K=BC(n),x=g(),L=(n.compareMode??"off")!=="off",w=(n.scene??"conversation")==="minimized",O=n.widgetCssPath??"/widget-dist/widget.css",G=n.buildSrcdoc??WC,ie=x==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",oe=V=>`<div class="${ie}" data-mount-id="${V.mountId}" data-device="${x}" data-shell-mode="${V.shellMode}">
|
|
212
|
+
${L?`<div class="preview-frame-meta"><span class="preview-frame-label">${Wg(V.label)}</span></div>`:""}
|
|
213
213
|
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${V.mountId}"></iframe>
|
|
214
|
-
</div>`,S=L?`<div class="preview-compare-grid">${K.map(V=>`<div class="preview-compare-cell">${oe(V)}</div>`).join("")}</div>`:`<div class="preview-single">${oe(K[0])}</div>`;n.morphContainer?n.morphContainer(t,S):t.innerHTML=S,h();let
|
|
214
|
+
</div>`,S=L?`<div class="preview-compare-grid">${K.map(V=>`<div class="preview-compare-cell">${oe(V)}</div>`).join("")}</div>`:`<div class="preview-single">${oe(K[0])}</div>`;n.morphContainer?n.morphContainer(t,S):t.innerHTML=S,h();let _=A(),R=0,I=_.length,Y=()=>{if(l||P!==u)return;for(let ae of _){let ce=ae.dataset.mountId;if(!ce||!ae.contentDocument)continue;let me=K.find(we=>we.mountId===ce);if(!me)continue;let Ce=()=>{},ue=Rt(me.config),_e=ue?(()=>{let we=ae.contentDocument?.getElementById(`preview-content-${ce}`);if(!we)return null;let $=PC(we,me.config),Pe=ae.contentDocument.createElement("div");Pe.id=ce,Pe.style.height="100%",Pe.style.display="flex",Pe.style.flexDirection="column",Pe.style.flex="1",Pe.style.minHeight="0",$.host.appendChild(Pe);let Ne=()=>$.syncWidgetState(ct.getState()),xe=Ce;return Ce=()=>{$.destroy(),xe()},Pe.__syncDock=Ne,Pe.__hostLayout=$,Pe})():ae.contentDocument.getElementById(ce);if(!_e)continue;let ct=AC(_e,me.config);if(o.push(ct),ue&&_e.__syncDock){let we=_e.__syncDock,$=ct.on("widget:opened",we),Pe=ct.on("widget:closed",we),Ne=Ce;Ce=()=>{$(),Pe(),Ne()},we()}s.push(Ce),w&&ct.close()}let V=n.scene??"conversation";if(V==="messages")for(let ae of o)ae.showHistory({focus:!1});if(V==="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:_,controllers:[...o]})};for(let V of _){let ae=V.dataset.mountId;if(!ae)continue;let ce=K.find(me=>me.mountId===ae);ce&&(V.addEventListener("load",()=>{R++,R>=I&&Y()},{once:!0}),V.srcdoc=G(ae,ce.shellMode,Rt(ce.config),O))}I===0&&Y()}function F(){if(l)return;let P=BC(n);if(o.length!==P.length){T();return}if(P.some(x=>{let L=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${x.mountId}"]`);return!L||L.dataset.shellMode!==x.shellMode})){T();return}o.forEach((x,L)=>{x.update(P[L].config),(n.scene??"conversation")==="minimized"&&x.close()});for(let x of P){let L=t.querySelector(`iframe[data-mount-id="${x.mountId}"]`);L&&RC(L,x.shellMode)}n.onAfterUpdate?.({iframes:A(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(i=new ResizeObserver(()=>{l||h()}),i.observe(t)),T(),{update(P){if(l)return;let K=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},K?T():F()},destroy(){l||(l=!0,M(),i?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){l||(n={...n,zoom:void 0},h())},getIframes(){return A()},getScale(){return p},setZoom(P){l||(n={...n,zoom:P},h())}}}export{DT as createThemePreview};
|