@runtypelabs/persona 4.21.1 → 4.22.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.
Files changed (77) hide show
  1. package/dist/{approval-ui-RNNBR5R3.js → approval-ui-K7R5Q5OC.js} +1 -1
  2. package/dist/approval-ui.cjs +2 -2
  3. package/dist/approval-ui.d.cts +73 -2
  4. package/dist/approval-ui.d.ts +73 -2
  5. package/dist/approval-ui.js +2 -2
  6. package/dist/artifacts-ui-F4N6VMKF.js +7 -0
  7. package/dist/artifacts-ui.cjs +1 -1
  8. package/dist/artifacts-ui.d.cts +73 -2
  9. package/dist/artifacts-ui.d.ts +73 -2
  10. package/dist/artifacts-ui.js +1 -1
  11. package/dist/chunk-NQLDCJAP.js +4 -0
  12. package/dist/codegen.cjs +1 -1
  13. package/dist/codegen.js +1 -1
  14. package/dist/context-mentions.d.cts +73 -2
  15. package/dist/context-mentions.d.ts +73 -2
  16. package/dist/event-stream-view-FKWDY3UB.js +1 -0
  17. package/dist/event-stream-view.cjs +1 -1
  18. package/dist/event-stream-view.d.cts +73 -2
  19. package/dist/event-stream-view.d.ts +73 -2
  20. package/dist/event-stream-view.js +1 -1
  21. package/dist/forms-ui.d.cts +73 -2
  22. package/dist/forms-ui.d.ts +73 -2
  23. package/dist/index.cjs +63 -63
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +136 -5
  26. package/dist/index.d.ts +136 -5
  27. package/dist/index.global.js +48 -48
  28. package/dist/index.global.js.map +1 -1
  29. package/dist/index.js +64 -64
  30. package/dist/index.js.map +1 -1
  31. package/dist/launcher.global.js +2 -2
  32. package/dist/launcher.global.js.map +1 -1
  33. package/dist/session-reconnect.d.cts +73 -2
  34. package/dist/session-reconnect.d.ts +73 -2
  35. package/dist/smart-dom-reader.d.cts +73 -2
  36. package/dist/smart-dom-reader.d.ts +73 -2
  37. package/dist/theme-editor-preview.cjs +64 -64
  38. package/dist/theme-editor-preview.d.cts +73 -2
  39. package/dist/theme-editor-preview.d.ts +73 -2
  40. package/dist/theme-editor-preview.js +45 -45
  41. package/dist/theme-editor.cjs +4 -4
  42. package/dist/theme-editor.d.cts +73 -2
  43. package/dist/theme-editor.d.ts +73 -2
  44. package/dist/theme-editor.js +2 -2
  45. package/dist/theme-reference.cjs +1 -1
  46. package/dist/theme-reference.d.cts +65 -1
  47. package/dist/theme-reference.d.ts +65 -1
  48. package/dist/theme-reference.js +1 -1
  49. package/dist/webmcp-polyfill.js +1 -4
  50. package/dist/webmcp-runtime-JI7T4QYF.js +6 -0
  51. package/dist/webmcp-runtime.cjs +2 -2
  52. package/dist/webmcp-runtime.d.cts +34 -2
  53. package/dist/webmcp-runtime.d.ts +34 -2
  54. package/dist/webmcp-runtime.js +2 -2
  55. package/package.json +2 -2
  56. package/src/components/artifact-preview.ts +5 -0
  57. package/src/components/event-stream-badge-theming.test.ts +159 -0
  58. package/src/components/event-stream-view.ts +50 -20
  59. package/src/generated/runtype-openapi-contract.ts +8 -0
  60. package/src/index-core.ts +2 -0
  61. package/src/runtime/init.registry.test.ts +56 -0
  62. package/src/runtime/init.ts +17 -0
  63. package/src/types/theme.ts +41 -1
  64. package/src/types.ts +38 -1
  65. package/src/ui.reasoning-display.test.ts +136 -2
  66. package/src/ui.ts +41 -10
  67. package/src/utils/__snapshots__/tokens-parity.test.ts.snap +1740 -0
  68. package/src/utils/formatting.ts +22 -0
  69. package/src/utils/theme.ts +16 -0
  70. package/src/utils/tokens.ts +59 -0
  71. package/src/webmcp-bridge.test.ts +132 -23
  72. package/src/webmcp-bridge.ts +26 -2
  73. package/src/webmcp-runtime-entry.ts +71 -11
  74. package/dist/artifacts-ui-J6AKUGTS.js +0 -7
  75. package/dist/chunk-HBE7LFNT.js +0 -4
  76. package/dist/event-stream-view-73NWKWVQ.js +0 -1
  77. package/dist/webmcp-runtime-P3CHZRHF.js +0 -6
@@ -1,22 +1,22 @@
1
- import{a as yc,b as Qh,c as nu,d as fa,e as bc,f as ha,g as vc,h as ya,i as Xh,j as ba}from"./chunk-CPVD5P5B.js";import{b as Mh,c as cc,d as Eh,e as oi,f as Th,g as dc,h as kh,i as Ph,j as Ih,k as pc,l as uc,m as Zp,n as gc,o as ma,p as Lh,q as Hh,r as Rh,s as Wh}from"./chunk-HBE7LFNT.js";import{a as qh,b as zh,c as Yo,d as hs,e as jh,f as Vh,g as Kh,h as tu,i as Gh}from"./chunk-VK6JOIYJ.js";import{a as Tt,b as Sh,c as ac,e as ni,f as xh,g as lc,h as Ah,j as _h,k as Oh,l as he,m as _t,n as sn,o as mc,p as Yh,q as Jh,u as Zh,v as ri,w as Jo}from"./chunk-NIKYKSNZ.js";import{a as fs,d as ou}from"./chunk-EFJBUH5F.js";import{a as Bh,c as Dh,d as hc,e as eu,f as $h}from"./chunk-UTVLOTWB.js";import{a as Nh,c as Fh,d as Uh}from"./chunk-R2TMIMDI.js";import{a as Zt}from"./chunk-7NQ4ZTHF.js";import{b as fc}from"./chunk-Q735PSZL.js";import{a as k,c as X,d as Wn}from"./chunk-76IELU7F.js";var ey=/^\s*\|?[\s:|-]*-[\s:|-]*$/,ty=t=>t.includes("|"),ny=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())},sx=t=>`| ${t.join(" | ")} |`,ix=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,ax=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),oy=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(!ty(s)||ey.test(s)||!ey.test(i))continue;let l=ny(s).length;if(l<1)continue;let c=ix(l);e[o+1]!==c&&(e[o+1]=c,n=!0);let p=o+2;for(;p<e.length;p++){let g=e[p];if(g.trim()===""||!ty(g))break;let u=sx(ax(ny(g),l));e[p]!==u&&(e[p]=u,n=!0)}o=p-1}return n?e.join(`
3
- `):t};var ry="var(--persona-md-table-scroll-fade, 24px)",sy=new WeakSet;function ay(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 iy(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":ry),t.style.setProperty("--persona-fade-r",s<=1?"0px":ry)}function ru(t){sy.has(t)||(sy.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&iy(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(iy)}var{setLoader:YT,load:lx}=Tt({fallbackImport:()=>import("./webmcp-runtime-P3CHZRHF.js")});var ly=lx;function Gn(t){return t==="card"?"collapsed":t}function si(t){return t.split(";",1)[0].trim().toLowerCase()}function cx(t,e){if(!t)return;let n=Object.entries(t);for(let[s,i]of n)if(si(s)===e)return{mode:Gn(i),selector:si(s)};let o=`${e.split("/",1)[0]}/*`;for(let[s,i]of n)if(si(s)===o)return{mode:Gn(i),selector:o}}function dx(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:Gn(o.files),matchedBy:{type:"files"}};let c=e.file.mimeType?si(e.file.mimeType):void 0,p=c?cx(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:Gn(o.files.default),matchedBy:{type:"files"}}}let s=o.byKind?.[e.artifactType];if(s)return{mode:Gn(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let i=o.byType?.[e.artifactType];if(i)return{mode:Gn(i),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let l=e.presentation?.preferredMode;return l?{mode:Gn(l),matchedBy:{type:"preferredMode"}}:o.default?{mode:Gn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Er(t,e){return dx(t,e).mode}function va(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 px="agent_",ux="flow_";function cy(t){return t.startsWith(px)?{kind:"agentId",agentId:t}:t.startsWith(ux)?{kind:"flowId",flowId:t}:null}function dy(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 g=cy(c);if(g)return g;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=cy(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 Cc(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ii(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function py(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}import{parse as gx,ARR as mx,OBJ as fx,STR as hx}from"partial-json";var su="ask_user_question",Ca=8,ai="data-persona-ask-sheet-for",yx="Other",bx="Other\u2026",gy="Type your own answer here",my="Send",vx="Next",Cx="Back",wx="Submit all",Sx="Skip",xx=3,iu="data-ask-current-index",au="data-ask-question-count",fy="data-ask-answers",lu="data-ask-grouped",hy="data-ask-layout",Ax=t=>t.layout==="pills"?"pills":"rows",Mx=t=>t.getAttribute(hy)==="pills"?"pills":"rows",uy=!1,yy=t=>t.replace(/["\\]/g,"\\$&"),ys=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===su,cu=t=>t?.features?.askUserQuestion??{},li=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=gx(s,hx|fx|mx);if(i&&typeof i=="object")return{payload:i,complete:n}}catch{}return{payload:null,complete:n}},wa=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Ca&&!uy&&(uy=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ca}.`)),e.slice(0,Ca)},Ex=t=>wa(t)[0]??null,Tx=(t,e)=>wa(t)[e]??null,kx=(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))},by=(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},Px=(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 g=k("span","persona-ask-row-description");g.textContent=t.description,l.appendChild(g)}i.appendChild(l);let p=by(n,o,e);p&&i.appendChild(p)}else i.textContent=t.label,t.description&&(i.title=t.description);return i},Ix=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},Lx=(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(u=>u&&typeof u.label=="string"&&u.label.length>0);if(p.length===0&&!n){for(let u=0;u<xx;u++)i.appendChild(Ix(o));return i}if(p.forEach((u,f)=>{i.appendChild(Px(u,f,o,l))}),t?.allowFreeText!==!1){let u=o==="rows"?yx:bx;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??gy,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",e.freeTextLabel??u),v.appendChild(h),f.appendChild(v);let x=by(o,l,p.length);x&&f.appendChild(x),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??u,i.appendChild(f)}}return i},vy=(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??gy,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??my,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Hx=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??my,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},Rx=(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??Cx,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??Sx,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??wx:n.nextLabel??vx,c.setAttribute("data-ask-user-action",p?"submit-all":"next"),c.disabled=!0,i.appendChild(c),o.appendChild(i),o},bs=t=>{let e=t.getAttribute(fy);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},Cy=(t,e)=>{t.setAttribute(fy,JSON.stringify(e))},Qn=t=>{let e=Number(t.getAttribute(iu)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Wx=(t,e)=>{t.setAttribute(iu,String(Math.max(0,Math.floor(e))))},ci=t=>{let e=Number(t.getAttribute(au)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Tr=t=>t.getAttribute(lu)==="true",Bx=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((s,i)=>{let l=typeof s?.question=="string"?s.question:"";if(l&&Object.prototype.hasOwnProperty.call(n,l)){let c=n[l];(typeof c=="string"||Array.isArray(c))&&(o[i]=c)}}),o},_x=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},wc=(t,e)=>{let{payload:n}=li(e),o=wa(n),s=bs(t),i={},l=new Set;return o.forEach((c,p)=>{let g=typeof c?.question=="string"?c.question:"";g&&(l.has(g)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${g}"; later answer wins.`),l.add(g),Object.prototype.hasOwnProperty.call(s,p)&&(i[g]=s[p]))}),i},wy=t=>{let e=bs(t),n=Qn(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 g=p.getAttribute("data-option-label")??"",u=s.has(g);p.setAttribute("aria-pressed",u?"true":"false"),p.classList.toggle("persona-ask-pill-selected",u)});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="")},Sy=t=>{if(!Tr(t))return;let e=bs(t),n=Qn(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}},du=(t,e,n)=>{let o=cu(n),s=Mx(t),{payload:i,complete:l}=li(e),c=Tr(t),p=Qn(t),g=ci(t),u=c?Tx(i,p):Ex(i),f=!!u?.multiSelect,v=t.querySelector('[data-ask-step-inline="true"]');v&&(v.textContent=c?`${p+1}/${g}`:"");let h=t.querySelector('[data-ask-stepper="true"]');h&&h.remove();let x=t.querySelector('[data-ask-question="true"]');if(x){let P=typeof u?.question=="string"?u.question:"";x.textContent=P,x.classList.toggle("persona-ask-question-skeleton",!P&&!l)}let E=t.querySelector('[data-ask-pill-list="true"]');if(E){let P=Lx(u,o,l,s);E.replaceWith(P)}if(s!=="rows"){let P=t.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(vy(o,s))}let M=t.querySelector('[data-ask-multi-actions="true"]');!c&&f&&!M?t.appendChild(Hx(o)):(!f||c)&&M&&M.remove(),t.setAttribute("data-multi-select",f?"true":"false");let F=t.querySelector('[data-ask-nav-row="true"]');if(c){let P=Rx(p,g,o);F?F.replaceWith(P):t.appendChild(P)}else F&&F.remove();wy(t),Sy(t)},Ox=(t,e,n)=>{let o=cu(e),s=Ax(o),i=t.toolCall.id,l=wa(n),c=Math.max(1,l.length),p=c>1,g=Bx(t,l),u=p?_x(t,c):0,f=k("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(ai,i),f.setAttribute("data-tool-call-id",i),f.setAttribute("data-message-id",t.id),f.setAttribute(au,String(c)),f.setAttribute(iu,String(u)),f.setAttribute(lu,p?"true":"false"),f.setAttribute(hy,s),Cy(f,g),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),kx(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 x=k("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",v.appendChild(x),f.appendChild(v);let M=k("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),f.appendChild(M),s!=="rows"&&f.appendChild(vy(o,s)),du(f,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Dx=(t,e,n)=>{let{payload:o}=li(e),s=Math.max(1,wa(o).length);s>ci(t)&&(t.setAttribute(au,String(s)),s>1&&!Tr(t)&&t.setAttribute(lu,"true")),du(t,e,n)};var Sc=(t,e,n)=>{if(!n||!ys(t)||cu(e).enabled===!1)return;let s=t.toolCall.id;n.querySelectorAll(`[${ai}]`).forEach(g=>{g.getAttribute(ai)!==s&&g.remove()});let l=n.querySelector(`[${ai}="${yy(s)}"]`);if(l){Dx(l,t,e);return}let{payload:c}=li(t),p=Ox(t,e,c);n.appendChild(p)},di=(t,e)=>{if(!t)return;let n=e?`[${ai}="${yy(e)}"]`:`[${ai}]`;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)})},pu=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),kr=(t,e)=>{let n=bs(t),o=Qn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,Cy(t,n),wy(t),Sy(t)},xc=(t,e,n,o)=>{let s=ci(t),i=Math.max(0,Math.min(s-1,o));Wx(t,i),du(t,e,n)};var Pr="suggest_replies";var Nx={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},Ay={name:Pr,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:Nx,origin:"sdk",annotations:{readOnlyHint:!0}},My=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Sa=t=>t.variant==="tool"&&t.toolCall?.name===Pr,Fx=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},Ey=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!Sa(n))continue;let o=Fx(n.toolCall?.args);return o.length>0?o:null}return null},xy=new Set,Ux=(t,e,n)=>{let o=`${t}:${e}:${n}`;xy.has(o)||(xy.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Ir=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&&Ux(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 $x={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ca,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},qx={name:su,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:$x,origin:"sdk",annotations:{readOnlyHint:!0}},Ac=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(qx),Ir(t).expose&&e.push(Ay),e};var Ty="4.21.1";var Lr=Ty;var pi="[Image]";function ky(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function Mc(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function ko(t){return{type:"text",text:t}}function Py(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var Iy=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],jx=["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"],Zo=[...Iy,...jx];function Vx(t){return Iy.includes(t)||t.startsWith("image/")}function Ec(t){return Vx(t.type)}function Ly(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function Hy(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;Ec(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 Ry(t,e=Zo,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 Kx(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Wy(t,e){let n=Kx(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 Gx=["user","assistant","system"],Qx=0;function By(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function Tc(t){return typeof t=="string"?t:void 0}function Xx(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?ko(e.text):null;case"image":return typeof e.image=="string"?Py(e.image,{mimeType:Tc(e.mimeType),alt:Tc(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?Ly(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...Tc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...Tc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function Yx(t,e){let n=By(e),o=t.map(l=>By(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,g=i>0?s[i-1]:null,u=c+1<o.length?o[c+1]:null,f=u!==null&&n!==null?Math.min(u,n):u??n;for(let v=0;v<p;v+=1)s[i+v]=f!==null?f-(p-v):g!==null?g+v+1:Qx+v;i=c+1}return s.map(l=>new Date(l).toISOString())}function _y(t,e){let n=Yx(t,e?.beforeCreatedAt),o=[];return t.forEach((s,i)=>{if(typeof s?.id!="string"||s.id===""||!Gx.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(Xx).filter(u=>u!==null),g=ky(p);o.push({id:s.id,role:l,content:g||(Mc(p)?pi:""),createdAt:c,...p.length>0&&{contentParts:p}});return}o.push({id:s.id,role:l,content:"",createdAt:c})}),o}function xa(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 Aa(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 Jx="https://api.runtype.com/v1/dispatch",Oy="https://api.runtype.com",Ue=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Dy=32768,uu=49152,Ny=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:""}},Fy=t=>"reason"in t?t.reason:void 0,Uy="The identity proof was not admitted; account history is unavailable",$y="The identity proof was rejected",qy="The request carried no visitor credential",zy="The stored visitor belongs to a different signed-in user",gu=(t,e)=>t instanceof Ue&&t.code===e;function Zx(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let s=e.indexOf("/");if(s>0){let i=e.slice(s+1).split(";")[0]?.trim()??"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var mu=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function eA(t){switch(t){case"json":return Rh;case"regex-json":return Hh;case"xml":return Wh;default:return Lh}}var jy=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function tA(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=jy(n);if(!jy(o))return t;if(!s||o===n||o.startsWith(n))return e;let l=ma(t);return ma(e)!==null&&l===null?e:t}var Ma=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??Jx,this.headers={"Content-Type":"application/json","X-Persona-Version":Lr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??eA(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 ly().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Mh,getToolDisplayTitle:cc,loadPolyfill:Th});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=dy(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$/,"")||Oy}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let s=n.conversationId,i=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!s||!i)throw new Ue("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),p=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":Lr,"X-Visitor-Token":i},signal:e.signal});if(p.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(p),null,!0);continue}if(!p.ok)throw await this.historyErrorFor(p,!0);return p}}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&&Fy(n)===Fy(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.historyIdentitySubscribers])s(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.routing(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,p={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}},g=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Lr},body:JSON.stringify(p)});if(g.status===400&&o){let f={...p};delete f.durableRecovery,g=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Lr},body:JSON.stringify(f)})}if(!g.ok){let f=await g.json().catch(()=>({error:"Session initialization failed"}));if(n&&g.status===403&&f.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),c)throw new Ue("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw g.status===403&&f.error==="durable_recovery_disabled"?new Ue("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&g.status===401&&f.error==="visitor_required"?new Ue("visitor_required","Visitor credential no longer resolves"):c&&g.status===404?new Ue("not_found","Conversation not found"):g.status===401?new Error(`Invalid client token: ${f.hint||f.error}`):g.status===403?new Error(`Origin not allowed: ${f.hint||f.error}`):new Error(f.error||"Failed to initialize session")}let u=await g.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.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.createClientSession({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(s,e,!1)}catch(s){if(!gu(s,"not_found")&&!gu(s,"visitor_required")&&!gu(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.createClientSession({storedSessionId:o}),i=await this.claimFirstConversation(s);return this.finishInit(i,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.createClientSession({storedSessionId:n,identityProof:e}),i=this.finishInit(s,o,!1);return this.clientSession=i,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),i}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let s=e.conversationId;return s&&n&&(o||s!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:s}),this.config.setStoredSessionId?.(e.sessionId),s&&(this.config.setStoredConversationId?.(s),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Ue("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 Ue("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":Lr},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 Ue("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 Ue("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 Ue("proof_not_admitted",Uy);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 Ue("invalid_identity_proof",$y);if(s.includes("visitor token required"))throw new Ue("visitor_token_missing",qy);if(s.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Ue("visitor_identity_mismatch",zy);return this.reinitWithProof(n)}if(s.includes("expired")||s.includes("not found"))return this.clearClientSession(),this.initSession();throw new Ue("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new Ue("not_found","Conversation not found");if(e.status===429){let s=Number.parseInt(e.headers.get("Retry-After")??"",10);return new Ue("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 Ue("proof_not_admitted",Uy);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 Ue("invalid_identity_proof",$y)):s.includes("visitor token required")?new Ue("visitor_token_missing",qy):s.includes("visitor_identity_mismatch")?new Ue("visitor_identity_mismatch",zy):new Ue("unauthorized",o||"History request was not authorized")}return new Ue("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 Ue("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Ue("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(s==="admitted")throw new Ue("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,g=await this.readVisitorToken();if(!g&&!n.visitorTokenOptional)throw new Ue("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(e,{...n.query,sessionId:s.sessionId}),{method:n.method,headers:{"X-Persona-Version":Lr,...g?{"X-Visitor-Token":g}:{},...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(u.status===401&&!c){c=!0,s=await this.recoverFromUnauthorized(await this.readErrorCode(u),i,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let f=u.headers.get("X-History-Identity-Status"),v=await u.json().catch(()=>{});if(l&&l.revision()!==p)throw new Ue("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 Ue("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(Ny),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:Ny(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 g=p.displayContent.length;if(g>Dy)throw new Ue("payload_too_large",`displayContent exceeds the ${Dy} character limit`);o+=g}if(o>uu)throw new Ue("payload_too_large",`Display projection batch exceeds the ${uu} 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<=uu,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=py();this.currentClientTurnId=o;let s=()=>this.currentClientTurnId===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=await this.initSession();if(new Date>=new Date(l.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let x=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:x}),x}let c=await this.buildPayload(e.messages),p=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null,g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,u=this.isHistoryCapable(),f={sessionId:l.sessionId,messages:e.messages.filter(mu).map(x=>{let E=u?xa(x):void 0;return{id:x.id,role:x.role,content:x.contentParts??x.llmContent??x.rawContent??x.content,...E!==void 0&&{displayContent:E}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},{response:v,commit:h}=await this.sendWithClientToolsDiff(l.sessionId,c.clientTools,x=>{let E={...f,...x};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",E),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Lr,...p?{"X-Visitor-Token":p}:{}},body:JSON.stringify(E),signal:e.signal})});if(!v.ok){let x=await v.json().catch(()=>({error:"Chat request failed"}));if(v.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let M=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:M}),M}if(v.status===429){let M=new Error(x.hint||"Message limit reached for this session.");throw i({type:"error",error:M}),M}if(v.status===410&&x.error==="conversation_deleted"){let M=new Ue("conversation_deleted","This conversation was deleted");throw i({type:"error",error:M}),M}let E=new Error(x.error||"Failed to send message");throw i({type:"error",error:E}),E}if(!v.body){let x=new Error("No response body received");throw i({type:"error",error:x}),x}h(),i({type:"status",status:"connected"});try{await this.streamResponse(v.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 Ue)&&!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?Eh(n):void 0,c=this.clientToolsFingerprintSessionId===e,p=i&&c&&this.lastSentClientToolsFingerprint===l,g=!i&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,f;for(let v=0;;v++){if(f=await o({...i&&(u||!p)&&n?{clientTools:n}:{},...g?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),f.status===409&&v===0&&i&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.sentNonEmptyClientToolsSessionId=e:g&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let s=this.isClientTokenMode(),i=s?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Oy}/resume`,l,c=null;if(s){let u=await this.initSession();l=u.sessionId,u.durableRecovery?.enabled===!0&&(c=await this.readVisitorToken())}let p={"Content-Type":"application/json",...c?{"X-Visitor-Token":c}:{},...this.headers};this.getHeaders&&Object.assign(p,await this.getHeaders());let g={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(l&&(g.sessionId=l),s&&l){let u=[...Ac(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:f,commit:v}=await this.sendWithClientToolsDiff(l,u,h=>{let x={...g,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",x),fetch(i,{method:"POST",headers:p,body:JSON.stringify(x),signal:o?.signal})},{emptyMeansReplace:!0});return f.ok&&v(),f}return fetch(i,{method:"POST",headers:p,body:JSON.stringify(g),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(i=>i.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=e.slice().filter(mu).filter(g=>g.role==="user"||g.role==="assistant"||g.role==="system").filter(g=>!g.variant||g.variant==="assistant").sort((g,u)=>{let f=new Date(g.createdAt).getTime(),v=new Date(u.createdAt).getTime();return f-v}).map(g=>({role:g.role,content:g.contentParts??g.llmContent??g.rawContent??g.content,createdAt:g.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=[...Ac(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(mu).sort((g,u)=>{let f=new Date(g.createdAt).getTime(),v=new Date(u.createdAt).getTime();return f-v}).map(g=>({role:g.role,content:g.contentParts??g.llmContent??g.rawContent??g.content,createdAt:g.createdAt})),s=this.routing(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[g,u]of Object.entries(s.targetPayload))g!=="messages"&&(i[g]=u);let l=[...Ac(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 g=await this.requestMiddleware({payload:{...i},config:this.config});if(g&&typeof g=="object"){let u=g;return i.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=i.clientTools),u}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",g)}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=u=>{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(),...u!==void 0&&{partId:u}};return o.current=f,s(f),f},g=u=>o.current?o.current:p(u);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 u=g(c.partId);c.partId!==void 0&&!u.partId&&(u.partId=c.partId),u.content+=c.text,s(u)}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(),g=0,u=()=>p+g++,f=D=>{let Q=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,b=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,O=D.tools?D.tools.map(N=>({...N,chunks:N.chunks?[...N.chunks]:void 0})):void 0;return{...D,reasoning:Q,toolCall:b,tools:O}},v=D=>{if(D.role!=="assistant"||D.variant)return!0;let Q=Array.isArray(D.contentParts)&&D.contentParts.length>0,b=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||Q||b||!!D.stopReason},h=D=>{v(D)&&n({type:"message",message:f(D)})},x=null,E=null,M={current:null},F={current:null},P=null,K="",A=new Map,L=new Map,w=new Map,_=new Map,G=new Map,le={lastId:null,byStep:new Map},ee={lastId:null,byCall:new Map},S=D=>{if(D==null)return null;try{return String(D)}catch{return null}},B=D=>S(D.stepId??D.step_id??D.step??D.parentId??D.flowStepId??D.flow_step_id),R=D=>S(D.callId??D.call_id??D.requestId??D.request_id??D.toolCallId??D.tool_call_id??D.stepId??D.step_id),I=o,Z=!1,V=()=>{if(x)return x;let D,Q="",b=P;return!Z&&I?(D=I,Z=!0,Q=s??""):I&&b?D=`${I}_${b}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:D,role:"assistant",content:Q,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(x),x},ce=(D,Q)=>{le.lastId=Q,D&&le.byStep.set(D,Q)},ie=(D,Q)=>{let b=D.reasoningId??D.id,O=B(D);if(b){let $=String(b);return ce(O,$),$}if(O){let $=le.byStep.get(O);if($)return le.lastId=$,$}if(le.lastId&&!Q)return le.lastId;if(!Q)return null;let N=`reason-${u()}`;return ce(O,N),N},me=D=>{let Q=_.get(D);if(Q)return Q;let b={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:D,status:"streaming",chunks:[]}};return _.set(D,b),h(b),b},Te=(D,Q)=>{ee.lastId=Q,D&&ee.byCall.set(D,Q)},Le=new Set,Ce=new Map,Ze=new Set,we=new Map,U=D=>{if(!D)return!1;let Q=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return Q==="emit_artifact_markdown"||Q==="emit_artifact_component"},ke=(D,Q)=>{let b=D.toolId??D.id,O=R(D);if(b){let $=String(b);return Te(O,$),$}if(O){let $=ee.byCall.get(O);if($)return ee.lastId=$,$}if(ee.lastId&&!Q)return ee.lastId;if(!Q)return null;let N=`tool-${u()}`;return Te(O,N),N},$e=D=>{let Q=G.get(D);if(Q)return Q;let b={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:D,status:"pending"}};return G.set(D,b),h(b),b},mt=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let Q=Number(D);if(!Number.isNaN(Q)&&Number.isFinite(Q))return Q;let b=Date.parse(D);if(!Number.isNaN(b))return b}return Date.now()},Re=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Ie=new Map,be=new Map,lo=new Map,co=(D,Q,b)=>{let O=lo.get(D);O||(O=[],lo.set(D,O));let N=0,$=O.length;for(;N<$;){let re=N+$>>>1;O[re].seq<Q?N=re+1:$=re}O[N]?.seq===Q?O[N]={seq:Q,text:b}:O.splice(N,0,{seq:Q,text:b});let te="";for(let re=0;re<O.length;re++)te+=O[re].text;return te},xs=(D,Q)=>{let b=Re(Q),O=be.get(D.id),N=tA(O,b);D.rawContent=N;let $=Ie.get(D.id),te=Be=>{let Pt=D.content??"";Be.trim()!==""&&(Pt.trim().length===0||Be.startsWith(Pt)||Be.trimStart().startsWith(Pt.trim()))&&(D.content=Be)},re=()=>{if($){let Be=$.close?.();Be instanceof Promise&&Be.catch(()=>{})}Ie.delete(D.id),be.delete(D.id),D.streaming=!1,h(D)};if(!$){te(b),re();return}let ae=ma(N);if(ae!==null&&ae.trim()!==""){te(ae),re();return}let de=Be=>{let Pt=typeof Be=="string"?Be:Be?.text??null;if(Pt!==null&&Pt.trim()!=="")return Pt;let wt=$.getExtractedText();return wt!==null&&wt.trim()!==""?wt:b},Ot;try{Ot=$.processChunk(N)}catch{te(b),re();return}if(Ot instanceof Promise){Ot.then(Be=>{te(de(Be)),re()}).catch(()=>{te(b),re()});return}te(de(Ot)),re()},kt=null,po=(D,Q,b,O)=>{D.rawContent=Q,Ie.has(D.id)||Ie.set(D.id,this.createStreamParser());let N=Ie.get(D.id),$=Q.trim().startsWith("{")||Q.trim().startsWith("[");if($&&be.set(D.id,Q),N.__isPlainTextParser===!0){D.content=O!==void 0?Q:D.content+b,be.delete(D.id),Ie.delete(D.id),D.rawContent=void 0,h(D);return}let re=N.processChunk(Q);if(re instanceof Promise)re.then(ae=>{let de=typeof ae=="string"?ae:ae?.text??null;de!==null&&de.trim()!==""?(D.content=de,h(D)):!$&&!Q.trim().startsWith("<")&&(D.content=O!==void 0?Q:D.content+b,be.delete(D.id),Ie.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=O!==void 0?Q:D.content+b,be.delete(D.id),Ie.delete(D.id),D.rawContent=void 0,h(D)});else{let ae=typeof re=="string"?re:re?.text??null;ae!==null&&ae.trim()!==""?(D.content=ae,h(D)):!$&&!Q.trim().startsWith("<")&&(D.content=O!==void 0?Q:D.content+b,be.delete(D.id),Ie.delete(D.id),D.rawContent=void 0,h(D))}},On=(D,Q)=>{let b=Q??D.content;if(b==null||b===""){D.streaming=!1,h(D);return}let N=be.get(D.id)??Re(b);D.rawContent=N;let $=Ie.get(D.id),te=null,re=!1;if($&&(te=$.getExtractedText(),te===null&&(te=ma(N)),te===null)){let ae=$.processChunk(N);ae instanceof Promise?(re=!0,ae.then(de=>{let Ot=typeof de=="string"?de:de?.text??null;Ot!==null&&(D.content=Ot,D.streaming=!1,Ie.delete(D.id),be.delete(D.id),h(D))}).catch(()=>{})):te=typeof ae=="string"?ae:ae?.text??null}if(!re){te!==null&&te.trim()!==""?D.content=te:be.has(D.id)||(D.content=Re(b));let ae=Ie.get(D.id);if(ae){let de=ae.close?.();de instanceof Promise&&de.catch(()=>{}),Ie.delete(D.id)}be.delete(D.id),D.streaming=!1,h(D)}},en=(D,Q,b)=>{let O=L.get(D);if(O)return O;let N={id:`nested-${Q}-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...b?{variant:b}:{},...b==="reasoning"?{reasoning:{id:D,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:Q}};return L.set(D,N),h(N),N},uo=[],Dn,Yn=new Map,As=0,go="agent",Ho=!1,Br=null,et=null,xn=new Map,Jn=this.config.iterationDisplay??"separate";for(Dn=()=>{for(let D=0;D<uo.length;D++){let Q=uo[D].payloadType,b=uo[D].payload;if(!Ho&&go!=="flow"&&typeof b.stepType=="string"&&(go="flow"),Q==="reasoning_start"){let O=typeof b.id=="string"?b.id:null,N=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(O&&N){A.set(O,N),en(O,N,"reasoning");continue}let $=ie(b,!0)??`reason-${u()}`,te=me($);te.reasoning=te.reasoning??{id:$,status:"streaming",chunks:[]},te.reasoning.startedAt=te.reasoning.startedAt??mt(b.startedAt??b.timestamp),te.reasoning.completedAt=void 0,te.reasoning.durationMs=void 0,(b.scope==="loop"||b.scope==="turn")&&(te.reasoning.scope=b.scope),te.streaming=!0,te.reasoning.status="streaming",h(te)}else if(Q==="reasoning_delta"){let O=typeof b.id=="string"?b.id:null;if(O&&A.has(O)&&L.has(O)){let re=L.get(O),ae=b.reasoningText??b.text??b.delta??"";ae&&b.hidden!==!0&&re.reasoning&&(re.reasoning.chunks.push(String(ae)),h(re));continue}let N=ie(b,!1)??ie(b,!0)??`reason-${u()}`,$=me(N);$.reasoning=$.reasoning??{id:N,status:"streaming",chunks:[]},$.reasoning.startedAt=$.reasoning.startedAt??mt(b.startedAt??b.timestamp);let te=b.reasoningText??b.text??b.delta??"";if(te&&b.hidden!==!0){let re=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(re!==void 0){let ae=co(N,re,String(te));$.reasoning.chunks=[ae]}else $.reasoning.chunks.push(String(te))}if($.reasoning.status=b.done?"complete":"streaming",b.done){$.reasoning.completedAt=mt(b.completedAt??b.timestamp);let re=$.reasoning.startedAt??Date.now();$.reasoning.durationMs=Math.max(0,($.reasoning.completedAt??Date.now())-re)}$.streaming=$.reasoning.status!=="complete",h($)}else if(Q==="reasoning_complete"){let O=typeof b.id=="string"?b.id:null;if(O&&A.has(O)&&L.has(O)){let ae=L.get(O);if(ae.reasoning){let de=typeof b.text=="string"?b.text:"";de&&ae.reasoning.chunks.length===0&&ae.reasoning.chunks.push(de),ae.reasoning.status="complete",ae.streaming=!1,h(ae)}A.delete(O),L.delete(O);continue}let N=ie(b,!1)??ie(b,!0)??`reason-${u()}`,$=typeof b.text=="string"?b.text:"";!_.get(N)&&($||b.scope==="loop")&&me(N);let te=_.get(N);if(te?.reasoning){(b.scope==="loop"||b.scope==="turn")&&(te.reasoning.scope=b.scope),$&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push($),te.reasoning.status="complete",te.reasoning.completedAt=mt(b.completedAt??b.timestamp);let ae=te.reasoning.startedAt??Date.now();te.reasoning.durationMs=Math.max(0,(te.reasoning.completedAt??Date.now())-ae),te.streaming=!1,h(te)}let re=B(b);re&&le.byStep.delete(re)}else if(Q==="tool_start"){x&&(x.streaming=!1,h(x),x=null),typeof b.iteration=="number"&&(As=b.iteration);let O=(typeof b.toolCallId=="string"?b.toolCallId:void 0)??ke(b,!0)??`tool-${u()}`,N=b.toolName??b.name;if(U(N)){Le.add(O);continue}Te(R(b),O);let $=$e(O),te=$.toolCall??{id:O,status:"pending"};te.name=N??te.name,te.status="running",b.parameters!==void 0?te.args=b.parameters:b.args!==void 0&&(te.args=b.args),te.startedAt=te.startedAt??mt(b.startedAt??b.timestamp),te.completedAt=void 0,te.durationMs=void 0,$.toolCall=te,$.streaming=!0,b.executionId&&($.agentMetadata={executionId:b.executionId,iteration:b.iteration}),h($)}else if(Q==="tool_output_delta"){let O=ke(b,!1)??ke(b,!0)??`tool-${u()}`;if(Le.has(O))continue;let N=$e(O),$=N.toolCall??{id:O,status:"running"};$.startedAt=$.startedAt??mt(b.startedAt??b.timestamp);let te=b.text??b.delta??b.message??"";te&&($.chunks=$.chunks??[],$.chunks.push(String(te))),$.status="running",N.toolCall=$,N.streaming=!0;let re=b.agentContext;(re||b.executionId)&&(N.agentMetadata=N.agentMetadata??{executionId:re?.executionId??b.executionId,iteration:re?.iteration??b.iteration}),h(N)}else if(Q==="tool_complete"){let O=ke(b,!1)??ke(b,!0)??`tool-${u()}`;if(Le.has(O)){Le.delete(O);continue}let N=$e(O),$=N.toolCall??{id:O,status:"running"};$.status="complete",b.result!==void 0&&($.result=b.result),typeof b.duration=="number"&&($.duration=b.duration),$.completedAt=mt(b.completedAt??b.timestamp);let te=b.duration??b.executionTime;if(typeof te=="number")$.durationMs=te;else{let de=$.startedAt??Date.now();$.durationMs=Math.max(0,($.completedAt??Date.now())-de)}N.toolCall=$,N.streaming=!1;let re=b.agentContext;(re||b.executionId)&&(N.agentMetadata=N.agentMetadata??{executionId:re?.executionId??b.executionId,iteration:re?.iteration??b.iteration}),h(N);let ae=R(b);ae&&ee.byCall.delete(ae)}else if(Q==="await"&&b.toolName){let O=typeof b.toolCallId=="string"&&b.toolCallId.length>0?b.toolCallId:void 0,N=O??b.toolId??`local-${u()}`,$=$e(N),te=b.toolName,re=b.origin==="webmcp"&&!oi(te)?`webmcp:${te}`:te,ae=oi(re),de=$.toolCall??{id:N,status:"pending"};de.name=re,de.args=b.parameters,de.status=ae?"running":"complete",de.chunks=de.chunks??[],de.startedAt=de.startedAt??mt(b.startedAt??b.timestamp??b.awaitedAt),ae?(de.completedAt=void 0,de.duration=void 0,de.durationMs=void 0):de.completedAt=de.completedAt??de.startedAt,$.toolCall=de,$.streaming=!1,$.agentMetadata={...$.agentMetadata,executionId:b.executionId??$.agentMetadata?.executionId,awaitingLocalTool:!0,...O?{webMcpToolCallId:O}:{}},h($)}else if(Q==="text_start"){let O=typeof b.id=="string"?b.id:null,N=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(O&&N){A.set(O,N);continue}let $=x;$&&(go==="flow"?(On($),kt=$):($.streaming=!1,h($)),x=null),P=typeof b.id=="string"?b.id:P,K=""}else if(Q==="text_delta"){let O=typeof b.id=="string"?b.id:null,N=O?A.get(O):void 0;if(O&&N){let re=typeof b.delta=="string"?b.delta:"",ae=(w.get(O)??"")+re;if(w.set(O,ae),ae.trim()==="")continue;let de=en(O,N);de.agentMetadata={...de.agentMetadata,executionId:b.executionId,parentToolId:N},po(de,ae,re,void 0);continue}if(P=typeof b.id=="string"?b.id:P,go==="flow"){let re=typeof b.delta=="string"?b.delta:"";if(K+=re,K.trim()==="")continue;let ae=V();ae.agentMetadata={executionId:b.executionId,iteration:b.iteration},po(ae,K,re,void 0),E=ae;continue}let $=typeof b.delta=="string"?b.delta:"";K+=$;let te=V();te.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:Br??void 0,agentName:et?.agentName},po(te,K,$,void 0),E=te}else if(Q==="text_complete"){let O=typeof b.id=="string"?b.id:null;if(O&&A.has(O)){let $=L.get(O);$&&On($),A.delete(O),w.delete(O),L.delete(O);continue}let N=x;N&&(go==="flow"?(On(N),kt=N):((N.content??"")===""&&typeof b.text=="string"&&(N.content=b.text),N.streaming=!1,h(N)),x=null),P=null,K=""}else if(Q==="step_complete"){let O=b.stepType,N=b.executionType;if(O==="tool"||N==="context")continue;if(b.success===!1){let $=b.error,te=typeof $=="string"&&$!==""?$:$!=null&&typeof $=="object"&&Reflect.has($,"message")?String($.message??"Step failed"):"Step failed";n({type:"error",error:new Error(te)});let re=x;re&&re.streaming&&(re.streaming=!1,h(re)),n({type:"status",status:"idle"});continue}{let $=kt;kt=null;let te=b.stopReason,re=b.result?.response;if($)te&&($.stopReason=te),re!=null?xs($,re):$.streaming!==!1&&(Ie.delete($.id),be.delete($.id),$.streaming=!1,h($));else{let ae=re!=null&&re!=="";if(ae||te){let de=V();te&&(de.stopReason=te),ae?On(de,re):(de.streaming=!1,h(de))}}continue}}else if(Q==="execution_start")go=b.kind==="flow"?"flow":"agent",Ho=!0,go==="agent"&&(et={executionId:b.executionId,agentId:b.agentId??"virtual",agentName:b.agentName??"",status:"running",currentIteration:0,maxTurns:b.maxTurns??1,startedAt:mt(b.startedAt)});else if(Q==="turn_start"){let O=typeof b.iteration=="number"?b.iteration:As;if(O!==As){if(et&&(et.currentIteration=O),Jn==="separate"&&O>1){let N=x;N&&(N.streaming=!1,h(N),xn.set(O-1,N),x=null)}As=O}Br=typeof b.id=="string"?b.id:null,E=null}else if(Q==="tool_input_delta"){let O=b.toolCallId??ee.lastId;if(O){let N=G.get(O);N?.toolCall&&(N.toolCall.chunks=N.toolCall.chunks??[],N.toolCall.chunks.push(b.delta??""),h(N))}}else{if(Q==="tool_input_complete")continue;if(Q==="turn_complete"){let O=b.stopReason,N=x??E;if(O&&N!==null){let $=b.id;(!$||N.agentMetadata?.turnId===$)&&(N.stopReason=O,h(N))}Br===b.id&&(Br=null)}else if(Q==="media_start"){let O=String(b.id);Yn.set(O,{mediaType:typeof b.mediaType=="string"?b.mediaType:void 0,role:typeof b.role=="string"?b.role:void 0,toolCallId:b.toolCallId,parts:[]})}else if(Q==="media_delta"){let O=Yn.get(String(b.id));O&&typeof b.delta=="string"&&O.parts.push(b.delta)}else if(Q==="media_complete"){let O=String(b.id),N=Yn.get(O);Yn.delete(O);let $=(typeof b.mediaType=="string"?b.mediaType:void 0)??N?.mediaType??"application/octet-stream",te=typeof b.data=="string"?b.data:void 0,re=typeof b.url=="string"?b.url:N&&N.parts.length>0?N.parts.join(""):void 0,ae=null;if(te)ae={type:"media",data:te,mediaType:$};else if(re){let Pt=$.toLowerCase();ae={type:Pt==="image"||Pt.startsWith("image/")?"image-url":"file-url",url:re,mediaType:$}}let de=b.toolCallId??N?.toolCallId,Ot=ae?[ae]:[],Be=[];for(let Pt of Ot){if(!Pt||typeof Pt!="object")continue;let wt=Pt,Ro=typeof wt.type=="string"?wt.type:void 0,sr=typeof wt.mediaType=="string"?wt.mediaType.toLowerCase():"",Dt=null,Nt="";if(Ro==="media"){let mn=typeof wt.data=="string"?wt.data:void 0;if(!mn)continue;Nt=sr.length>0?sr:"application/octet-stream",Dt=`data:${Nt};base64,${mn}`}else if(Ro==="image-url"){let mn=typeof wt.url=="string"?wt.url:void 0;if(!mn)continue;Nt=sr,Dt=mn}else if(Ro==="file-url"){let mn=typeof wt.url=="string"?wt.url:void 0;if(!mn)continue;Nt=sr,Dt=mn}else continue;if(Dt)if(Ro==="image-url"||Nt.startsWith("image/"))Be.push({type:"image",image:Dt,...Nt.includes("/")?{mimeType:Nt}:{}});else if(Nt.startsWith("audio/"))Be.push({type:"audio",audio:Dt,mimeType:Nt});else if(Nt.startsWith("video/"))Be.push({type:"video",video:Dt,mimeType:Nt});else{let mn=Nt||"application/octet-stream";Be.push({type:"file",data:Dt,mimeType:mn,filename:Zx(mn)})}}if(Be.length>0){let Pt=u(),wt=de,sr={id:`agent-media-${typeof wt=="string"&&wt.length>0?`${wt}-${Pt}`:String(Pt)}`,role:"assistant",content:"",contentParts:Be,createdAt:new Date().toISOString(),streaming:!1,sequence:Pt,agentMetadata:{executionId:b.executionId,iteration:typeof b.iteration=="number"?b.iteration:As}};h(sr);let Dt=x;Dt&&(Dt.streaming=!1,h(Dt)),x=null,M.current=null}}else if(Q==="execution_complete"){let O=b.kind??go;O==="agent"&&et&&(et.status=b.success?"complete":"error",et.completedAt=mt(b.completedAt),et.stopReason=b.stopReason);let N=x;N&&(O==="flow"&&N.streaming!==!1?On(N):(N.streaming=!1,h(N)),x=null),P=null,K="",kt=null,n({type:"status",status:"idle",terminal:!0})}else if(Q==="execution_error"){let O=typeof b.error=="string"?b.error:b.error?.message??"Execution error";n({type:"error",error:new Error(O)})}else if(Q!=="ping"){if(Q==="approval_start"){let O=b.approvalId??`approval-${u()}`,N={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:O,status:"pending",agentId:et?.agentId??"virtual",executionId:b.executionId??et?.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(Q==="step_await"&&b.awaitReason==="approval_required"){let O=b.approvalId??`approval-${u()}`,N={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:O,status:"pending",agentId:et?.agentId??"virtual",executionId:b.executionId??et?.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(Q==="approval_complete"){let O=b.approvalId;if(O){let $={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:O,status:b.decision??"approved",agentId:et?.agentId??"virtual",executionId:b.executionId??et?.executionId??"",toolName:b.toolName??"",description:b.description??"",resolvedAt:Date.now()}};h($)}}else if(Q==="artifact_start"||Q==="artifact_delta"||Q==="artifact_update"||Q==="artifact_complete"){if(Q==="artifact_start"){let O=b.artifactType,N=String(b.id),$=typeof b.title=="string"?b.title:void 0,te=b.file,re;te&&typeof te=="object"&&!Array.isArray(te)&&typeof te.path=="string"&&typeof te.mimeType=="string"&&(re={path:te.path,mimeType:te.mimeType,...typeof te.language=="string"?{language:te.language}:{}}),n({type:"artifact_start",id:N,artifactType:O,title:$,component:typeof b.component=="string"?b.component:void 0,...re?{file:re}:{}});let ae=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?{...b.props}:void 0;if(we.set(N,{markdown:"",title:$,file:re,...ae?{props:ae}:{}}),!Ze.has(N)){Ze.add(N);let de=Er(this.config.features?.artifacts,{artifactType:O,...re?{file:re}:{}}),Ot=typeof b.component=="string"?b.component:void 0,Be={id:`artifact-ref-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:va(de,{artifactId:N,title:$,artifactType:O,status:"streaming",...re?{file:re}:{},...Ot?{component:Ot}:{}})};Ce.set(N,Be),h(Be)}}else if(Q==="artifact_delta"){let O=String(b.id),N=typeof b.delta=="string"?b.delta:String(b.delta??"");n({type:"artifact_delta",id:O,artDelta:N});let $=we.get(O);$&&($.markdown+=N)}else if(Q==="artifact_update"){let O=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};n({type:"artifact_update",id:String(b.id),props:O,component:typeof b.component=="string"?b.component:void 0});let N=we.get(String(b.id));N&&(N.props={...N.props??{},...O})}else if(Q==="artifact_complete"){let O=String(b.id);n({type:"artifact_complete",id:O});let N=Ce.get(O);if(N){N.streaming=!1;try{let $=JSON.parse(N.rawContent??"{}");if($.props){$.props.status="complete";let te=we.get(O);te?.markdown&&($.props.markdown=te.markdown),te?.file&&($.props.file=te.file),$.component==="PersonaArtifactInline"&&te?.props&&Object.keys(te.props).length>0&&($.props.componentProps=te.props)}N.rawContent=JSON.stringify($)}catch{}we.delete(O),h(N),Ce.delete(O)}}}else if(Q==="transcript_insert"){let O=b.message;if(!O||typeof O!="object")continue;let N=String(O.id??`msg-${u()}`),$=O.role,re={id:N,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof O.content=="string"?O.content:"",rawContent:typeof O.rawContent=="string"?O.rawContent:void 0,createdAt:typeof O.createdAt=="string"?O.createdAt:new Date().toISOString(),streaming:O.streaming===!0,...typeof O.variant=="string"?{variant:O.variant}:{},sequence:u()};if(h(re),re.rawContent)try{let de=JSON.parse(re.rawContent)?.props?.artifactId;typeof de=="string"&&Ze.add(de)}catch{}x=null,M.current=null,Ie.delete(N),be.delete(N)}else if(Q==="error"){if(b.recoverable===!1&&b.error!=null&&b.error!==""){let O=typeof b.error=="string"?b.error:b.error?.message!=null?String(b.error.message):"Execution error";n({type:"error",error:new Error(O)});let N=x;N&&N.streaming&&(N.streaming=!1,h(N)),n({type:"status",status:"idle"})}}else if(Q==="step_error"||Q==="dispatch_error"||Q==="flow_error"){let O=null;if(b.error instanceof Error)O=b.error;else if(Q==="dispatch_error"){let N=b.message??b.error;N!=null&&N!==""&&(O=new Error(String(N)))}else{let N=b.error;typeof N=="string"&&N!==""?O=new Error(N):N!=null&&typeof N=="object"&&Reflect.has(N,"message")&&(O=new Error(String(N.message??N)))}if(O){n({type:"error",error:O});let N=x;N&&N.streaming&&(N.streaming=!1,h(N)),n({type:"status",status:"idle"})}}}}}uo.length=0};;){let{done:D,value:Q}=await i.read();if(D)break;c+=l.decode(Q,{stream:!0});let b=c.split(`
1
+ import{a as bc,b as Xh,c as ou,d as ha,e as vc,f as ya,g as Cc,h as ba,i as Yh,j as va}from"./chunk-CPVD5P5B.js";import{b as Mh,c as dc,d as Eh,e as ri,f as Th,g as pc,h as kh,i as Ph,j as Ih,k as Lh,l as uc,m as gc,n as eu,o as fc,p as ma,q as Hh,r as Rh,s as Wh,t as Bh}from"./chunk-NQLDCJAP.js";import{a as zh,b as jh,c as Jo,d as hs,e as Vh,f as Kh,g as Gh,h as nu,i as Qh}from"./chunk-VK6JOIYJ.js";import{a as Pt,b as Sh,c as lc,e as oi,f as xh,g as cc,h as Ah,j as Oh,k as Dh,l as me,m as Dt,n as an,o as mc,p as Jh,q as Zh,u as ey,v as si,w as Zo}from"./chunk-NIKYKSNZ.js";import{a as ms,d as ru}from"./chunk-EFJBUH5F.js";import{a as _h,c as Nh,d as yc,e as tu,f as qh}from"./chunk-UTVLOTWB.js";import{a as Fh,c as Uh,d as $h}from"./chunk-R2TMIMDI.js";import{a as tn}from"./chunk-7NQ4ZTHF.js";import{b as hc}from"./chunk-Q735PSZL.js";import{a as k,c as X,d as Bn}from"./chunk-76IELU7F.js";var ty=/^\s*\|?[\s:|-]*-[\s:|-]*$/,ny=t=>t.includes("|"),oy=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())},ix=t=>`| ${t.join(" | ")} |`,ax=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,lx=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),ry=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(!ny(s)||ty.test(s)||!ty.test(i))continue;let l=oy(s).length;if(l<1)continue;let c=ax(l);e[o+1]!==c&&(e[o+1]=c,n=!0);let p=o+2;for(;p<e.length;p++){let g=e[p];if(g.trim()===""||!ny(g))break;let u=ix(lx(oy(g),l));e[p]!==u&&(e[p]=u,n=!0)}o=p-1}return n?e.join(`
3
+ `):t};var sy="var(--persona-md-table-scroll-fade, 24px)",iy=new WeakSet;function ly(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 ay(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":sy),t.style.setProperty("--persona-fade-r",s<=1?"0px":sy)}function su(t){iy.has(t)||(iy.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&ay(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(ay)}var{setLoader:JT,load:cx}=Pt({fallbackImport:()=>import("./webmcp-runtime-JI7T4QYF.js")});var cy=cx;function Qn(t){return t==="card"?"collapsed":t}function ii(t){return t.split(";",1)[0].trim().toLowerCase()}function dx(t,e){if(!t)return;let n=Object.entries(t);for(let[s,i]of n)if(ii(s)===e)return{mode:Qn(i),selector:ii(s)};let o=`${e.split("/",1)[0]}/*`;for(let[s,i]of n)if(ii(s)===o)return{mode:Qn(i),selector:o}}function px(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:Qn(o.files),matchedBy:{type:"files"}};let c=e.file.mimeType?ii(e.file.mimeType):void 0,p=c?dx(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:Qn(o.files.default),matchedBy:{type:"files"}}}let s=o.byKind?.[e.artifactType];if(s)return{mode:Qn(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let i=o.byType?.[e.artifactType];if(i)return{mode:Qn(i),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let l=e.presentation?.preferredMode;return l?{mode:Qn(l),matchedBy:{type:"preferredMode"}}:o.default?{mode:Qn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Er(t,e){return px(t,e).mode}function Ca(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 ux="agent_",gx="flow_";function dy(t){return t.startsWith(ux)?{kind:"agentId",agentId:t}:t.startsWith(gx)?{kind:"flowId",flowId:t}:null}function py(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 g=dy(c);if(g)return g;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=dy(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 wc(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ai(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function uy(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}import{parse as fx,ARR as mx,OBJ as hx,STR as yx}from"partial-json";var iu="ask_user_question",wa=8,li="data-persona-ask-sheet-for",bx="Other",vx="Other\u2026",fy="Type your own answer here",my="Send",Cx="Next",wx="Back",Sx="Submit all",xx="Skip",Ax=3,au="data-ask-current-index",lu="data-ask-question-count",hy="data-ask-answers",cu="data-ask-grouped",yy="data-ask-layout",Mx=t=>t.layout==="pills"?"pills":"rows",Ex=t=>t.getAttribute(yy)==="pills"?"pills":"rows",gy=!1,by=t=>t.replace(/["\\]/g,"\\$&"),ys=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===iu,du=t=>t?.features?.askUserQuestion??{},ci=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=fx(s,yx|hx|mx);if(i&&typeof i=="object")return{payload:i,complete:n}}catch{}return{payload:null,complete:n}},Sa=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>wa&&!gy&&(gy=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${wa}.`)),e.slice(0,wa)},Tx=t=>Sa(t)[0]??null,kx=(t,e)=>Sa(t)[e]??null,Px=(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))},vy=(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},Ix=(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 g=k("span","persona-ask-row-description");g.textContent=t.description,l.appendChild(g)}i.appendChild(l);let p=vy(n,o,e);p&&i.appendChild(p)}else i.textContent=t.label,t.description&&(i.title=t.description);return i},Lx=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},Hx=(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(u=>u&&typeof u.label=="string"&&u.label.length>0);if(p.length===0&&!n){for(let u=0;u<Ax;u++)i.appendChild(Lx(o));return i}if(p.forEach((u,m)=>{i.appendChild(Ix(u,m,o,l))}),t?.allowFreeText!==!1){let u=o==="rows"?bx:vx;if(o==="rows"){let m=k("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(p.length)),m.setAttribute("data-ask-other-row","true");let v=k("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=e.freeTextPlaceholder??fy,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",e.freeTextLabel??u),v.appendChild(h),m.appendChild(v);let x=vy(o,l,p.length);x&&m.appendChild(x),i.appendChild(m)}else{let m=k("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=e.freeTextLabel??u,i.appendChild(m)}}return i},Cy=(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??fy,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??my,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Rx=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??my,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},Wx=(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??wx,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??xx,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??Sx:n.nextLabel??Cx,c.setAttribute("data-ask-user-action",p?"submit-all":"next"),c.disabled=!0,i.appendChild(c),o.appendChild(i),o},bs=t=>{let e=t.getAttribute(hy);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},wy=(t,e)=>{t.setAttribute(hy,JSON.stringify(e))},Xn=t=>{let e=Number(t.getAttribute(au)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Bx=(t,e)=>{t.setAttribute(au,String(Math.max(0,Math.floor(e))))},di=t=>{let e=Number(t.getAttribute(lu)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Tr=t=>t.getAttribute(cu)==="true",_x=(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},Ox=(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)))},Sc=(t,e)=>{let{payload:n}=ci(e),o=Sa(n),s=bs(t),i={},l=new Set;return o.forEach((c,p)=>{let g=typeof c?.question=="string"?c.question:"";g&&(l.has(g)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${g}"; later answer wins.`),l.add(g),Object.prototype.hasOwnProperty.call(s,p)&&(i[g]=s[p]))}),i},Sy=t=>{let e=bs(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 g=p.getAttribute("data-option-label")??"",u=s.has(g);p.setAttribute("aria-pressed",u?"true":"false"),p.classList.toggle("persona-ask-pill-selected",u)});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="")},xy=t=>{if(!Tr(t))return;let e=bs(t),n=Xn(t),o=e[n],s=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,i=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');i&&(i.disabled=!s);let l=t.querySelector('[data-ask-user-action="submit-multi"]');if(l){let c=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));l.disabled=c.length===0}},pu=(t,e,n)=>{let o=du(n),s=Ex(t),{payload:i,complete:l}=ci(e),c=Tr(t),p=Xn(t),g=di(t),u=c?kx(i,p):Tx(i),m=!!u?.multiSelect,v=t.querySelector('[data-ask-step-inline="true"]');v&&(v.textContent=c?`${p+1}/${g}`:"");let h=t.querySelector('[data-ask-stepper="true"]');h&&h.remove();let x=t.querySelector('[data-ask-question="true"]');if(x){let P=typeof u?.question=="string"?u.question:"";x.textContent=P,x.classList.toggle("persona-ask-question-skeleton",!P&&!l)}let E=t.querySelector('[data-ask-pill-list="true"]');if(E){let P=Hx(u,o,l,s);E.replaceWith(P)}if(s!=="rows"){let P=t.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Cy(o,s))}let M=t.querySelector('[data-ask-multi-actions="true"]');!c&&m&&!M?t.appendChild(Rx(o)):(!m||c)&&M&&M.remove(),t.setAttribute("data-multi-select",m?"true":"false");let F=t.querySelector('[data-ask-nav-row="true"]');if(c){let P=Wx(p,g,o);F?F.replaceWith(P):t.appendChild(P)}else F&&F.remove();Sy(t),xy(t)},Dx=(t,e,n)=>{let o=du(e),s=Mx(o),i=t.toolCall.id,l=Sa(n),c=Math.max(1,l.length),p=c>1,g=_x(t,l),u=p?Ox(t,c):0,m=k("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(li,i),m.setAttribute("data-tool-call-id",i),m.setAttribute("data-message-id",t.id),m.setAttribute(lu,String(c)),m.setAttribute(au,String(u)),m.setAttribute(cu,p?"true":"false"),m.setAttribute(yy,s),wy(m,g),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Px(m,o);let v=k("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=k("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",v.appendChild(h);let x=k("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",v.appendChild(x),m.appendChild(v);let M=k("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),s!=="rows"&&m.appendChild(Cy(o,s)),pu(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Nx=(t,e,n)=>{let{payload:o}=ci(e),s=Math.max(1,Sa(o).length);s>di(t)&&(t.setAttribute(lu,String(s)),s>1&&!Tr(t)&&t.setAttribute(cu,"true")),pu(t,e,n)};var xc=(t,e,n)=>{if(!n||!ys(t)||du(e).enabled===!1)return;let s=t.toolCall.id;n.querySelectorAll(`[${li}]`).forEach(g=>{g.getAttribute(li)!==s&&g.remove()});let l=n.querySelector(`[${li}="${by(s)}"]`);if(l){Nx(l,t,e);return}let{payload:c}=ci(t),p=Dx(t,e,c);n.appendChild(p)},pi=(t,e)=>{if(!t)return;let n=e?`[${li}="${by(e)}"]`:`[${li}]`;t.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let i=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(i)?i:180)})},uu=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),kr=(t,e)=>{let n=bs(t),o=Xn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,wy(t,n),Sy(t),xy(t)},Ac=(t,e,n,o)=>{let s=di(t),i=Math.max(0,Math.min(s-1,o));Bx(t,i),pu(t,e,n)};var Pr="suggest_replies";var Fx={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},My={name:Pr,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:Fx,origin:"sdk",annotations:{readOnlyHint:!0}},Ey=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),xa=t=>t.variant==="tool"&&t.toolCall?.name===Pr,Ux=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},Ty=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!xa(n))continue;let o=Ux(n.toolCall?.args);return o.length>0?o:null}return null},Ay=new Set,$x=(t,e,n)=>{let o=`${t}:${e}:${n}`;Ay.has(o)||(Ay.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Ir=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 qx={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:wa,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},zx={name:iu,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:qx,origin:"sdk",annotations:{readOnlyHint:!0}},Mc=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(zx),Ir(t).expose&&e.push(My),e};var ky="4.22.0";var Lr=ky;var ui="[Image]";function Py(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function Ec(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function ko(t){return{type:"text",text:t}}function Iy(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var Ly=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Vx=["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"],er=[...Ly,...Vx];function Kx(t){return Ly.includes(t)||t.startsWith("image/")}function Tc(t){return Kx(t.type)}function Hy(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function Ry(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;Tc(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 Wy(t,e=er,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 Gx(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function By(t,e){let n=Gx(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"],Xx=0;function _y(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function kc(t){return typeof t=="string"?t:void 0}function Yx(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?ko(e.text):null;case"image":return typeof e.image=="string"?Iy(e.image,{mimeType:kc(e.mimeType),alt:kc(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?Hy(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...kc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...kc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function Jx(t,e){let n=_y(e),o=t.map(l=>_y(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,g=i>0?s[i-1]:null,u=c+1<o.length?o[c+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let v=0;v<p;v+=1)s[i+v]=m!==null?m-(p-v):g!==null?g+v+1:Xx+v;i=c+1}return s.map(l=>new Date(l).toISOString())}function Oy(t,e){let n=Jx(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(Yx).filter(u=>u!==null),g=Py(p);o.push({id:s.id,role:l,content:g||(Ec(p)?ui:""),createdAt:c,...p.length>0&&{contentParts:p}});return}o.push({id:s.id,role:l,content:"",createdAt:c})}),o}function Aa(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 Ma(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 Zx="https://api.runtype.com/v1/dispatch",Dy="https://api.runtype.com",Ne=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Ny=32768,gu=49152,Fy=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:""}},Uy=t=>"reason"in t?t.reason:void 0,$y="The identity proof was not admitted; account history is unavailable",qy="The identity proof was rejected",zy="The request carried no visitor credential",jy="The stored visitor belongs to a different signed-in user",fu=(t,e)=>t instanceof Ne&&t.code===e;function eA(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let s=e.indexOf("/");if(s>0){let i=e.slice(s+1).split(";")[0]?.trim()??"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var mu=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function tA(t){switch(t){case"json":return Wh;case"regex-json":return Rh;case"xml":return Bh;default:return Hh}}var Vy=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function nA(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=Vy(n);if(!Vy(o))return t;if(!s||o===n||o.startsWith(n))return e;let l=ma(t);return ma(e)!==null&&l===null?e:t}var Ea=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??Zx,this.headers={"Content-Type":"application/json","X-Persona-Version":Lr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??tA(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 cy().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Mh,getToolDisplayTitle:dc,loadPolyfill:Th});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=py(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$/,"")||Dy}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let s=n.conversationId,i=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!s||!i)throw new Ne("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),p=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":Lr,"X-Visitor-Token":i},signal:e.signal});if(p.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(p),null,!0);continue}if(!p.ok)throw await this.historyErrorFor(p,!0);return p}}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&&Uy(n)===Uy(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.historyIdentitySubscribers])s(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.routing(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,p={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}},g=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Lr},body:JSON.stringify(p)});if(g.status===400&&o){let m={...p};delete m.durableRecovery,g=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Lr},body:JSON.stringify(m)})}if(!g.ok){let m=await g.json().catch(()=>({error:"Session initialization failed"}));if(n&&g.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),c)throw new Ne("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw g.status===403&&m.error==="durable_recovery_disabled"?new Ne("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&g.status===401&&m.error==="visitor_required"?new Ne("visitor_required","Visitor credential no longer resolves"):c&&g.status===404?new Ne("not_found","Conversation not found"):g.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):g.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await g.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.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.createClientSession({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(s,e,!1)}catch(s){if(!fu(s,"not_found")&&!fu(s,"visitor_required")&&!fu(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.createClientSession({storedSessionId:o}),i=await this.claimFirstConversation(s);return this.finishInit(i,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.createClientSession({storedSessionId:n,identityProof:e}),i=this.finishInit(s,o,!1);return this.clientSession=i,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),i}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let s=e.conversationId;return s&&n&&(o||s!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:s}),this.config.setStoredSessionId?.(e.sessionId),s&&(this.config.setStoredConversationId?.(s),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Ne("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 Ne("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":Lr},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 Ne("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 Ne("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 Ne("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 Ne("invalid_identity_proof",qy);if(s.includes("visitor token required"))throw new Ne("visitor_token_missing",zy);if(s.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Ne("visitor_identity_mismatch",jy);return this.reinitWithProof(n)}if(s.includes("expired")||s.includes("not found"))return this.clearClientSession(),this.initSession();throw new Ne("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new Ne("not_found","Conversation not found");if(e.status===429){let s=Number.parseInt(e.headers.get("Retry-After")??"",10);return new Ne("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 Ne("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 Ne("invalid_identity_proof",qy)):s.includes("visitor token required")?new Ne("visitor_token_missing",zy):s.includes("visitor_identity_mismatch")?new Ne("visitor_identity_mismatch",jy):new Ne("unauthorized",o||"History request was not authorized")}return new Ne("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 Ne("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Ne("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(s==="admitted")throw new Ne("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,g=await this.readVisitorToken();if(!g&&!n.visitorTokenOptional)throw new Ne("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(e,{...n.query,sessionId:s.sessionId}),{method:n.method,headers:{"X-Persona-Version":Lr,...g?{"X-Visitor-Token":g}:{},...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(u.status===401&&!c){c=!0,s=await this.recoverFromUnauthorized(await this.readErrorCode(u),i,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),v=await u.json().catch(()=>{});if(l&&l.revision()!==p)throw new Ne("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,i!==null,o),v}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Ne("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(Fy),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:Fy(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 g=p.displayContent.length;if(g>Ny)throw new Ne("payload_too_large",`displayContent exceeds the ${Ny} character limit`);o+=g}if(o>gu)throw new Ne("payload_too_large",`Display projection batch exceeds the ${gu} character limit`);await this.initSession();let s=this.historyInternals.visitorStore,i=s?.revision()??0,l=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=gu,trackIdentity:!1}),c=typeof l?.conversationRevision=="string"?l.conversationRevision:null;return c&&this.clientSession?.conversationId===e&&(s?.revision()??0)===i&&this.historyInternals.setStoredConversationRevision?.(c),{conversationRevision:c}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){let o=uy();this.currentClientTurnId=o;let s=()=>this.currentClientTurnId===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=await this.initSession();if(new Date>=new Date(l.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let x=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:x}),x}let c=await this.buildPayload(e.messages),p=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null,g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,u=this.isHistoryCapable(),m={sessionId:l.sessionId,messages:e.messages.filter(mu).map(x=>{let E=u?Aa(x):void 0;return{id:x.id,role:x.role,content:x.contentParts??x.llmContent??x.rawContent??x.content,...E!==void 0&&{displayContent:E}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},{response:v,commit:h}=await this.sendWithClientToolsDiff(l.sessionId,c.clientTools,x=>{let E={...m,...x};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",E),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Lr,...p?{"X-Visitor-Token":p}:{}},body:JSON.stringify(E),signal:e.signal})});if(!v.ok){let x=await v.json().catch(()=>({error:"Chat request failed"}));if(v.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let M=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:M}),M}if(v.status===429){let M=new Error(x.hint||"Message limit reached for this session.");throw i({type:"error",error:M}),M}if(v.status===410&&x.error==="conversation_deleted"){let M=new Ne("conversation_deleted","This conversation was deleted");throw i({type:"error",error:M}),M}let E=new Error(x.error||"Failed to send message");throw i({type:"error",error:E}),E}if(!v.body){let x=new Error("No response body received");throw i({type:"error",error:x}),x}h(),i({type:"status",status:"connected"});try{await this.streamResponse(v.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 Ne)&&!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?Eh(n):void 0,c=this.clientToolsFingerprintSessionId===e,p=i&&c&&this.lastSentClientToolsFingerprint===l,g=!i&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,m;for(let v=0;;v++){if(m=await o({...i&&(u||!p)&&n?{clientTools:n}:{},...g?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),m.status===409&&v===0&&i&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.sentNonEmptyClientToolsSessionId=e:g&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let s=this.isClientTokenMode(),i=s?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Dy}/resume`,l,c=null;if(s){let u=await this.initSession();l=u.sessionId,u.durableRecovery?.enabled===!0&&(c=await this.readVisitorToken())}let p={"Content-Type":"application/json",...c?{"X-Visitor-Token":c}:{},...this.headers};this.getHeaders&&Object.assign(p,await this.getHeaders());let g={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(l&&(g.sessionId=l),s&&l){let u=[...Mc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:v}=await this.sendWithClientToolsDiff(l,u,h=>{let x={...g,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",x),fetch(i,{method:"POST",headers:p,body:JSON.stringify(x),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&v(),m}return fetch(i,{method:"POST",headers:p,body:JSON.stringify(g),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(i=>i.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=e.slice().filter(mu).filter(g=>g.role==="user"||g.role==="assistant"||g.role==="system").filter(g=>!g.variant||g.variant==="assistant").sort((g,u)=>{let m=new Date(g.createdAt).getTime(),v=new Date(u.createdAt).getTime();return m-v}).map(g=>({role:g.role,content:g.contentParts??g.llmContent??g.rawContent??g.content,createdAt:g.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=[...Mc(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(mu).sort((g,u)=>{let m=new Date(g.createdAt).getTime(),v=new Date(u.createdAt).getTime();return m-v}).map(g=>({role:g.role,content:g.contentParts??g.llmContent??g.rawContent??g.content,createdAt:g.createdAt})),s=this.routing(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[g,u]of Object.entries(s.targetPayload))g!=="messages"&&(i[g]=u);let l=[...Mc(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 g=await this.requestMiddleware({payload:{...i},config:this.config});if(g&&typeof g=="object"){let u=g;return i.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=i.clientTools),u}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",g)}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=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:i(),...u!==void 0&&{partId:u}};return o.current=m,s(m),m},g=u=>o.current?o.current:p(u);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 u=g(c.partId);c.partId!==void 0&&!u.partId&&(u.partId=c.partId),u.content+=c.text,s(u)}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(),g=0,u=()=>p+g++,m=D=>{let Q=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,b=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,O=D.tools?D.tools.map(N=>({...N,chunks:N.chunks?[...N.chunks]:void 0})):void 0;return{...D,reasoning:Q,toolCall:b,tools:O}},v=D=>{if(D.role!=="assistant"||D.variant)return!0;let Q=Array.isArray(D.contentParts)&&D.contentParts.length>0,b=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||Q||b||!!D.stopReason},h=D=>{v(D)&&n({type:"message",message:m(D)})},x=null,E=null,M={current:null},F={current:null},P=null,K="",A=new Map,H=new Map,w=new Map,_=new Map,G=new Map,le={lastId:null,byStep:new Map},ee={lastId:null,byCall:new Map},S=D=>{if(D==null)return null;try{return String(D)}catch{return null}},B=D=>S(D.stepId??D.step_id??D.step??D.parentId??D.flowStepId??D.flow_step_id),R=D=>S(D.callId??D.call_id??D.requestId??D.request_id??D.toolCallId??D.tool_call_id??D.stepId??D.step_id),I=o,Z=!1,V=()=>{if(x)return x;let D,Q="",b=P;return!Z&&I?(D=I,Z=!0,Q=s??""):I&&b?D=`${I}_${b}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:D,role:"assistant",content:Q,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(x),x},ce=(D,Q)=>{le.lastId=Q,D&&le.byStep.set(D,Q)},ie=(D,Q)=>{let b=D.reasoningId??D.id,O=B(D);if(b){let $=String(b);return ce(O,$),$}if(O){let $=le.byStep.get(O);if($)return le.lastId=$,$}if(le.lastId&&!Q)return le.lastId;if(!Q)return null;let N=`reason-${u()}`;return ce(O,N),N},fe=D=>{let Q=_.get(D);if(Q)return Q;let b={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:D,status:"streaming",chunks:[]}};return _.set(D,b),h(b),b},Me=(D,Q)=>{ee.lastId=Q,D&&ee.byCall.set(D,Q)},Le=new Set,be=new Map,Je=new Set,ve=new Map,U=D=>{if(!D)return!1;let Q=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return Q==="emit_artifact_markdown"||Q==="emit_artifact_component"},Ee=(D,Q)=>{let b=D.toolId??D.id,O=R(D);if(b){let $=String(b);return Me(O,$),$}if(O){let $=ee.byCall.get(O);if($)return ee.lastId=$,$}if(ee.lastId&&!Q)return ee.lastId;if(!Q)return null;let N=`tool-${u()}`;return Me(O,N),N},Fe=D=>{let Q=G.get(D);if(Q)return Q;let b={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:D,status:"pending"}};return G.set(D,b),h(b),b},yt=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let Q=Number(D);if(!Number.isNaN(Q)&&Number.isFinite(Q))return Q;let b=Date.parse(D);if(!Number.isNaN(b))return b}return Date.now()},Re=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Pe=new Map,ye=new Map,co=new Map,po=(D,Q,b)=>{let O=co.get(D);O||(O=[],co.set(D,O));let N=0,$=O.length;for(;N<$;){let re=N+$>>>1;O[re].seq<Q?N=re+1:$=re}O[N]?.seq===Q?O[N]={seq:Q,text:b}:O.splice(N,0,{seq:Q,text:b});let te="";for(let re=0;re<O.length;re++)te+=O[re].text;return te},xs=(D,Q)=>{let b=Re(Q),O=ye.get(D.id),N=nA(O,b);D.rawContent=N;let $=Pe.get(D.id),te=Be=>{let Lt=D.content??"";Be.trim()!==""&&(Lt.trim().length===0||Be.startsWith(Lt)||Be.trimStart().startsWith(Lt.trim()))&&(D.content=Be)},re=()=>{if($){let Be=$.close?.();Be instanceof Promise&&Be.catch(()=>{})}Pe.delete(D.id),ye.delete(D.id),D.streaming=!1,h(D)};if(!$){te(b),re();return}let ae=ma(N);if(ae!==null&&ae.trim()!==""){te(ae),re();return}let de=Be=>{let Lt=typeof Be=="string"?Be:Be?.text??null;if(Lt!==null&&Lt.trim()!=="")return Lt;let xt=$.getExtractedText();return xt!==null&&xt.trim()!==""?xt:b},Nt;try{Nt=$.processChunk(N)}catch{te(b),re();return}if(Nt instanceof Promise){Nt.then(Be=>{te(de(Be)),re()}).catch(()=>{te(b),re()});return}te(de(Nt)),re()},It=null,uo=(D,Q,b,O)=>{D.rawContent=Q,Pe.has(D.id)||Pe.set(D.id,this.createStreamParser());let N=Pe.get(D.id),$=Q.trim().startsWith("{")||Q.trim().startsWith("[");if($&&ye.set(D.id,Q),N.__isPlainTextParser===!0){D.content=O!==void 0?Q:D.content+b,ye.delete(D.id),Pe.delete(D.id),D.rawContent=void 0,h(D);return}let re=N.processChunk(Q);if(re instanceof Promise)re.then(ae=>{let de=typeof ae=="string"?ae:ae?.text??null;de!==null&&de.trim()!==""?(D.content=de,h(D)):!$&&!Q.trim().startsWith("<")&&(D.content=O!==void 0?Q:D.content+b,ye.delete(D.id),Pe.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=O!==void 0?Q:D.content+b,ye.delete(D.id),Pe.delete(D.id),D.rawContent=void 0,h(D)});else{let ae=typeof re=="string"?re:re?.text??null;ae!==null&&ae.trim()!==""?(D.content=ae,h(D)):!$&&!Q.trim().startsWith("<")&&(D.content=O!==void 0?Q:D.content+b,ye.delete(D.id),Pe.delete(D.id),D.rawContent=void 0,h(D))}},Dn=(D,Q)=>{let b=Q??D.content;if(b==null||b===""){D.streaming=!1,h(D);return}let N=ye.get(D.id)??Re(b);D.rawContent=N;let $=Pe.get(D.id),te=null,re=!1;if($&&(te=$.getExtractedText(),te===null&&(te=ma(N)),te===null)){let ae=$.processChunk(N);ae instanceof Promise?(re=!0,ae.then(de=>{let Nt=typeof de=="string"?de:de?.text??null;Nt!==null&&(D.content=Nt,D.streaming=!1,Pe.delete(D.id),ye.delete(D.id),h(D))}).catch(()=>{})):te=typeof ae=="string"?ae:ae?.text??null}if(!re){te!==null&&te.trim()!==""?D.content=te:ye.has(D.id)||(D.content=Re(b));let ae=Pe.get(D.id);if(ae){let de=ae.close?.();de instanceof Promise&&de.catch(()=>{}),Pe.delete(D.id)}ye.delete(D.id),D.streaming=!1,h(D)}},nn=(D,Q,b)=>{let O=H.get(D);if(O)return O;let N={id:`nested-${Q}-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...b?{variant:b}:{},...b==="reasoning"?{reasoning:{id:D,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:Q}};return H.set(D,N),h(N),N},go=[],Nn,Jn=new Map,As=0,fo="agent",Ho=!1,Br=null,Ze=null,An=new Map,Zn=this.config.iterationDisplay??"separate";for(Nn=()=>{for(let D=0;D<go.length;D++){let Q=go[D].payloadType,b=go[D].payload;if(!Ho&&fo!=="flow"&&typeof b.stepType=="string"&&(fo="flow"),Q==="reasoning_start"){let O=typeof b.id=="string"?b.id:null,N=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(O&&N){A.set(O,N),nn(O,N,"reasoning");continue}let $=ie(b,!0)??`reason-${u()}`,te=fe($);te.reasoning=te.reasoning??{id:$,status:"streaming",chunks:[]},te.reasoning.startedAt=te.reasoning.startedAt??yt(b.startedAt??b.timestamp),te.reasoning.completedAt=void 0,te.reasoning.durationMs=void 0,(b.scope==="loop"||b.scope==="turn")&&(te.reasoning.scope=b.scope),te.streaming=!0,te.reasoning.status="streaming",h(te)}else if(Q==="reasoning_delta"){let O=typeof b.id=="string"?b.id:null;if(O&&A.has(O)&&H.has(O)){let re=H.get(O),ae=b.reasoningText??b.text??b.delta??"";ae&&b.hidden!==!0&&re.reasoning&&(re.reasoning.chunks.push(String(ae)),h(re));continue}let N=ie(b,!1)??ie(b,!0)??`reason-${u()}`,$=fe(N);$.reasoning=$.reasoning??{id:N,status:"streaming",chunks:[]},$.reasoning.startedAt=$.reasoning.startedAt??yt(b.startedAt??b.timestamp);let te=b.reasoningText??b.text??b.delta??"";if(te&&b.hidden!==!0){let re=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(re!==void 0){let ae=po(N,re,String(te));$.reasoning.chunks=[ae]}else $.reasoning.chunks.push(String(te))}if($.reasoning.status=b.done?"complete":"streaming",b.done){$.reasoning.completedAt=yt(b.completedAt??b.timestamp);let re=$.reasoning.startedAt??Date.now();$.reasoning.durationMs=Math.max(0,($.reasoning.completedAt??Date.now())-re)}$.streaming=$.reasoning.status!=="complete",h($)}else if(Q==="reasoning_complete"){let O=typeof b.id=="string"?b.id:null;if(O&&A.has(O)&&H.has(O)){let ae=H.get(O);if(ae.reasoning){let de=typeof b.text=="string"?b.text:"";de&&ae.reasoning.chunks.length===0&&ae.reasoning.chunks.push(de),ae.reasoning.status="complete",ae.streaming=!1,h(ae)}A.delete(O),H.delete(O);continue}let N=ie(b,!1)??ie(b,!0)??`reason-${u()}`,$=typeof b.text=="string"?b.text:"";!_.get(N)&&($||b.scope==="loop")&&fe(N);let te=_.get(N);if(te?.reasoning){(b.scope==="loop"||b.scope==="turn")&&(te.reasoning.scope=b.scope),$&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push($),te.reasoning.status="complete",te.reasoning.completedAt=yt(b.completedAt??b.timestamp);let ae=te.reasoning.startedAt??Date.now();te.reasoning.durationMs=Math.max(0,(te.reasoning.completedAt??Date.now())-ae),te.streaming=!1,h(te)}let re=B(b);re&&le.byStep.delete(re)}else if(Q==="tool_start"){x&&(x.streaming=!1,h(x),x=null),typeof b.iteration=="number"&&(As=b.iteration);let O=(typeof b.toolCallId=="string"?b.toolCallId:void 0)??Ee(b,!0)??`tool-${u()}`,N=b.toolName??b.name;if(U(N)){Le.add(O);continue}Me(R(b),O);let $=Fe(O),te=$.toolCall??{id:O,status:"pending"};te.name=N??te.name,te.status="running",b.parameters!==void 0?te.args=b.parameters:b.args!==void 0&&(te.args=b.args),te.startedAt=te.startedAt??yt(b.startedAt??b.timestamp),te.completedAt=void 0,te.durationMs=void 0,$.toolCall=te,$.streaming=!0,b.executionId&&($.agentMetadata={executionId:b.executionId,iteration:b.iteration}),h($)}else if(Q==="tool_output_delta"){let O=Ee(b,!1)??Ee(b,!0)??`tool-${u()}`;if(Le.has(O))continue;let N=Fe(O),$=N.toolCall??{id:O,status:"running"};$.startedAt=$.startedAt??yt(b.startedAt??b.timestamp);let te=b.text??b.delta??b.message??"";te&&($.chunks=$.chunks??[],$.chunks.push(String(te))),$.status="running",N.toolCall=$,N.streaming=!0;let re=b.agentContext;(re||b.executionId)&&(N.agentMetadata=N.agentMetadata??{executionId:re?.executionId??b.executionId,iteration:re?.iteration??b.iteration}),h(N)}else if(Q==="tool_complete"){let O=Ee(b,!1)??Ee(b,!0)??`tool-${u()}`;if(Le.has(O)){Le.delete(O);continue}let N=Fe(O),$=N.toolCall??{id:O,status:"running"};$.status="complete",b.result!==void 0&&($.result=b.result),typeof b.duration=="number"&&($.duration=b.duration),$.completedAt=yt(b.completedAt??b.timestamp);let te=b.duration??b.executionTime;if(typeof te=="number")$.durationMs=te;else{let de=$.startedAt??Date.now();$.durationMs=Math.max(0,($.completedAt??Date.now())-de)}N.toolCall=$,N.streaming=!1;let re=b.agentContext;(re||b.executionId)&&(N.agentMetadata=N.agentMetadata??{executionId:re?.executionId??b.executionId,iteration:re?.iteration??b.iteration}),h(N);let ae=R(b);ae&&ee.byCall.delete(ae)}else if(Q==="await"&&b.toolName){let O=typeof b.toolCallId=="string"&&b.toolCallId.length>0?b.toolCallId:void 0,N=O??b.toolId??`local-${u()}`,$=Fe(N),te=b.toolName,re=b.origin==="webmcp"&&!ri(te)?`webmcp:${te}`:te,ae=ri(re),de=$.toolCall??{id:N,status:"pending"};de.name=re,de.args=b.parameters,de.status=ae?"running":"complete",de.chunks=de.chunks??[],de.startedAt=de.startedAt??yt(b.startedAt??b.timestamp??b.awaitedAt),ae?(de.completedAt=void 0,de.duration=void 0,de.durationMs=void 0):de.completedAt=de.completedAt??de.startedAt,$.toolCall=de,$.streaming=!1,$.agentMetadata={...$.agentMetadata,executionId:b.executionId??$.agentMetadata?.executionId,awaitingLocalTool:!0,...O?{webMcpToolCallId:O}:{}},h($)}else if(Q==="text_start"){let O=typeof b.id=="string"?b.id:null,N=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(O&&N){A.set(O,N);continue}let $=x;$&&(fo==="flow"?(Dn($),It=$):($.streaming=!1,h($)),x=null),P=typeof b.id=="string"?b.id:P,K=""}else if(Q==="text_delta"){let O=typeof b.id=="string"?b.id:null,N=O?A.get(O):void 0;if(O&&N){let re=typeof b.delta=="string"?b.delta:"",ae=(w.get(O)??"")+re;if(w.set(O,ae),ae.trim()==="")continue;let de=nn(O,N);de.agentMetadata={...de.agentMetadata,executionId:b.executionId,parentToolId:N},uo(de,ae,re,void 0);continue}if(P=typeof b.id=="string"?b.id:P,fo==="flow"){let re=typeof b.delta=="string"?b.delta:"";if(K+=re,K.trim()==="")continue;let ae=V();ae.agentMetadata={executionId:b.executionId,iteration:b.iteration},uo(ae,K,re,void 0),E=ae;continue}let $=typeof b.delta=="string"?b.delta:"";K+=$;let te=V();te.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:Br??void 0,agentName:Ze?.agentName},uo(te,K,$,void 0),E=te}else if(Q==="text_complete"){let O=typeof b.id=="string"?b.id:null;if(O&&A.has(O)){let $=H.get(O);$&&Dn($),A.delete(O),w.delete(O),H.delete(O);continue}let N=x;N&&(fo==="flow"?(Dn(N),It=N):((N.content??"")===""&&typeof b.text=="string"&&(N.content=b.text),N.streaming=!1,h(N)),x=null),P=null,K=""}else if(Q==="step_complete"){let O=b.stepType,N=b.executionType;if(O==="tool"||N==="context")continue;if(b.success===!1){let $=b.error,te=typeof $=="string"&&$!==""?$:$!=null&&typeof $=="object"&&Reflect.has($,"message")?String($.message??"Step failed"):"Step failed";n({type:"error",error:new Error(te)});let re=x;re&&re.streaming&&(re.streaming=!1,h(re)),n({type:"status",status:"idle"});continue}{let $=It;It=null;let te=b.stopReason,re=b.result?.response;if($)te&&($.stopReason=te),re!=null?xs($,re):$.streaming!==!1&&(Pe.delete($.id),ye.delete($.id),$.streaming=!1,h($));else{let ae=re!=null&&re!=="";if(ae||te){let de=V();te&&(de.stopReason=te),ae?Dn(de,re):(de.streaming=!1,h(de))}}continue}}else if(Q==="execution_start")fo=b.kind==="flow"?"flow":"agent",Ho=!0,fo==="agent"&&(Ze={executionId:b.executionId,agentId:b.agentId??"virtual",agentName:b.agentName??"",status:"running",currentIteration:0,maxTurns:b.maxTurns??1,startedAt:yt(b.startedAt)});else if(Q==="turn_start"){let O=typeof b.iteration=="number"?b.iteration:As;if(O!==As){if(Ze&&(Ze.currentIteration=O),Zn==="separate"&&O>1){let N=x;N&&(N.streaming=!1,h(N),An.set(O-1,N),x=null)}As=O}Br=typeof b.id=="string"?b.id:null,E=null}else if(Q==="tool_input_delta"){let O=b.toolCallId??ee.lastId;if(O){let N=G.get(O);N?.toolCall&&(N.toolCall.chunks=N.toolCall.chunks??[],N.toolCall.chunks.push(b.delta??""),h(N))}}else{if(Q==="tool_input_complete")continue;if(Q==="turn_complete"){let O=b.stopReason,N=x??E;if(O&&N!==null){let $=b.id;(!$||N.agentMetadata?.turnId===$)&&(N.stopReason=O,h(N))}Br===b.id&&(Br=null)}else if(Q==="media_start"){let O=String(b.id);Jn.set(O,{mediaType:typeof b.mediaType=="string"?b.mediaType:void 0,role:typeof b.role=="string"?b.role:void 0,toolCallId:b.toolCallId,parts:[]})}else if(Q==="media_delta"){let O=Jn.get(String(b.id));O&&typeof b.delta=="string"&&O.parts.push(b.delta)}else if(Q==="media_complete"){let O=String(b.id),N=Jn.get(O);Jn.delete(O);let $=(typeof b.mediaType=="string"?b.mediaType:void 0)??N?.mediaType??"application/octet-stream",te=typeof b.data=="string"?b.data:void 0,re=typeof b.url=="string"?b.url:N&&N.parts.length>0?N.parts.join(""):void 0,ae=null;if(te)ae={type:"media",data:te,mediaType:$};else if(re){let Lt=$.toLowerCase();ae={type:Lt==="image"||Lt.startsWith("image/")?"image-url":"file-url",url:re,mediaType:$}}let de=b.toolCallId??N?.toolCallId,Nt=ae?[ae]:[],Be=[];for(let Lt of Nt){if(!Lt||typeof Lt!="object")continue;let xt=Lt,Ro=typeof xt.type=="string"?xt.type:void 0,ir=typeof xt.mediaType=="string"?xt.mediaType.toLowerCase():"",Ft=null,Ut="";if(Ro==="media"){let mn=typeof xt.data=="string"?xt.data:void 0;if(!mn)continue;Ut=ir.length>0?ir:"application/octet-stream",Ft=`data:${Ut};base64,${mn}`}else if(Ro==="image-url"){let mn=typeof xt.url=="string"?xt.url:void 0;if(!mn)continue;Ut=ir,Ft=mn}else if(Ro==="file-url"){let mn=typeof xt.url=="string"?xt.url:void 0;if(!mn)continue;Ut=ir,Ft=mn}else continue;if(Ft)if(Ro==="image-url"||Ut.startsWith("image/"))Be.push({type:"image",image:Ft,...Ut.includes("/")?{mimeType:Ut}:{}});else if(Ut.startsWith("audio/"))Be.push({type:"audio",audio:Ft,mimeType:Ut});else if(Ut.startsWith("video/"))Be.push({type:"video",video:Ft,mimeType:Ut});else{let mn=Ut||"application/octet-stream";Be.push({type:"file",data:Ft,mimeType:mn,filename:eA(mn)})}}if(Be.length>0){let Lt=u(),xt=de,ir={id:`agent-media-${typeof xt=="string"&&xt.length>0?`${xt}-${Lt}`:String(Lt)}`,role:"assistant",content:"",contentParts:Be,createdAt:new Date().toISOString(),streaming:!1,sequence:Lt,agentMetadata:{executionId:b.executionId,iteration:typeof b.iteration=="number"?b.iteration:As}};h(ir);let Ft=x;Ft&&(Ft.streaming=!1,h(Ft)),x=null,M.current=null}}else if(Q==="execution_complete"){let O=b.kind??fo;O==="agent"&&Ze&&(Ze.status=b.success?"complete":"error",Ze.completedAt=yt(b.completedAt),Ze.stopReason=b.stopReason);let N=x;N&&(O==="flow"&&N.streaming!==!1?Dn(N):(N.streaming=!1,h(N)),x=null),P=null,K="",It=null,n({type:"status",status:"idle",terminal:!0})}else if(Q==="execution_error"){let O=typeof b.error=="string"?b.error:b.error?.message??"Execution error";n({type:"error",error:new Error(O)})}else if(Q!=="ping"){if(Q==="approval_start"){let O=b.approvalId??`approval-${u()}`,N={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:O,status:"pending",agentId:Ze?.agentId??"virtual",executionId:b.executionId??Ze?.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(Q==="step_await"&&b.awaitReason==="approval_required"){let O=b.approvalId??`approval-${u()}`,N={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:O,status:"pending",agentId:Ze?.agentId??"virtual",executionId:b.executionId??Ze?.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(Q==="approval_complete"){let O=b.approvalId;if(O){let $={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:O,status:b.decision??"approved",agentId:Ze?.agentId??"virtual",executionId:b.executionId??Ze?.executionId??"",toolName:b.toolName??"",description:b.description??"",resolvedAt:Date.now()}};h($)}}else if(Q==="artifact_start"||Q==="artifact_delta"||Q==="artifact_update"||Q==="artifact_complete"){if(Q==="artifact_start"){let O=b.artifactType,N=String(b.id),$=typeof b.title=="string"?b.title:void 0,te=b.file,re;te&&typeof te=="object"&&!Array.isArray(te)&&typeof te.path=="string"&&typeof te.mimeType=="string"&&(re={path:te.path,mimeType:te.mimeType,...typeof te.language=="string"?{language:te.language}:{}}),n({type:"artifact_start",id:N,artifactType:O,title:$,component:typeof b.component=="string"?b.component:void 0,...re?{file:re}:{}});let ae=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?{...b.props}:void 0;if(ve.set(N,{markdown:"",title:$,file:re,...ae?{props:ae}:{}}),!Je.has(N)){Je.add(N);let de=Er(this.config.features?.artifacts,{artifactType:O,...re?{file:re}:{}}),Nt=typeof b.component=="string"?b.component:void 0,Be={id:`artifact-ref-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Ca(de,{artifactId:N,title:$,artifactType:O,status:"streaming",...re?{file:re}:{},...Nt?{component:Nt}:{}})};be.set(N,Be),h(Be)}}else if(Q==="artifact_delta"){let O=String(b.id),N=typeof b.delta=="string"?b.delta:String(b.delta??"");n({type:"artifact_delta",id:O,artDelta:N});let $=ve.get(O);$&&($.markdown+=N)}else if(Q==="artifact_update"){let O=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};n({type:"artifact_update",id:String(b.id),props:O,component:typeof b.component=="string"?b.component:void 0});let N=ve.get(String(b.id));N&&(N.props={...N.props??{},...O})}else if(Q==="artifact_complete"){let O=String(b.id);n({type:"artifact_complete",id:O});let N=be.get(O);if(N){N.streaming=!1;try{let $=JSON.parse(N.rawContent??"{}");if($.props){$.props.status="complete";let te=ve.get(O);te?.markdown&&($.props.markdown=te.markdown),te?.file&&($.props.file=te.file),$.component==="PersonaArtifactInline"&&te?.props&&Object.keys(te.props).length>0&&($.props.componentProps=te.props)}N.rawContent=JSON.stringify($)}catch{}ve.delete(O),h(N),be.delete(O)}}}else if(Q==="transcript_insert"){let O=b.message;if(!O||typeof O!="object")continue;let N=String(O.id??`msg-${u()}`),$=O.role,re={id:N,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof O.content=="string"?O.content:"",rawContent:typeof O.rawContent=="string"?O.rawContent:void 0,createdAt:typeof O.createdAt=="string"?O.createdAt:new Date().toISOString(),streaming:O.streaming===!0,...typeof O.variant=="string"?{variant:O.variant}:{},sequence:u()};if(h(re),re.rawContent)try{let de=JSON.parse(re.rawContent)?.props?.artifactId;typeof de=="string"&&Je.add(de)}catch{}x=null,M.current=null,Pe.delete(N),ye.delete(N)}else if(Q==="error"){if(b.recoverable===!1&&b.error!=null&&b.error!==""){let O=typeof b.error=="string"?b.error:b.error?.message!=null?String(b.error.message):"Execution error";n({type:"error",error:new Error(O)});let N=x;N&&N.streaming&&(N.streaming=!1,h(N)),n({type:"status",status:"idle"})}}else if(Q==="step_error"||Q==="dispatch_error"||Q==="flow_error"){let O=null;if(b.error instanceof Error)O=b.error;else if(Q==="dispatch_error"){let N=b.message??b.error;N!=null&&N!==""&&(O=new Error(String(N)))}else{let N=b.error;typeof N=="string"&&N!==""?O=new Error(N):N!=null&&typeof N=="object"&&Reflect.has(N,"message")&&(O=new Error(String(N.message??N)))}if(O){n({type:"error",error:O});let N=x;N&&N.streaming&&(N.streaming=!1,h(N)),n({type:"status",status:"idle"})}}}}}go.length=0};;){let{done:D,value:Q}=await i.read();if(D)break;c+=l.decode(Q,{stream:!0});let b=c.split(`
4
4
 
5
5
  `);c=b.pop()??"";for(let O of b){let N=O.split(`
6
- `),$="message",te="",re=null;for(let Be of N)Be.startsWith("event:")?$=Be.replace("event:","").trim():Be.startsWith("data:")?te+=Be.replace("data:","").trim():Be.startsWith("id:")&&(re=Be.slice(3).trim());let ae=()=>{re!==null&&re!==""&&n({type:"cursor",id:re})};if(!te){ae();continue}let de;try{de=JSON.parse(te)}catch(Be){n({type:"error",error:Be instanceof Error?Be:new Error("Failed to parse chat stream payload")});continue}let Ot=$!=="message"?$:de.type??"message";if(this.onSSEEvent?.(Ot,de),this.parseSSEEvent){M.current=x;let Be=await this.handleCustomSSEEvent(de,n,M,h,u,F);if(M.current&&M.current!==x&&(x=M.current),Be){ae();continue}}uo.push({payloadType:Ot,payload:de}),Dn(),ae()}}Dn()}};var nA=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function oA(t){let e=t?.text?.trim()??"";return e?Bh(nA(t),e):""}function Vy(t){let e=oA(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[ko(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
6
+ `),$="message",te="",re=null;for(let Be of N)Be.startsWith("event:")?$=Be.replace("event:","").trim():Be.startsWith("data:")?te+=Be.replace("data:","").trim():Be.startsWith("id:")&&(re=Be.slice(3).trim());let ae=()=>{re!==null&&re!==""&&n({type:"cursor",id:re})};if(!te){ae();continue}let de;try{de=JSON.parse(te)}catch(Be){n({type:"error",error:Be instanceof Error?Be:new Error("Failed to parse chat stream payload")});continue}let Nt=$!=="message"?$:de.type??"message";if(this.onSSEEvent?.(Nt,de),this.parseSSEEvent){M.current=x;let Be=await this.handleCustomSSEEvent(de,n,M,h,u,F);if(M.current&&M.current!==x&&(x=M.current),Be){ae();continue}}go.push({payloadType:Nt,payload:de}),Nn(),ae()}}Nn()}};var oA=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function rA(t){let e=t?.text?.trim()??"";return e?_h(oA(t),e):""}function Ky(t){let e=rA(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[ko(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
7
7
 
8
- `)}:{}}function kc(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function Ky(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 fu(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 Gy(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 fu(t,n.id)?n.id:null}return null}function hu(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 yu(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 Ea=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):yu(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 Pc=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 rA=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Qy(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:rA()}catch{return!1}}var{setLoader:Rk,load:sA}=Tt({fallbackImport:()=>import("./voice-runtime-EFR3R5ES.js")});var bu=sA;function vu(t){if(!t)return"";let e=iA(t);return Xy(e!==null?e:t)}function iA(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 Xy(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
8
+ `)}:{}}function Pc(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function Gy(t,e){let n=t.findIndex(s=>s.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function hu(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function Qy(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return hu(t,n.id)?n.id:null}return null}function yu(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}function bu(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(s=>s.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Ta=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(e.text),i=o.getVoices();if(e.voice){let l=i.find(c=>c.name===e.voice);l&&(s.voice=l)}else i.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(i):bu(i));e.rate!==void 0&&(s.rate=e.rate),e.pitch!==void 0&&(s.pitch=e.pitch),s.onend=()=>n.onEnd?.(),s.onerror=l=>{let c=l.error;c==="canceled"||c==="interrupted"?n.onEnd?.():n.onError?.(new Error(c||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var Ic=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 sA=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Xy(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:sA()}catch{return!1}}var{setLoader:Wk,load:iA}=Pt({fallbackImport:()=>import("./voice-runtime-EFR3R5ES.js")});var vu=iA;function Cu(t){if(!t)return"";let e=aA(t);return Yy(e!==null?e:t)}function aA(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 Yy(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/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 Yy=null;var Cu=()=>Yy?Yy():import("./runtype-tts-entry-UJAEF7NZ.js");var{setLoader:Dk,load:aA}=Tt({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var Jy=aA;var lA=["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 cA(t,e){return lA.some(n=>t[n]!==e[n])}var Po=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function wu(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}
10
+ `),e.trim()}var Jy=null;var wu=()=>Jy?Jy():import("./runtype-tts-entry-UJAEF7NZ.js");var{setLoader:Nk,load:lA}=Pt({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var Zy=lA;var cA=["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 dA(t,e){return cA.some(n=>t[n]!==e[n])}var Po=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function Su(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
11
11
 
12
- _Details: ${n.message}_`:o}var Su=t=>({isError:!0,content:[{type:"text",text:t}]}),dA=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Zy=t=>oi(t)||t===Pr,Ic=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 Pc(()=>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&&(oi(n.name)||n.name===Pr&&Ir(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(s=>({...s,sequence:s.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Ma(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&&bu().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||Cu().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 Qy(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=Ea.isSupported()?new Ea({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 Cu().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:p})=>{let g=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new p(g,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):g});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=bu().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 Po("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 fs("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 Po("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 Po("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.historyOpenEpoch)throw c.discard(),new Po("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 g=this.fetchOlderPage(s,e,l,i).finally(()=>{this.olderPageRequests.delete(c)});return this.olderPageRequests.set(c,g),g}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=Aa(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 Po("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 Po("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 Po("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 Po("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let s=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let i=this.runBootReconciliation(n,o,s).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===i&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=i,i}async runBootReconciliation(e,n,o){this.activeConversationId=n;let s=this.clientSession?.conversationRevision??this.activeConversationRevision??null,i=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),s&&i&&s===i){this.activeConversationRevision=s;return}let l=await e.getPage(n,{context:o}),c=new Set(l.messages.map(f=>f.id)),p=this.messages.some(f=>c.has(f.id)),g=l.messages[0]?.createdAt,u;if(!p)u=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:g!==void 0&&h.createdAt<g);u=Aa(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(u),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=xa(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=xa(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 Ue&&(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 Ue?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 Ue&&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(!cA(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 Ma(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:g=!1,voiceProcessing:u,rawContent:f}=e,h={id:l??(n==="user"?Cc():n==="assistant"?ii():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:g,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...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:g,sequence:u,streaming:f=!1,voiceProcessing:v,rawContent:h}=o,E={id:p??(s==="user"?Cc():s==="assistant"?ii():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:g??new Date().toISOString(),sequence:u??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(E)}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,g={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(g),...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 xu=t=>({isError:!0,content:[{type:"text",text:t}]}),pA=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,eb=t=>ri(t)||t===Pr,Lc=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 Ic(()=>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&&(ri(n.name)||n.name===Pr&&Ir(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(s=>({...s,sequence:s.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Ea(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let s of e.initialArtifacts??[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&vu().catch(()=>{})}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||wu().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Xy(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=Ta.isSupported()?new Ta({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,s=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,l=e.browserFallback!==!1;if(o&&s&&i)return wu().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:p})=>{let g=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new p(g,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):g});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=vu().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 Po("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 ms("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 Po("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 Po("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.historyOpenEpoch)throw c.discard(),new Po("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 g=this.fetchOlderPage(s,e,l,i).finally(()=>{this.olderPageRequests.delete(c)});return this.olderPageRequests.set(c,g),g}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=Ma(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 Po("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 Po("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 Po("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 Po("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let s=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let i=this.runBootReconciliation(n,o,s).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===i&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=i,i}async runBootReconciliation(e,n,o){this.activeConversationId=n;let s=this.clientSession?.conversationRevision??this.activeConversationRevision??null,i=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),s&&i&&s===i){this.activeConversationRevision=s;return}let l=await e.getPage(n,{context:o}),c=new Set(l.messages.map(m=>m.id)),p=this.messages.some(m=>c.has(m.id)),g=l.messages[0]?.createdAt,u;if(!p)u=l.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,v=this.messages.filter(h=>c.has(h.id)||h.id===m?!0:g!==void 0&&h.createdAt<g);u=Ma(v,l.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=l.nextCursor,this.activeConversationRevision=l.conversationRevision||s||null,this.acknowledgedProjections.clear();for(let m of l.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),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=Aa(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=Aa(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 Ne&&(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 Ne?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 Ne&&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(!dA(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 Ea(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:g=!1,voiceProcessing:u,rawContent:m}=e,h={id:l??(n==="user"?wc():n==="assistant"?ai():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:g,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:s,content:i,llmContent:l,contentParts:c,id:p,createdAt:g,sequence:u,streaming:m=!1,voiceProcessing:v,rawContent:h}=o,E={id:p??(s==="user"?wc():s==="assistant"?ai():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:g??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...v!==void 0&&{voiceProcessing:v},...h!==void 0&&{rawContent:h}};n.push(E)}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,g={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(g),...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 g=[];i&&g.push(ko(i)),g.push(...s.contentParts),g.push(...e.contentParts),e.contentParts=g}else if(p){let g=[];l&&g.push(ko(l)),g.push(...s.contentParts),e.contentParts=g}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=Cc(),l=ii();this.activeAssistantMessageId=null;let c=n?.contentParts&&Mc(n.contentParts)?pi:"",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 g=new AbortController;if(this.abortController=g,n?.mentions){let f=this.messages.find(v=>v.id===i)??p;if(await this.applyMentionBundle(f,o,n.mentions.finalize),g.signal.aborted||this.abortController!==g)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let f=this.messages.find(h=>h.id===i)??p,v=Vy({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 u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,g,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=wu(f,this.config.errorMessage);if(h){let x={id:l,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(x)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(f instanceof Error?this.callbacks.onError?.(f):this.callbacks.onError?.(new Error(String(f))))}}resubmitFrom(e,n){let o=Ky(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 g=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}},u=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]}:{},...u?{composerOptions:u}:{},...v?{quote:v}:{},...g&&Object.keys(g).length>0?{replayFields:g}:{},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=ii();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=wu(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(u=>u.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,g=p&&typeof p=="object"?p.onDecision:void 0;try{let u;if(g?u=await g({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),u){let f=null;if(u instanceof Response){if(!u.ok){let v=await u.json().catch(()=>null);throw new Error(v?.error??`Approval request failed: ${u.status}`)}f=u.body}else u instanceof ReadableStream&&(f=u);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(u){let f=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}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(u=>u.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 u=e.toolCall?.args,f=Array.isArray(u?.questions)?u.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,g=Array.isArray(p?.questions)?p.questions:[];if(g.length===0){let u=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:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=l??{};g.forEach((f,v)=>{let h=typeof f?.question=="string"?f.question:"";if(!h)return;let x=u[h],E=Array.isArray(x)?x.join(", "):typeof x=="string"?x:"";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:E||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(s,{[i]:n},{after:this.resumable?.executionId===s?this.resumable.lastEventId:void 0});if(!u.ok){let f=await u.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let f=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}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!==Pr?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,s=Date.now(),i){this.messages.some(l=>l.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...i},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:s,duration:void 0,durationMs:Math.max(0,s-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let i=async p=>{let g=p.toolCall?.name,u=p.toolCall?.id;if(!g||!u)return null;let f=`${e}:${u}`;if(this.webMcpInflightKeys.has(f)||this.webMcpResolvedKeys.has(f)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(f),o.push(f);let v=this.markWebMcpToolRunning(p),h=p.agentMetadata?.webMcpToolCallId??g;if(g===Pr)return{dedupeKey:f,resumeKey:h,output:My(),toolMessage:p,startedAt:v,completedAt:Date.now()};let x=this.client.executeWebMcpToolCall(g,p.toolCall?.args,s.signal),E;if(!x)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await x}catch(M){let F=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));return F||this.callbacks.onError?.(M instanceof Error?M:new Error(String(M))),this.markWebMcpToolComplete(p,Su(F?"Aborted by cancel()":dA(M)),v),this.webMcpInflightKeys.delete(f),null}return s.signal.aborted?(this.markWebMcpToolComplete(p,Su("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:h,output:E,toolMessage:p,startedAt:v,completedAt:Date.now()}},l;if(this.config.webmcp?.execution==="sequential"){l=[];for(let p of n)l.push(await i(p))}else l=await Promise.all(n.map(i));let c=[];try{if(c=l.filter(u=>u!==null),c.length===0)return;let p={};for(let u of c)p[u.resumeKey]=u.output;let g=await this.client.resumeFlow(e,p,{signal:s.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!g.ok){let u=await g.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${g.status}`)}for(let u of c)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===Pr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let u of c)this.markWebMcpToolComplete(u.toolMessage,Su("Aborted by cancel()"),u.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);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,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!i.ok){let l=await i.json().catch(()=>null);throw new Error(l?.error??`Resume failed: ${i.status}`)}s?.onHttpOk?.(),i.body?await this.connectStream(i.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=Er(this.config.features?.artifacts,e),s=va(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=Er(this.config.features?.artifacts,n),i=va(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=Jy().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=>wu(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=ii(),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=vu(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return yu(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=vu(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 u=s.approval,f=n.approval;l.approval={...u,...f,executionId:f.executionId||u.executionId,toolName:f.toolName||u.toolName,description:f.description||u.description,toolType:f.toolType??u.toolType,reason:f.reason??u.reason,parameters:f.parameters??u.parameters}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,g=n.toolCall?.id;if(c&&Zy(c)&&p&&g&&n.agentMetadata?.awaitingLocalTool===!0){let u=`${p}:${g}`,f=this.webMcpInflightKeys.has(u),v=this.webMcpResolvedKeys.has(u),h=s.toolCall?.name,x=s.agentMetadata?.executionId===p&&s.toolCall?.id===g&&h!==void 0&&Zy(h)&&s.toolCall?.status==="complete";(f||v||x)&&(l.agentMetadata={...l.agentMetadata??{},awaitingLocalTool:!1},l.toolCall=s.toolCall,l.streaming=s.streaming)}return l}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),i=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=n.sequence??0,c=o.sequence??0;return l!==c?l-c:n.id.localeCompare(o.id)})}};import{File as pA,FileCode as uA,FileSpreadsheet as gA,FileText as xu,X as mA}from"lucide";var fA={add:t=>Hy(t)},hA=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Lc={allowedTypes:Zo,maxFileSize:10*1024*1024,maxFiles:4};function yA(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function bA(t){return t==="application/pdf"?xu:t.startsWith("text/")?xu:t.includes("word")?xu:t.includes("excel")||t.includes("spreadsheet")?gA:t==="application/json"?uA:pA}var Ta=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Lc.allowedTypes,maxFileSize:e.maxFileSize??Lc.maxFileSize,maxFiles:e.maxFiles??Lc.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:fA}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:Lc.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=Ry(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:yA(),file:o,previewUrl:Ec(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=hA(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=Ec(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 u=k("img");u.src=e.previewUrl,u.alt=e.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=k("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let f=bA(e.file.type),v=Zt(f,20,"var(--persona-muted, #6b7280)",1.5);v&&u.appendChild(v);let h=k("span");h.textContent=Wy(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",u.appendChild(h),o.appendChild(u)}let s=X("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=X("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",u=>{u.preventDefault(),u.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 g=Zt(mA,10,"var(--persona-text-inverse, #ffffff)",2);g?p.appendChild(g):(p.textContent="\xD7",p.style.color="var(--persona-text-inverse, #ffffff)",p.style.fontSize="14px",p.style.lineHeight="1"),p.addEventListener("click",u=>{u.preventDefault(),u.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 eb=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),vA=(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 tb(){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 u=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:u,inputDisabled:t.inputDisabled,sendDisabled:u!=="idle"||t.sendDisabled||t.inputDisabled})},c=()=>(n||(n=l()),n),p=()=>{if(o=!1,s||e.size===0)return;let u=c();for(let f of[...e])try{f(u)}catch(v){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",v)}},g=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(p))};return{getState:c,subscribe:u=>(e.add(u),()=>e.delete(u)),setText:u=>{t.text!==u&&(t.text=u,g())},setAttachments:u=>{vA(t.attachments,u)||(t.attachments=[...u],g())},setMentionRefs:u=>{eb(t.mentionRefs,u)||(t.mentionRefs=[...u],g())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,g())},setActiveModeIds:u=>{eb(t.activeModeIds,u)||(t.activeModeIds=[...u],g())},setQuote:u=>{let f=t.quote;f?.text===u?.text&&f?.messageId===u?.messageId&&f?.sourceLabel===u?.sourceLabel||(t.quote=u?{...u}:void 0,g())},setPendingSubmission:u=>{t.pendingSubmission!==u&&(t.pendingSubmission=u,g())},setPreparing:u=>{t.preparing!==u&&(t.preparing=u,g())},setStreaming:u=>{t.streaming!==u&&(t.streaming=u,g())},setInputDisabled:u=>{t.inputDisabled!==u&&(t.inputDisabled=u,g())},setSendDisabled:u=>{t.sendDisabled!==u&&(t.sendDisabled=u,g())},flush:()=>{o&&p()},destroy:()=>{s=!0,o=!1,e.clear()}}}var Sn=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},nb=(t,e)=>{let n=k("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function ob(t,e={}){let n=Sn(t,"[data-persona-composer-form]"),o=Sn(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:Sn(t,"[data-persona-composer-header]"),body:Sn(t,"[data-persona-composer-body]"),actionsStart:Sn(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Sn(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Sn(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Sn(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Sn(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=nb("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=(M,F,P,K,A)=>{if(F)return F;i.add(M);let L=nb(P,K);return A.appendChild(L),L},g=p("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=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=[],x=(M,F)=>M.target===F.target&&M.type===F.type&&M.handler===F.handler,E=Sn(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:l,body:c,actionsStart:g,actionsEnd:u,suggestions:f,status:v,attachmentInput:E,attachmentPreviews:Sn(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Sn(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Sn(t,"[data-persona-composer-submit]")??void 0,micButton:Sn(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(M,F,P,K)=>{M.addEventListener(F,P,K),h.push({target:M,type:F,handler:P,options:K})},removeListener:(M,F,P,K)=>{M.removeEventListener(F,P,K),h=h.filter(A=>!x(A,{target:M,type:F,handler:P}))},destroy:()=>{for(let M of h)M.target.removeEventListener(M.type,M.handler,M.options);h=[]}}}var CA=8,wA=8,Au=10,rb=200,sb=300,ib=0,Rc=t=>Math.max(0,t);function ab(t){t.delayMs!==void 0&&(rb=Rc(t.delayMs)),t.skipDelayMs!==void 0&&(sb=Rc(t.skipDelayMs))}var SA=()=>Date.now()<ib,xA=t=>{ib=t>0?Date.now()+t:0},Hc=new WeakMap,Eu="data-persona-tooltip-suppressed",AA=t=>typeof t.closest=="function"&&t.closest(`[${Eu}]`)!==null;function lb(t){Hc.get(t)?.hide()}var cb=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,MA=t=>{let e=t.getRootNode?.();return cb(e)?e:t.ownerDocument.body},Mu=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),EA=[...["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 Xt(t){Hc.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:s,enabled:i=!0,gap:l=CA,viewportPadding:c=wA}=t,p=()=>e.ownerDocument,g=()=>p().defaultView??window,u=null,f=null,v=null,h=null,x,E=!1,M=!1,F=!1,P=()=>(typeof o=="function"?o():o).trim(),K=()=>(typeof s=="function"?s():s??"").trim(),A=()=>Rc(t.delayMs??rb),L=()=>Rc(t.skipDelayMs??sb),w=()=>{x!==void 0&&(g().clearTimeout(x),x=void 0)},_=()=>{w();let me=u!==null;h?.(),h=null,u?.remove(),u=null,f=null,v=null,me&&xA(L())},G=()=>{if(!u)return;let me=p(),Te=g(),Le=e.getBoundingClientRect(),Ce=u.getBoundingClientRect(),Ze=me.documentElement.clientWidth||Te.innerWidth,we=me.documentElement.clientHeight||Te.innerHeight,U=Ze-c-Ce.width,ke=Le.left+Le.width/2-Ce.width/2,$e=Mu(ke,c,U),mt=Le.top-c,Re=we-c-Le.bottom,Ie=Ce.height+l,be=mt>=Ie||mt>=Re?"top":"bottom",lo=be==="top"?Le.top-l-Ce.height:Le.bottom+l,co=we-c-Ce.height,xs=Mu(lo,c,co),kt=Le.left+Le.width/2,po=Math.max(Au,Ce.width-Au),On=Mu(kt-$e,Au,po);u.dataset.placement=be,u.style.left=`${$e}px`,u.style.top=`${xs}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${On}px`)},le=()=>{if(F||!i||u||!e.isConnected||AA(e))return;let me=P(),Te=MA(e);if(!me||!Te)return;let Le=p(),Ce=g();u=Le.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(mc);let Ze=Ce.getComputedStyle?.(e);if(Ze){for(let Ie of EA){let be=Ze.getPropertyValue(Ie).trim();be&&u.style.setProperty(Ie,be)}Ze.fontFamily&&(u.style.fontFamily=Ze.fontFamily)}f=Le.createElement("span"),f.className="persona-control-tooltip__label",f.textContent=me,u.appendChild(f);let we=K();we&&(v=Le.createElement("span"),v.className="persona-control-tooltip__hint",v.textContent=we,u.appendChild(v));let U=Le.createElement("span");U.className="persona-control-tooltip__arrow",u.appendChild(U),Te.appendChild(u),G(),u.dataset.state="open";let ke=()=>{if(!e.isConnected){_();return}f&&(f.textContent=P()),v&&(v.textContent=K()),G()};Ce.addEventListener("scroll",ke,!0),Ce.addEventListener("resize",ke);let $e=e.getRootNode(),mt=cb($e)?$e:Le.documentElement,Re=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||_()});Re?.observe(mt,{childList:!0,subtree:!0}),h=()=>{Ce.removeEventListener("scroll",ke,!0),Ce.removeEventListener("resize",ke),Re?.disconnect()}},ee=me=>{if(!(F||u)){if(w(),me||A()<=0||SA()){le();return}x=g().setTimeout(()=>{x=void 0,le()},A())}},S=()=>{E||M?ee(M):_()},B=()=>{let me=g();(!me.matchMedia||!me.matchMedia("(hover: none)").matches)&&(E=!0,S())},R=()=>{E=!1,S()},I=()=>{try{M=e.matches(":focus-visible")}catch{M=!0}S()},Z=()=>{M=!1,S()},V=()=>{E=!1,M=!1,_()},ce=me=>{me.key==="Escape"&&V()};n.addEventListener("mouseenter",B),n.addEventListener("mouseleave",R),e.addEventListener("focus",I),e.addEventListener("blur",Z),e.addEventListener("keydown",ce),e.addEventListener("click",V);let ie={get isOpen(){return u!==null},show:le,hide:_,reposition:G,destroy:()=>{F||(F=!0,_(),n.removeEventListener("mouseenter",B),n.removeEventListener("mouseleave",R),e.removeEventListener("focus",I),e.removeEventListener("blur",Z),e.removeEventListener("keydown",ce),e.removeEventListener("click",V),Hc.delete(e))}};return Hc.set(e,ie),ie}var db=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ui(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];db(i)&&db(s)?n[o]=ui(i,s):n[o]=s}return n}var er="min(440px, calc(100vw - 24px))",ub="440px",Tu="How can I help...",TA={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:er,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:TA,copy:{inputPlaceholder:Tu,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 pb(t,e){if(!(!t&&!e))return t?e?ui(t,e):t:e}function Wc(t){return t?{...rt,...t,theme:pb(rt.theme,t.theme),darkTheme:pb(rt.darkTheme,t.darkTheme),launcher:{...rt.launcher,...t.launcher,dock:{...rt.launcher?.dock,...t.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...rt.tooltip,...t.tooltip},copy:{...rt.copy,...t.copy},sendButton:{...rt.sendButton,...t.sendButton},statusIndicator:{...rt.statusIndicator,...t.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=rt.features?.artifacts,n=t.features?.artifacts,o=rt.features?.scrollToBottom,s=t.features?.scrollToBottom,i=rt.features?.scrollBehavior,l=t.features?.scrollBehavior,c=rt.features?.streamAnimation,p=t.features?.streamAnimation,g=rt.features?.askUserQuestion,u=t.features?.askUserQuestion,f=rt.features?.history,v=t.features?.history,h=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},x=o===void 0&&s===void 0?void 0:{...o,...s},E=i===void 0&&l===void 0?void 0:{...i,...l},M=c===void 0&&p===void 0?void 0:{...c,...p},F=g===void 0&&u===void 0?void 0:{...g,...u,styles:{...g?.styles,...u?.styles}},P=f===void 0&&v===void 0?void 0:{...f,...v,copy:{...f?.copy,...v?.copy}};return{...rt.features,...t.features,...x!==void 0?{scrollToBottom:x}:{},...E!==void 0?{scrollBehavior:E}:{},...h!==void 0?{artifacts:h}:{},...M!==void 0?{streamAnimation:M}:{},...F!==void 0?{askUserQuestion:F}:{},...P!==void 0?{history:P}:{}}})(),suggestionChips:t.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...rt.layout,...t.layout,header:{...rt.layout?.header,...t.layout?.header},messages:{...rt.layout?.messages,...t.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...t.layout?.slots}},markdown:{...rt.markdown,...t.markdown,options:{...rt.markdown?.options,...t.markdown?.options}},messageActions:{...rt.messageActions,...t.messageActions}}:rt}function ku(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 Bc(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function gb(t,e){t.style.maxHeight=`${e*ku(t)}px`,t.style.overflowY="auto"}function Ia(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 mb(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function fb(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||!mb(e)}function kA(t){return(t.submitKey??"enter")!=="enter"||mb(t)?"enter":"send"}function _c(t,e){t.setAttribute("enterkeyhint",kA(e))}function Oc(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 Pu(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 Bn="persona-composer-control",ao="persona-composer-control--glyph",Lu=40,cn=24,Dc=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let s=o.getComputedStyle(t);for(let i of n){let l=s.getPropertyValue(i).trim();l?e.style.setProperty(i,l):e.style.removeProperty(i)}},Nc=(t,e)=>{let n=k("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??Tu,n.dir="auto",_c(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:Ia(n)}),Oc(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=Bc(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 g=parseFloat(c);if(Number.isFinite(g)&&g>0)return g}let p=o*ku(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}},IA="[data-persona-glyph-stack]",Hu=(t,e,n="send")=>{let o=X("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},Fc=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",g=t?.copy?.stopButtonLabel??"Stop",u=e.showTooltip??!1,f=e.size,v=parseFloat(f??"")||Lu,h=e.backgroundColor,x=e.textColor,E=k("div","persona-send-button-wrapper"),M=X("button",{className:Wn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Bn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!x&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?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?x||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":x||void 0,backgroundColor:n&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),F=null,P=null,K=null;if(n){let w=parseFloat(e.iconSize??"")||Math.round(v*.5),_=e.iconStrokeWidth??2,G=x?.trim()||"currentColor";s&&(F=he(s,w,G,_)),P=he(i,w,G,_),F&&P?(K=Hu(F,P),M.appendChild(K)):F?M.appendChild(F):(M.textContent=o,P=null)}else M.textContent=p;M.setAttribute("aria-label",l),E.appendChild(M),Xt({anchor:M,trigger:E,text:()=>M.getAttribute("aria-label")??"",enabled:u});let A="send";return{button:M,wrapper:E,setMode:w=>{if(w===A)return;A=w;let _=w==="stop"?c:l;M.setAttribute("aria-label",_),M.setAttribute("data-persona-send-mode",w),n?(M.querySelector(IA)??K)?.setAttribute("data-mode",w):M.textContent=w==="stop"?g:p},glyphStack:K}},gi=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,g=parseFloat(p??"")||cn,u=e.backgroundColor??t?.sendButton?.backgroundColor,f=e.iconColor??t?.sendButton?.textColor,v=k("div","persona-send-button-wrapper"),h=X("button",{className:Wn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Bn,!p&&ao),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:u||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}}),E=he(c,g,f||"currentColor",1.5);E?h.appendChild(E):h.textContent="\u{1F3A4}",v.appendChild(h);let M=e.tooltipText??"Start voice recognition",F=e.showTooltip??!1;return Xt({anchor:h,trigger:v,text:()=>h.getAttribute("aria-label")??M,enabled:F}),{button:h,wrapper:v}},Uc=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??Zo).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=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Bn} ${ao}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),c=he(s,cn,"currentColor",1.5);c?l.appendChild(c):l.textContent="\u{1F4CE}",l.addEventListener("click",g=>{g.preventDefault(),o.click()}),i.appendChild(l);let p=e.buttonTooltipText??"Attach file";return Xt({anchor:l,trigger:i,text:()=>l.getAttribute("aria-label")??p}),{button:l,wrapper:i,input:o,previewsContainer:n}},$c=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},qc=()=>X("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var LA='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',HA=["--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"],Ru="data-persona-menu-focus",RA=new Set(["ArrowDown","ArrowUp","Home","End"]);function hb(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(LA)??t}var WA=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function yb(t){let e=t.label,n=!1,o=k("div","persona-send-button-wrapper"),s=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Bn} ${ao}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=X("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 Z=he("plus",cn,"currentColor",1.5);Z?s.appendChild(Z):s.textContent="+"},c=()=>{s.setAttribute("aria-label",e),s.setAttribute("title",e),i.setAttribute("aria-label",e)};c(),l();let p=[],g=-1,u=!1,f=()=>{let Z=i.getRootNode().activeElement;return Z instanceof HTMLElement?Z:null},v=()=>{let I=f();for(let Z of p){let V=!!I&&hb(Z)===I;Z.toggleAttribute(Ru,V&&u)}},h=()=>p.filter(I=>I.isConnected||i.contains(I)).map(hb).filter(I=>!WA(I)),x=(I,Z)=>{I.forEach((V,ce)=>{V.setAttribute("tabindex",ce===Z?"0":"-1")})},E=I=>{let Z=h();if(Z.length===0)return;let V=(I%Z.length+Z.length)%Z.length;g=V,x(Z,V),Z[V].focus(),v()},M=()=>o.ownerDocument??document,F=null,P=null,K=null,A=()=>{F&&(M().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=fc({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),A()}})),w),G=()=>w?.isOpen===!0,le=(I=!1)=>{if(G()){w?.close(),s.setAttribute("aria-expanded","false"),A(),L(),g=-1,u=!1;for(let Z of p)Z.removeAttribute(Ru);I&&s.focus()}},ee=(I=0,Z=!1)=>{if(n||G())return;u=Z,Dc(s,i,HA),_().open(),s.setAttribute("aria-expanded","true");let V=h();x(V,-1),E(I<0?V.length-1:I),F=ce=>{let ie=typeof ce.composedPath=="function"?ce.composedPath():[];ie.includes(i)||ie.includes(o)||le()},M().addEventListener("focusin",F,!0),P=()=>v(),i.addEventListener("focusin",P),K=()=>{u=!1},i.addEventListener("pointerdown",K,!0)},S=I=>{I.preventDefault(),I.stopPropagation(),G()?le(!0):ee(0)},B=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),u=!0,G()?E(0):ee(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),u=!0,G()?E(-1):ee(-1,!0))},R=I=>{switch(RA.has(I.key)&&(u=!0),I.key){case"ArrowDown":I.preventDefault(),E(g+1);return;case"ArrowUp":I.preventDefault(),E(g-1);return;case"Home":I.preventDefault(),E(0);return;case"End":I.preventDefault(),E(h().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),le(!0);return;case"Tab":le(!0);return;default:}};return s.addEventListener("click",S),s.addEventListener("keydown",B),i.addEventListener("keydown",R),{trigger:o,triggerButton:s,panel:i,setItems:I=>{for(let V of p)I.includes(V)||V.removeAttribute(Ru);if(p=[...I],!G())return;let Z=h();x(Z,Math.min(g,Z.length-1)),v()},isOpen:G,open:()=>ee(0),close:le,setLabel:I=>{I!==e&&(e=I,c())},applyButtonSize:l,destroy:()=>{n=!0,A(),L(),s.removeEventListener("click",S),s.removeEventListener("keydown",B),i.removeEventListener("keydown",R),w?.destroy(),w=null,o.remove(),i.remove(),p=[]}}}var Io={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},bb="data-persona-composer-action",Wu="data-persona-composer-disable-when-streaming",BA="core:overflow",_A=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function OA(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 Bu(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 vb=(t,e)=>{!t||typeof console>"u"||console.warn(e)},DA=(t,e)=>e.includes(":")?e:`${t}:${e}`;function NA(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let p=o.get(c.id);if(p){vb(e,`[Persona] composer action "${c.id}" is already contributed by ${Cb(p)}; the ${Cb(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,g)=>{let u=g?DA(g,c.id):c.id,f=c.order??Io.custom;c.placement==="end"&&f>=Io.send&&(vb(e,`[Persona] composer action "${u}" ordered at ${f} would render after send; clamped to ${Io.send-1}.`),f=Io.send-1),i({id:u,placement:c.placement,presentation:c.presentation??"bar",order:f,sequence:s++,source:p,pluginId:g,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(g){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,g);continue}for(let g of p??[])l(g,"plugin",c.id)}return n.sort((c,p)=>c.order===p.order?c.sequence-p.sequence:c.order-p.order)}var Cb=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",wb=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,FA=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function UA(t,e){if(!t||t==="always")return!0;let n=FA(e);return t==="when-text"?n:!n}var Hr=t=>t.kind==="custom",_u=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,$A=t=>{let e=_u(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},qA='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function zA(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(qA)||o.childNodes.forEach(n)};return n(t),e.trim()}var jA=t=>zA(t).length===0;function Sb(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(S,B)=>{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",B.tooltipText?R.setAttribute("title",B.tooltipText):R.removeAttribute("title"),R.replaceChildren();let I=k("span","persona-composer-overflow-menu__icon");if(B.iconName){let V=he(B.iconName,16,"currentColor",1.5);V&&I.appendChild(V)}let Z=k("span","persona-composer-overflow-menu__label");Z.textContent=B.shortLabel??B.label,R.append(I,Z)},l=(S,B)=>{let R=S.button;if(!R)return;if(R.setAttribute("aria-label",B.label),B.pressed===void 0?R.removeAttribute("aria-pressed"):R.setAttribute("aria-pressed",B.pressed?"true":"false"),R.toggleAttribute(Wu,B.disableWhenStreaming===!0),S.mode==="menu"){S.tooltip?.destroy(),S.tooltip=void 0,i(S,B);return}R.removeAttribute("role"),R.removeAttribute("tabindex"),R.removeAttribute("title");let I=s(),Z=!!B.shortLabel;if(R.className=Wn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Bn,ao,Z&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),R.style.width=I&&!Z?I:"",R.style.height=I??"",R.style.minWidth=I&&!Z?I:"",R.style.minHeight=I??"",R.style.fontSize=Z?"":"18px",R.style.lineHeight="1",R.style.color=B.iconColor??"",R.style.backgroundColor=B.backgroundColor??"",R.replaceChildren(),B.iconName){let V=he(B.iconName,cn,"currentColor",1.5);V&&R.appendChild(V)}if(Z){let V=k("span","persona-composer-action-button__label");V.textContent=B.shortLabel,R.appendChild(V)}else R.firstChild||(R.textContent=B.label);S.tooltip?.destroy(),S.tooltip=Xt({anchor:R,trigger:S.element,text:()=>B.tooltipText??B.label,enabled:!!B.tooltipText})},c=(S,B)=>{let R=S.action,I=X("button",{attrs:{type:"button"}}),Z=I;if(B==="bar"){let ie=k("div","persona-send-button-wrapper");ie.appendChild(I),Z=ie}Z.setAttribute(bb,S.id);let V={resolved:S,element:Z,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:B},ce=ie=>{if(ie.preventDefault(),ie.stopPropagation(),V.busy||I.disabled)return;let me=V.resolved.action;V.mode==="menu"&&h?.close(!0);let Te;try{Te=me.onSelect(t.actionContext,ie)}catch(Le){t.reportError(Le,{actionId:V.resolved.id});return}!Te||typeof Te.then!="function"||(V.busy=!0,I.setAttribute("aria-busy","true"),Te.catch(Le=>{t.reportError(Le,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",ce),V.detach=()=>I.removeEventListener("click",ce),l(V,R),V},p=S=>{let B=S.action,R;try{R=B.render({...t.actionContext,id:S.id,action:B})}catch(I){return t.reportError(I,{actionId:S.id}),null}return R?.element?(R.element.setAttribute(bb,S.id),R.element.toggleAttribute(Wu,B.disableWhenStreaming===!0),{resolved:S,element:R.element,owned:!0,managed:!0,destroy:R.destroy,busy:!1,visible:!0,mode:"bar"}):null},g=(S,B)=>{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?Hr(R)?p(S):c(S,B):null},u=S=>{if(S.detach?.(),S.tooltip?.destroy(),S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0,S.owned){try{S.destroy?.()}catch(B){t.reportError(B,{actionId:S.resolved.id})}S.element.remove()}},f=(S,B)=>{for(let R=0;R<B.length;R++){let I=B[R];if(!I.managed)continue;let Z=null;for(let V=R+1;V<B.length;V++){let ce=B[V];if(!ce.managed&&ce.element.parentElement===S){Z=ce.element;break}}Z?(I.element.parentElement!==S||I.element.nextSibling!==Z)&&S.insertBefore(I.element,Z):S.lastChild!==I.element&&S.appendChild(I.element)}},v=(S,B)=>{if(S.button){S.button.disabled=B;return}if(!S.owned)return;let R=S.element;R.toggleAttribute("data-disabled",B),R.setAttribute("aria-disabled",B?"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=B)},h=null,x=null,E=null,M=0,F=()=>{let S=t.getOverflow?.();return S?.enabled===!0?S:void 0},P=()=>(h?h.setLabel(t.getOverflowLabel?.()??"More actions"):h=yb({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),h),K=S=>{x!==S&&(E?.disconnect(),x=S,M=Bu(S),!(typeof ResizeObserver>"u")&&(E=new ResizeObserver(B=>{let I=B[B.length-1]?.contentRect?.width??Bu(S);I!==M&&(M=I,le())}),E.observe(S)))},A=(S,B)=>{let R=OA(S.collapseAutoActionsBelow,B);if(R===null)return!1;let I=M||Bu(B);return I>0&&I<R},L=(S,B,R)=>{if(!B)return"bar";if(S.resolved.builtIn){let Z=_A(S.resolved.id);return Z&&B.includeBuiltIns?.includes(Z)?"menu":"bar"}let I=S.resolved.presentation;return I==="overflow"||I==="auto"&&R?"menu":"bar"},w=S=>{let B=S.menuSlot;if(!B)return;if(!jA(S.element)){S.menuLabel?.remove(),S.menuLabel=void 0;return}let R=$A(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!==B&&B.appendChild(S.menuLabel)},_=(S,B)=>{if(S.mode===B)return S;let R=S.resolved.action;if(R&&!Hr(R)){u(S),e.delete(S.resolved.id);let I=c(S.resolved,B);return e.set(S.resolved.id,I),I}if(B==="menu"){let I=X("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Eu]:""}});I.appendChild(S.element),lb(_u(S.element)),S.menuSlot=I;let Z=V=>{let ce=_u(S.element);if(ce.disabled)return;let ie=V.target===ce||ce.contains(V.target);h?.close(!0),ie||ce.click()};I.addEventListener("click",Z,!0),S.detachMenuSlot=()=>I.removeEventListener("click",Z,!0),S.managed=!0,w(S)}else S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0;return S.mode=B,S},G=(S,B)=>{let R=B.map(I=>I.menuSlot??I.element);for(R.forEach((I,Z)=>{let V=S.children[Z];V!==I&&(V?S.insertBefore(I,V):S.appendChild(I))});S.children.length>R.length;)S.lastElementChild?.remove()},le=()=>{if(o)return;let S=t.getBindings();if(!S)return;let B=t.getState(),R=B.phase==="streaming",I=F();I&&K(S.footer);let Z=I?A(I,S.footer):!1,V={start:[],end:[]},ce=[];for(let ie of n){let me=e.get(ie.id);if(!me)continue;let Te=ie.action,Le=Te?wb(Te.visible,B,!0)&&UA(Te.visibility,B):!0;if(me.visible!==Le&&(me.visible=Le,!Le&&me.managed&&(me.menuSlot??me.element).remove()),!!Le){if(me=_(me,L(me,I,Z)),Te){let Ce=wb(Te.disabled,B,!1)||Te.disableWhenStreaming===!0&&R;v(me,Ce),!Hr(Te)&&Te.pressed!==void 0&&me.button?.setAttribute("aria-pressed",Te.pressed?"true":"false")}me.mode==="menu"?(w(me),ce.push(me)):V[ie.placement].push(me)}}if(ce.length>0){let ie=P();G(ie.panel,ce),ie.setItems(ce.map(Ce=>Ce.menuSlot??Ce.element)),ie.applyButtonSize();let me=Number.isFinite(I?.order)?I?.order:Io.overflow,Te=V.start.findIndex(Ce=>Ce.resolved.order>me),Le={resolved:{id:BA,placement:"start",presentation:"bar",order:me,sequence:-1,source:"core"},element:ie.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(Te<0?V.start.length:Te,0,Le)}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=NA(t.collect()),B=new Set(S.map(R=>R.id));for(let[R,I]of e)B.has(R)||(u(I),e.delete(R));for(let R of S){let I=e.get(R.id);if(!I){let ie=g(R,"bar");ie&&e.set(R.id,ie);continue}let Z=I.resolved.action,V=R.action;if(!!Z!=!!V||Z&&V&&Hr(Z)!==Hr(V)||Z&&V&&Hr(Z)&&Hr(V)&&Z.render!==V.render){u(I),e.delete(R.id);let ie=g(R,I.mode);ie&&e.set(R.id,ie);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&&!Hr(V)?l(I,V):V&&I.element.toggleAttribute(Wu,V.disableWhenStreaming===!0)}n=S,le()},sync:le,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,E?.disconnect(),E=null,x=null;for(let S of e.values())u(S);e.clear(),h?.destroy(),h=null,n=[]}}}}var VA="core:model",KA=700,xb=16,GA=["--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"],Ab=()=>{let t=X("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=X("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Mb(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=p=>{let g=t.getSelectedModelId();return p.find(u=>u.id===g)??p[0]},i=()=>{let p=X("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),g="",u=()=>{let E=t.getModels(),M=E.map(F=>`${F.id}:${F.label}`).join("|");M!==g&&(g=M,p.replaceChildren(...E.map(F=>{let P=X("option",{attrs:{value:F.id}});return P.textContent=F.label,P}))),p.value=s(E)?.id??""};u(),o=u;let f=()=>{p.value&&t.onSelect(p.value)};p.addEventListener("change",f);let v=E=>E.stopPropagation();p.addEventListener("click",v);let{wrapper:h,chevron:x}=Ab();return h.append(p,x),{element:h,destroy:()=>{o===u&&(o=null),p.removeEventListener("change",f),p.removeEventListener("click",v)}}},l=()=>{let p=X("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"}}),g=k("span","persona-composer-model-picker-label"),u=k("span","persona-composer-model-picker-suffix");p.append(g,u);let f=X("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),v=new Map,h="",x=null,E=()=>x?.isOpen===!0,M=(B=!1)=>{E()&&(x?.close(),p.setAttribute("aria-expanded","false"),B&&p.focus())},F=B=>{let R=[...v.values()];if(R.length===0)return;let I=(B%R.length+R.length)%R.length;R[I].focus()},P=B=>{if(E())return;x||(x=fc({anchor:p,content:f,placement:"top-start",offset:6,onDismiss:()=>p.setAttribute("aria-expanded","false")})),Dc(p,f,GA),x.open(),p.setAttribute("aria-expanded","true");let I=[...v.keys()].indexOf(s(t.getModels())?.id??"");F(B??(I>=0?I:0))},K=B=>{M(!0),t.onSelect(B)},A=B=>{B.preventDefault(),B.stopPropagation();let R=B.currentTarget.getAttribute("data-persona-model-option");R&&K(R)},L=B=>{let R=X("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":B.id}});if(B.icon){let ie=he(B.icon,xb,"currentColor",1.5);if(ie){let me=k("span","persona-composer-model-option-icon");me.appendChild(ie),R.appendChild(me)}}let I=k("span","persona-composer-model-option-body"),Z=k("span","persona-composer-model-option-label");if(Z.textContent=B.label,I.appendChild(Z),B.description){let ie=k("span","persona-composer-model-option-description");ie.textContent=B.description,I.appendChild(ie)}R.appendChild(I);let V=k("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let ce=he("check",xb,"currentColor",2);return ce&&V.appendChild(ce),R.appendChild(V),R.addEventListener("click",A),R},w=()=>{let B=t.getModels(),R=B.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",A);v.clear(),f.replaceChildren(...B.map(V=>{let ce=L(V);return v.set(V.id,ce),ce}))}let I=s(B);for(let[V,ce]of v)ce.setAttribute("aria-selected",String(V===I?.id));g.textContent=I?.label??"";let Z=t.getSuffix?.()??"";u.textContent=Z,p.setAttribute("aria-label",[e,[I?.label,Z].filter(Boolean).join(" ")].filter(Boolean).join(": "))};w(),o=w;let _=B=>{B.preventDefault(),B.stopPropagation(),E()?M(!0):P()},G=B=>{if(B.key==="ArrowDown"){B.preventDefault(),E()?F(0):P(0);return}B.key==="ArrowUp"&&(B.preventDefault(),E()?F(-1):P(-1))},le=B=>{let R=[...v.values()],I=R.indexOf(B.target?.closest?.(".persona-composer-model-option"));switch(B.key){case"ArrowDown":B.preventDefault(),F(I+1);return;case"ArrowUp":B.preventDefault(),F(I-1);return;case"Home":B.preventDefault(),F(0);return;case"End":B.preventDefault(),F(R.length-1);return;case"Escape":B.preventDefault(),B.stopPropagation(),M(!0);return;case"Tab":M(!0);return;default:}};p.addEventListener("click",_),p.addEventListener("keydown",G),f.addEventListener("keydown",le);let{wrapper:ee,chevron:S}=Ab();return ee.append(p,S),{element:ee,destroy:()=>{o===w&&(o=null),p.removeEventListener("click",_),p.removeEventListener("keydown",G),f.removeEventListener("keydown",le);for(let B of v.values())B.removeEventListener("click",A);v.clear(),x?.destroy(),x=null,f.remove()}}};return{action:{id:VA,kind:"custom",placement:"end",order:KA,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var QA=":scope > [data-persona-composer-mode]";function Eb(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=g=>{let u=X("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":g.id}});if(g.iconName){let x=k("span","persona-mention-chip-icon"),E=he(g.iconName,12,"currentColor",1.5);E&&x.appendChild(E),u.appendChild(x)}let f=k("span","persona-mention-chip-label");f.textContent=g.shortLabel??g.label,u.appendChild(f);let v=X("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${g.label}`}}),h=he("x",12,"currentColor",2);return h?v.appendChild(h):v.textContent="\xD7",v.addEventListener("click",x=>{x.preventDefault(),x.stopPropagation(),t.onRemove(g.id)}),u.appendChild(v),u},l=()=>Array.from(e.querySelectorAll(QA)),c=g=>{g.setAttribute("data-persona-chip-exit",""),g.setAttribute("aria-hidden","true"),g.style.pointerEvents="none";let u=()=>{g.remove(),hc(e)},f=e.ownerDocument.defaultView,v=typeof f?.getComputedStyle=="function"?f.getComputedStyle(g).animationName:"";if(!v||v==="none"){u();return}g.addEventListener("animationend",u,{once:!0}),g.addEventListener("animationcancel",u,{once:!0})},p=()=>{for(let g of l())g.remove()};return{element:e,render:(g,u)=>{if(o)return;let f=u.filter(E=>g.includes(E.id)),v=f.map(E=>`${E.id}:${E.shortLabel??E.label}`).join("|");if(v===n)return;n=v;let h=new Map;for(let E of l()){let M=E.getAttribute("data-persona-composer-mode");M&&f.some(P=>P.id===M)&&!E.hasAttribute("data-persona-chip-exit")?h.set(M,E):E.hasAttribute("data-persona-chip-exit")||c(E)}let x=e.firstChild;for(let E of f){let M=h.get(E.id);M||(M=i(E),s.has(E.id)||(M.setAttribute("data-persona-chip-enter",""),M.addEventListener("animationend",()=>M?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(E.id),M!==x&&e.insertBefore(M,x),x=M.nextSibling}hc(e)},destroy:()=>{o=!0,p(),hc(e)}}}var Tb=t=>`core:mode:${t}`;var Ou=t=>Math.min(300+t,499),kb=t=>`core:mode-group:${t}`;function zc(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function XA(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Pb(t,e){return t?.length?t.filter(n=>!zc(n.groupId,e)&&!XA(n.groupId,e)):[]}var YA=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Ib(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(YA(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 jc(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Lb(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Hb(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var JA=16;function Rb(t){let e=null;return{action:{id:kb(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=X("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=g=>{g.preventDefault(),g.stopPropagation();let f=g.currentTarget.getAttribute("data-persona-composer-mode");!f||t.getActiveIds().includes(f)&&t.getGroup()?.selection==="single"||t.onSelect(f)},c=g=>{let u=X("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":g.id,"aria-label":g.label}});if(g.iconName){let v=he(g.iconName,JA,"currentColor",1.5);v&&u.appendChild(v)}let f=k("span","persona-composer-segmented-label");return f.textContent=g.shortLabel??g.label,u.appendChild(f),u.addEventListener("click",l),u},p=()=>{let g=t.getGroup();g?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",g.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=t.getModes(),f=u.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(f!==i){i=f;for(let x of s.values())x.removeEventListener("click",l);s.clear();let h=u.map(x=>{let E=c(x);return s.set(x.id,E),E});o.replaceChildren(...h)}let v=t.getActiveIds();for(let[h,x]of s)x.setAttribute("aria-pressed",String(v.includes(h)))};return p(),e=p,{element:o,destroy:()=>{e===p&&(e=null);for(let g of s.values())g.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function Wb(t){let e=X("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=X("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});p.textContent=kc(i.text),c.appendChild(p);let g=X("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=he("x",12,"currentColor",2);u?g.appendChild(u):g.textContent="\xD7",g.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),t.onDismiss()}),e.replaceChildren(l,c,g)};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 Bb(t){let e=X("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,p,g)=>{let u=X("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[p]:""}}),f=he(l,12,"currentColor",2);return f?u.appendChild(f):u.textContent=c,u.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),g()}),u},i=l=>{let c=kc(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(u=>u.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=X("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 _b(t){let e=X("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=X("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,g,u)=>{let f=X("button",{className:`persona-message-edit-button ${p}`,attrs:{type:"button",[g]:""},text:c});return f.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),u()}),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 Ob(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 Db(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 Nb(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 Fb(t){return t.wrapped||t.text.includes(`
17
- `)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function Ub(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function $b(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 Du(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 zb(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var ZA=t=>typeof t?.then=="function";function qb(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 jb(t,e,n){let o;try{o=t(Du(e),{signal:n})}catch(s){return{status:"error",error:s}}return ZA(o)?Promise.resolve(o).then(s=>n.aborted?{status:"aborted"}:qb(e,s),s=>n.aborted?{status:"aborted"}:{status:"error",error:s}):qb(e,o)}function Vb(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",s=e.buttonTooltipText??"Add context",i=k("div","persona-send-button-wrapper"),l=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Bn} ${ao}`,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,cn,"currentColor",1.5);return c?l.appendChild(c):l.textContent="+",l.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),n()}),i.appendChild(l),Xt({anchor:l,trigger:i,text:()=>l.getAttribute("aria-label")??s}),{button:l,wrapper:i}}var{setLoader:v0,load:eM}=Tt({fallbackImport:()=>import("./context-mentions-45MODWOY.js")});var Nu=eM;var{setLoader:S0,load:tM}=Tt({fallbackImport:()=>import("./context-mentions-inline-I2RDEBAK.js"),resetOnSetLoader:!0});var Kb=tM;function La(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=X("span",{className:Wn("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(X("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function Gb(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=$h(e).filter(A=>A.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(A=>A.sources.some(L=>typeof L.matchCommand=="function")),s=A=>o.some(L=>L.trigger?L.position==="line-start"?A.split(`
18
- `).some(_=>_.startsWith(L.trigger)):(L.position==="anywhere"?A:A.split(`
19
- `)[0]).startsWith(L.trigger):!1),i=(A,L)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:L}))}catch{}},l=!t.chipRow,c=t.chipRow??X("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),p=null,g=null,u=t.textarea,f=null,v=null,h=null,x=null,E=()=>{if(p)return Promise.resolve(p);if(g)return g;let A=Nu().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),g===A&&(g=null),null));return g=A,A},M=()=>{Kb().then(A=>{let L=A.mountInlineComposer({textarea:t.textarea,renderToken:_=>La(_,{render:e.renderMentionToken}),onMentionRemoved:_=>p?.untrackMention(_)});f=L.input,v=L.destroy;let w=u;w.replaceWith(L.element),u=L.element,x={next:L.element,prev:w},h?.(L.element,w),p?p.rebindComposer(L.input):g&&g.then(_=>_?.rebindComposer(L.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&M();let F=[],P=new Map;for(let A of n){if(!A.showButton)continue;let L=Vb({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{E().then(w=>w?.openMenu(A.trigger))}});F.push(L),P.set(A.trigger,L.button)}let K=(A,L,w)=>{let _=P.get(L);_&&(_.setAttribute("aria-expanded",A?"true":"false"),A?_.setAttribute("aria-controls",w):_.removeAttribute("aria-controls"))};return{affordanceButtons:F.map(A=>A.wrapper),contextRow:c,handleInput:A=>{if(p){p.handleInput();return}if(!Uh(A))return;let L=u,w=L.selectionStart??0;Fh(L.value,w,n)&&E().then(_=>_?.handleInput())},handleKeydown:A=>{if(p?.isMenuOpen())return p.handleKeydown(A);if(A.key==="Backspace"&&p?.hasMentions()&&!x){let L=u,w=L.selectionStart===0&&L.selectionEnd===0;if((L.value.length===0||w)&&p.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>p?.isMenuOpen()??!1,hasMentions:()=>p?.hasMentions()??!1,getMentionRefs:()=>p?.getMentionRefs()??[],collectForSubmit:()=>p?.collectForSubmit()??null,takeInlineCommand:async A=>s(A)?(p??await E())?.dispatchInlineCommand(A)??null:null,clear:()=>p?.clear(),prefetch:()=>{Nu().catch(()=>{})},onComposerSwap:A=>{h=A,x&&A(x.next,x.prev)},destroy:()=>{p?.destroy(),v?.();for(let A of F)A.wrapper.remove();l&&c.remove()}}}var Vc="16px",Kc="transparent",nM=(()=>{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})(),oM={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:nM,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"}},rM={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"}},sM={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:er,maxWidth:ub,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Vc,canvasBackground:Kc},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 dn(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."))?dn(t,o):o}function Xb(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=dn(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 iM(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 Yb(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]=Yb(i,s):n[o]=s}return n}function aM(t,e){return e?Yb(t,e):t}function mi(t,e={}){let n={palette:oM,semantic:rM,components:sM},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:aM(n.components,t?.components)};if(e.validate!==!1){let s=iM(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 Fu=t=>t.trim()==="0"?"0px":t,Qb="--persona-",lM=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 g=p.endsWith("%"),u=parseFloat(g?p.slice(0,-1):p);return g?u/100*255:u}))}}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},cM=.179,Yt=(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[Qb+i],s!==void 0)break;s!==void 0&&(t[Qb+n]=s)}};function Jb(t){let e=Xb(t),n={};for(let[U,ke]of Object.entries(e)){let $e=U.replace(/\./g,"-");n[`--persona-${$e}`]=ke.value}Yt(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"],Yt(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"]]),Yt(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"]}`,Yt(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"]??Vc,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Kc,Yt(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"]]),Yt(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"],Yt(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"],Yt(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 g=n["--persona-components-history-railHeader-border"];g&&(n["--persona-history-rail-header-border"]=g);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[U,ke]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let $e=n[`--persona-components-history-overlay-${U}`];$e&&(n[`--persona-history-overlay-${ke}`]=$e)}for(let[U,ke]of[["background","bg"],["borderRadius","radius"]]){let $e=n[`--persona-components-history-menu-${U}`];$e&&(n[`--persona-history-menu-${ke}`]=$e)}let f=t.components?.history?.motion;if(f){let U=mt=>{if(mt===void 0)return;let Re=String(mt).trim();return/^\d+(\.\d+)?$/.test(Re)?`${Re}ms`:Re},ke=U(f.enterDurationMs);ke!==void 0&&(n["--persona-history-enter-ms"]=ke);let $e=U(f.exitDurationMs);$e!==void 0&&(n["--persona-history-exit-ms"]=$e),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 U of["scrim","shadow"]){let ke=n[`--persona-components-history-confirm-${U}`];ke&&(n[`--persona-history-confirm-${U}`]=ke)}for(let[U,ke]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let $e=n[`--persona-components-tooltip-${U}`];$e&&(n[`--persona-tooltip-${ke}`]=$e)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[U,ke]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let $e=n[`--persona-components-messageActions-${U}`];$e&&(n[`--persona-message-action-${ke}`]=$e)}Yt(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],x=n["--persona-components-introCard-shadow"],E=(!h||h==="transparent"||h==="none")&&(!x||x==="none"),M=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=E&&M==="1.5rem"?"1.5rem 0":M,Yt(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"]]),Yt(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 A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let L=n["--persona-components-markdown-prose-fontFamily"];L&&L!=="inherit"&&(n["--persona-md-prose-font-family"]=L),Yt(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"]]),Yt(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Yt(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Yt(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Yt(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"],Yt(n,[["message-border","components-message-border","border"]]),Yt(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 le=w?.toggleGroup;le&&(le.gap&&(n["--persona-toggle-group-gap"]=le.gap),le.borderRadius&&(n["--persona-toggle-group-radius"]=le.borderRadius));let ee=w?.artifact;if(ee?.toolbar){let U=ee.toolbar;U.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=U.iconHoverColor),U.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=U.iconHoverBackground),U.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=U.iconPadding),U.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=U.iconBorderRadius),U.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=U.iconBorder),U.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Fu(U.toggleGroupGap)),U.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=U.toggleBorderRadius),U.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Fu(U.toggleGroupPadding)),U.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=U.toggleGroupBorder),U.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=U.toggleGroupBorderRadius),U.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=dn(t,U.toggleGroupBackground)??U.toggleGroupBackground),U.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=U.copyBackground),U.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=U.copyBorder),U.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=U.copyColor),U.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Fu(U.copyBorderRadius)),U.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=U.copyPadding),U.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=U.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??U.copyMenuBackground),U.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=U.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??U.copyMenuBorder),U.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=U.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??U.copyMenuShadow),U.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=U.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??U.copyMenuBorderRadius),U.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=U.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??U.copyMenuItemHoverBackground),U.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=U.iconBackground),U.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=U.toolbarBorder)}if(ee?.tab){let U=ee.tab;U.background&&(n["--persona-artifact-tab-bg"]=U.background),U.activeBackground&&(n["--persona-artifact-tab-active-bg"]=U.activeBackground),U.activeBorder&&(n["--persona-artifact-tab-active-border"]=U.activeBorder),U.borderRadius&&(n["--persona-artifact-tab-radius"]=U.borderRadius),U.textColor&&(n["--persona-artifact-tab-color"]=U.textColor),U.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=U.hoverBackground),U.listBackground&&(n["--persona-artifact-tab-list-bg"]=U.listBackground),U.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=U.listBorderColor),U.listPadding&&(n["--persona-artifact-tab-list-padding"]=U.listPadding)}if(ee?.pane){let U=ee.pane;if(U.toolbarBackground){let ke=dn(t,U.toolbarBackground)??U.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ke}}if(ee?.card){let U=ee.card;U.background&&(n["--persona-artifact-card-bg"]=U.background),U.border&&(n["--persona-artifact-card-border"]=U.border),U.borderRadius&&(n["--persona-artifact-card-radius"]=U.borderRadius),U.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=U.hoverBackground),U.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=U.hoverBorderColor)}if(ee?.inline){let U=ee.inline;U.background&&(n["--persona-artifact-inline-bg"]=dn(t,U.background)??U.background),U.border&&(n["--persona-artifact-inline-border"]=U.border),U.borderRadius&&(n["--persona-artifact-inline-radius"]=U.borderRadius),U.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=dn(t,U.chromeBackground)??U.chromeBackground),U.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=dn(t,U.chromeBorder)??U.chromeBorder),U.titleColor&&(n["--persona-artifact-inline-title-color"]=dn(t,U.titleColor)??U.titleColor),U.mutedColor&&(n["--persona-artifact-inline-muted-color"]=dn(t,U.mutedColor)??U.mutedColor),U.frameHeight&&(n["--persona-artifact-inline-frame-height"]=U.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"]=dn(t,S.background)??S.background));let B=n["--persona-surface"],R=n["--persona-container"],I=n["--persona-palette-colors-gray-100"]??"#f3f4f6",Z=n["--persona-palette-colors-gray-200"]??"#e5e7eb",V=n["--persona-palette-colors-gray-300"]??"#d1d5db",ce=!R||R===B,ie=lM(B??n["--persona-background"]),me=ce&&ie!==void 0&&ie<cM,Te=me?"rgba(255, 255, 255, 0.08)":I,Le=me?"rgba(255, 255, 255, 0.12)":Z,Ce=me?"rgba(255, 255, 255, 0.16)":V,Ze=ce?Te:R,we=ce?Le:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Ze,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??we,ce&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??Ce),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Ze,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Ze,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Ze,n}var dM={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"}}},pM={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)"}}}},Zb=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Uu=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",uM=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Uu()},ev=t=>uM(t),gM=t=>mi(t),mM=t=>{let e=ui(pM,t??{})??{};return mi({...e,palette:{...e.palette,colors:{...dM.colors,...e.palette?.colors}}},{validate:!1})},fi=t=>{let e=ev(t),n=Zb(t?.theme),o=Zb(t?.darkTheme);return e==="dark"?mM(ui(n??{},o??{})):gM(n)},fM=t=>Jb(t),Ha=(t,e)=>{let n=fi(e),o=fM(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",ev(e))},Gc=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Uu())});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(Uu());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 wC,Check as SC,Copy as xC}from"lucide";var Rr=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Qc="24px",$u=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",Ra=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},tv=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var nv=null;var qu=()=>{if(nv!==null)return nv;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},hM="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Xc=(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 Xc("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Xc("unsupported",t),null):(n==="space"&&(o.key=" "),o)},yM=t=>hM.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),ov=(t,e)=>{let n=Yc(t);if(!n)return"";let o=qu(),s=yM(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("+")},Jc=t=>ov(t,!1),Wa=t=>ov(t,!0),bM=(t,e)=>e.key?.toLowerCase()===t.key&&(qu()?e.metaKey:e.ctrlKey)===t.mod&&!(qu()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,vM=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},rv=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(bM(c.parsed,i)&&c.when?.()!==!1&&o(c,i)&&!(!c.allowInInput&&vM(l))){i.preventDefault();try{c.run(i)}catch(p){Xc(`${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?(Xc(`${p.id} already owns`,i.combo),()=>{}):(e.set(c,{...i,parsed:l}),i.element?.setAttribute("aria-keyshortcuts",Wa(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 CM}from"idiomorph";var Zc=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;CM.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 sv=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var zu={index:-1,draft:""};function iv(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 av(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 lv(){return new Map}function cv(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function dv(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function pv(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:X0,load:wM}=Tt({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var uv=wM;function ju(t,e=sn){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 Ba=0,Wr=null;function Vu(t=document){if(Ba++,Ba===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Wr={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,Ba=Math.max(0,Ba-1),Ba===0&&Wr)){let n=t.body,o=t.defaultView??window;n.style.overflow=Wr.originalOverflow,n.style.position=Wr.originalPosition,n.style.top=Wr.originalTop,n.style.width=Wr.originalWidth,o.scrollTo(0,Wr.scrollY),Wr=null}}}var _a={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=t=>(t?.launcher?.mountMode??"floating")==="docked",Oa=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Xn=t=>{let e=t?.launcher?.dock;return{side:e?.side??_a.side,width:e?.width??_a.width,animate:e?.animate??_a.animate,reveal:e?.reveal??_a.reveal,maxHeight:e?.maxHeight??_a.maxHeight}};import{ArrowRight as SM}from"lucide";var Ku=t=>t==="followUp"?"follow-up":t,Gu=(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"}},xM=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'}},gv=new WeakSet,AM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,MM=t=>{AM()||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"})})},Qu=t=>{var K,A,L;let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:p,chipsConfig:g,session:u,getTextarea:f,eventTarget:v,submitPrompt:h}=t,x=o==="followUp",E=e.behavior,M=()=>{if(u.isStreaming())return;let w={suggestion:{...e},surface:o,source:s,behavior:E},_=v.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:w,bubbles:!0,composed:!0,cancelable:!0}));if(x&&v.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!_)return;for(let le of p)if(le.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let G=f();if(E==="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="",u.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=E,i==="chip"&&(g?.fontFamily&&(w.style.fontFamily=xM(g.fontFamily)),g?.fontWeight&&(w.style.fontWeight=g.fontWeight),g?.paddingX&&(w.style.paddingLeft=g.paddingX,w.style.paddingRight=g.paddingX),g?.paddingY&&(w.style.paddingTop=g.paddingY,w.style.paddingBottom=g.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(X("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&_.appendChild(X("span",{className:"persona-suggestion__description",text:e.description})),w.appendChild(_),i!=="chip"){let G=Zt(SM,16,"currentColor",1.8);G&&(G.classList.add("persona-suggestion__arrow"),w.appendChild(G))}return w.addEventListener("click",M),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:M}),P))break;return P??(P=F()),(K=P.dataset).suggestionId||(K.suggestionId=e.id),(A=P.dataset).behavior||(A.behavior=E),(L=P.dataset).emphasis||(L.emphasis=e.emphasis),P instanceof HTMLButtonElement||P.setAttribute("aria-disabled",l?"true":"false"),P},Da=t=>{let e=[],n=[],o=null,s=null,i=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},l=()=>{if(s=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){i();return}let u=Math.max(0,t.scrollWidth-t.clientWidth);if(u<=1){i();return}let f=getComputedStyle(t).direction==="rtl",v=Math.min(u,Math.max(0,Math.abs(t.scrollLeft))),h=4,x=v<=h,E=v>=u-h,M=f?!E:!x,F=f?!x:!E;t.toggleAttribute("data-scroll-left",M),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:(u,f,v,h,x,E)=>{t.replaceChildren(),e.length=0,n.length=0;let M=E?.source??"config",F=E?.surface??(M==="config"?"starter":"followUp"),P=F==="followUp",K=E?.variant??"chip",A=E?.behavior??"send",L=E?.overflow??"wrap",w=E?.config??{},_=E?.plugins??[],G=typeof E?.maxItems=="number"?Math.max(0,Math.floor(E.maxItems)):void 0,le=P?"followUps":"starters";!gv.has(w)&&w.debug===!0&&K!=="chip"&&w.suggestions?.[le]?.overflow!==void 0&&(gv.add(w),console.info(`[persona] suggestions.${le}.overflow applies to the "chip" variant only; the "${K}" variant manages its own stacking.`));let ee=V=>V.map(Gu).filter(ce=>ce!==null).map(ce=>({...ce,behavior:ce.behavior??A})),S=ee(u??[]);_.forEach(V=>{V.transformSuggestions&&(S=ee(V.transformSuggestions({suggestions:S.map(ce=>({...ce})),surface:F,source:M,config:w})))});let B=G===void 0?S:S.slice(0,G);if(!B.length){t.hidden=!0,o=null,i();return}if(!P&&(h??f.getMessages()).some(ce=>ce.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=Ku(F),t.dataset.variant=K,t.dataset.overflow=L;let R=document.createDocumentFragment(),I=f.isStreaming();B.forEach((V,ce)=>{let ie=Qu({item:V,index:ce,surface:F,source:M,variant:K,streaming:I,config:w,plugins:_,chipsConfig:x,session:f,getTextarea:()=>v,eventTarget:t,submitPrompt:E?.submitPrompt});R.appendChild(ie),n.push(ie),[...ie instanceof HTMLButtonElement?[ie]:[],...Array.from(ie.querySelectorAll("button"))].forEach(Te=>{e.includes(Te)||(Te.disabled=I,e.push(Te))})}),t.appendChild(R),l(),c();let Z=JSON.stringify({normalized:B,surface:F,variant:K,source:M});Z!==o&&(o=Z,MM(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:B.map(V=>({...V})),surface:F,source:M,variant:K},bubbles:!0,composed:!0})),P&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:B.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var _n={"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 EM="persona-header-control",TM="persona-header-control--glyph",kM="persona-header-control--sparse",PM=20,IM={x:[1.4,1.05]},mv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",LM="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ed=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=IM[e]??[1,1.5],c=!o;t.classList.toggle(TM,c),t.classList.toggle(kM,c&&i!==1);let p=parseFloat(o??"")||PM,g=he(e,`${Math.round(p*i)}px`,"currentColor",l);g?(g.style.display="block",c||(g.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((l/1.5).toFixed(4))})`),t.replaceChildren(g)):s&&(t.textContent=s)},vs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=mv,size:c,iconSize:p,color:g,backgroundColor:u,borderWidth:f,borderColor:v,borderRadius:h,paddingX:x,paddingY:E,hidden:M,extraClassName:F,attrs:P}=t,K=k("div",l),A=!!(f||v),L=X("button",{className:Wn(EM,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"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:M?"none":void 0,color:g||pn.actionIconColor,backgroundColor:u,border:A?`${f||"0px"} solid ${v||"transparent"}`:void 0,borderRadius:h,paddingLeft:x,paddingRight:x,paddingTop:E,paddingBottom:E}});return s?ed(L,s,{iconSize:p,iconText:i}):i&&(L.textContent=i),K.appendChild(L),Xt({anchor:L,trigger:K,text:()=>L.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:L,wrapper:K}},hi=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=mv,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",p=l.closeButtonShowTooltip??!0,{button:g,wrapper:u}=vs({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:g,wrapper:u}},yi=(t,e={})=>{let{wrapperClassName:n=LM,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",p=l.showTooltip??!0,{button:g,wrapper:u}=vs({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:g,wrapper:u}};var pn={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)"},Xu={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)"},HM={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)"},Cs=t=>{let{config:e,showClose:n=!0}=t,o=X("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:pn.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,g=X("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?g.replaceChildren(w):g.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,g.replaceChildren(L)}else g.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let u=k("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=X("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:pn.titleColor,...Xu}}),v=X("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:pn.subtitleColor,...HM}});u.append(f,v),c?o.append(u):o.append(g,u);let h=s.clearChat??{},x=h.enabled??!0,E=h.placement??"inline",M=null,F=null;if(x){let w=yi(e,{wrapperClassName:E==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=w.button,F=w.wrapper,E==="top-right"&&(F.style.right="48px"),E==="inline"&&o.appendChild(F)}let P=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&E==="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:A}=hi(e,{showClose:n,wrapperClassName:P});return l!=="top-right"&&o.appendChild(A),{header:o,iconHolder:g,headerTitle:f,headerSubtitle:v,closeButton:K,closeButtonWrapper:A,clearChatButton:M,clearChatButtonWrapper:F}},Na=(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 RM=t=>{let e=Cs({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 WM(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=vs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Jc(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=Wa(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=Yh({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 BM=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=pn.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,g,u;if(p){let A=Zh({label:l.title??"Chat Assistant",menuItems:p.menuItems,onSelect:L=>{let w=G=>{G===!1&&A.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:""});g=A.element,g.style.color=pn.titleColor,u=g.querySelector(".persona-combo-btn-label")??g}else{if(g=k("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=k("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=pn.titleColor,Object.assign(u.style,Xu),u.textContent=l.title??"Chat Assistant",g.appendChild(u),s?.onTitleClick){g.style.cursor="pointer",g.setAttribute("role","button"),g.setAttribute("tabindex","0");let L=s.onTitleClick;g.addEventListener("click",w=>{w.target.closest("button")||L()}),g.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),L())})}let A=s?.titleRowHover;A&&(g.style.borderRadius=A.borderRadius??"10px",g.style.padding=A.padding??"6px 4px 6px 12px",g.style.margin="-6px 0 -6px -12px",g.style.border="1px solid transparent",g.style.transition="background-color 0.15s ease, border-color 0.15s ease",g.style.width="fit-content",g.style.flex="none",g.addEventListener("mouseenter",()=>{g.style.backgroundColor=A.background??"",g.style.borderColor=A.border??""}),g.addEventListener("mouseleave",()=>{g.style.backgroundColor="",g.style.borderColor="transparent"}))}c.appendChild(g);let f="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:v,wrapper:h}=hi(e,{showClose:n,wrapperClassName:f});o&&v.addEventListener("click",o);let x=k("div","persona-flex persona-items-center persona-gap-1");p||WM(x,s?.trailingActions,s?.onAction??i);let E=l.clearChat??{},M=null,F=null;if(E.enabled??!0){let A=E.placement??"inline",L=yi(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":f});M=L.button,F=L.wrapper,A==="top-right"?F.style.right="48px":x.appendChild(F)}x.appendChild(h),c.appendChild(x);let P=k("div");P.style.display="none";let K=k("span");return K.style.display="none",{header:c,iconHolder:P,headerTitle:u,headerSubtitle:K,closeButton:v,closeButtonWrapper:h,clearChatButton:M,clearChatButtonWrapper:F}},fv={default:RM,minimal:BM},_M=t=>fv[t]??fv.default,td=(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"),g=k("span"),u=k("button");u.style.display="none";let f=k("div");return f.style.display="none",{header:l,iconHolder:c,headerTitle:p,headerSubtitle:g,closeButton:u,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=_M(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 Fa=t=>{let{config:e}=t,n=X("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=qc(),s=X("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}=Nc(e);l();let c=Fc(e),p=gi(e),g=Uc(e),u=$c(e),f=X("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(f),g&&(g.previewsContainer.style.gap="8px",f.append(g.previewsContainer),s.append(g.input)),s.append(i);let v=X("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=X("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),x=X("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return g&&h.append(g.wrapper),p&&x.append(p.wrapper),x.append(c.wrapper),v.append(h,x),s.append(v),s.addEventListener("click",E=>{E.target!==c.button&&E.target!==c.wrapper&&E.target!==p?.button&&E.target!==p?.wrapper&&E.target!==g?.button&&E.target!==g?.wrapper&&i.focus()}),n.append(o,s,u),{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:u,attachmentButton:g?.button??null,attachmentButtonWrapper:g?.wrapper??null,attachmentInput:g?.input??null,attachmentPreviewsContainer:g?.previewsContainer??null,actionsRow:v,leftActions:h,rightActions:x,setSendButtonMode:c.setMode}};import{ChevronUp as OM,MessageSquare as DM}from"lucide";var hv=()=>{let t=X("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=Zt(DM,16,"currentColor",1.5);n&&e.appendChild(n);let o=k("span","persona-pill-peek__text"),s=k("span","persona-pill-peek__caret"),i=Zt(OM,16,"currentColor",1.5);return i&&s.appendChild(i),t.append(e,o,s),{root:t,textNode:o}},nd=t=>{let{config:e}=t,n=X("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=qc(),s=$c(e);s.style.display="none";let{textarea:i,attachAutoResize:l}=Nc(e,{defaultMaxLines:5});l();let c=Fc(e),p=gi(e),g=Uc(e);g&&g.previewsContainer.classList.add("persona-pill-composer__previews");let u=X("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=X("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});g&&f.append(g.wrapper);let v=X("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),u.addEventListener("click",E=>{E.target!==c.button&&E.target!==c.wrapper&&E.target!==p?.button&&E.target!==p?.wrapper&&E.target!==g?.button&&E.target!==g?.wrapper&&i.focus()}),g&&u.append(g.input),u.append(f,i,v);let h=X("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),g&&h.append(g.previewsContainer),n.append(o,u,s);let x=u;return{footer:n,suggestions:o,composerForm:u,header:h,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:s,attachmentButton:g?.button??null,attachmentButtonWrapper:g?.wrapper??null,attachmentInput:g?.input??null,attachmentPreviewsContainer:g?.previewsContainer??null,actionsRow:x,leftActions:f,rightActions:v,setSendButtonMode:c.setMode}};var NM=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}},FM=(t,e)=>{if(!t)return null;let n=NM(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},UM=(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},$M=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Ju=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(":"))},Zu=320,wv=320,qM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),zM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),jM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),VM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),KM=t=>{if(!t||t.length===0)return null;let e=X("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=X("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(X("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},GM=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(La(o.ref,{readonly:!0,render:e}))}return n},yv="\uE000",bv="\uE001",QM=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=v=>`${yv}${s}:${v}${bv}`,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(GM(e,o));return}t.innerHTML=c;let g=new RegExp(`${yv}${s}:(\\d+)${bv}`),u=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),f=[];for(let v=u.nextNode();v;v=u.nextNode())f.push(v);for(let v of f){let h=v;for(let x=g.exec(h.data);x;x=g.exec(h.data)){let E=e[Number(x[1])],M=h.splitText(x.index);M.data=M.data.slice(x[0].length),E?.kind==="mention"&&M.parentNode?.insertBefore(La(E.ref,{readonly:!0,render:o}),M),h=M}}},XM=(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 g=k("img");g.alt=c.alt?.trim()||`Attached image ${p+1}`,g.loading="lazy",g.decoding="async",g.referrerPolicy="no-referrer",g.style.display="block",g.style.width="100%",g.style.maxWidth=`${Zu}px`,g.style.maxHeight=`${wv}px`,g.style.height="auto",g.style.objectFit="contain",g.style.borderRadius="10px",g.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",g.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,g.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),g.remove(),s===0&&l())}),g.addEventListener("load",()=>{u=!0}),$M(c.image)?(g.src=c.image,o.appendChild(g)):(u=!0,s=Math.max(0,s-1),g.remove())}),s===0?(l(),null):o}catch{return n?.(),null}},YM=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(!Ju(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=`${Zu}px`,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","video");let n=0;return t.forEach(o=>{if(!Ju(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=`${Zu}px`,s.style.maxHeight=`${wv}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}},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","files");let n=0;return t.forEach(o=>{if(!Ju(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}},Ua=()=>{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},eE=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Ua};if(e){let s=e(o);if(s!==null)return s}return Ua()},tE=(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},vv=(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},$a=(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},Cv={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"}},nE=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=Cv[n??"bubble"]??Cv.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)`)},od="custom:",oE=t=>`${od}${t}`,Sv=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),rE=(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,g=(e.showEdit??!1)&&o?.canEdit===!0,u=(e.showQuote??!1)&&o?.canQuote!==!1,f=Sv(e,t.role);if(!s&&!i&&!l&&!c&&!p&&!g&&!u&&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",x=e.layout??"pill-inside",E={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],M={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[x],F=k("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${E} ${M} ${v==="hover"?"persona-message-actions-hover":""}`);F.id=`actions-${t.id}`,F.setAttribute("data-actions-for",t.id);let P=(K,A,L)=>{let w=Jh({icon:K,label:A,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")),g&&F.appendChild(P("pencil","Edit message","edit")),u&&F.appendChild(P("quote","Quote message","quote"));for(let K of f)F.appendChild(P(K.iconName??"ellipsis",K.label,oE(K.id)));return F},eg=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",p=l.avatar,g=l.timestamp,u=p?.show??!1,f=g?.show??!1,v=p?.position??"left",h=g?.position??"below",x=$a(t.role,c),E=k("div",x.join(" "));E.id=`bubble-${t.id}`,E.setAttribute("data-message-id",t.id),E.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let M=i?.widgetConfig?.theme?.components?.message;nE(E,t.role,c,t.role==="user"?M?.user:M?.assistant),c==="flat"?(E.style.backgroundColor="transparent",E.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(E.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",E.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(E.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",E.style.color="var(--persona-message-assistant-text, var(--persona-text))");let F=qM(t),P=t.content?.trim()??"",A=F.length>0&&P===pi,L=yc(i?.widgetConfig?.features?.streamAnimation),w=i?.widgetConfig?.features?.streamAnimation?.plugins,_=t.role==="assistant"&&L.type!=="none"?fa(L.type,w):null,G=t.role==="assistant"&&_?.isAnimating?.(t)===!0,le=t.role==="assistant"&&_!==null&&(!!t.streaming||G);le&&_?.bubbleClass&&E.classList.add(_.bubbleClass);let ee=document.createElement("div");ee.classList.add("persona-message-content"),t.streaming&&ee.classList.add("persona-content-streaming"),le&&_&&(_.containerClass&&ee.classList.add(_.containerClass),ee.style.setProperty("--persona-stream-step",`${L.speed}ms`),ee.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let S=le?bc(t.content??"",L.buffer,_,t,!!t.streaming):t.content??"",B=()=>{let we=e({text:S,message:t,streaming:!!t.streaming,raw:t.rawContent});return le&&_?.wrap==="char"?ha(we,"char",t.id,{skipTags:_.skipTags}):le&&_?.wrap==="word"?ha(we,"word",t.id,{skipTags:_.skipTags}):we},R=null;if(A?(R=document.createElement("div"),R.innerHTML=B(),R.style.display="none",ee.appendChild(R)):t.contentSegments?.length?QM(ee,t.contentSegments,we=>e({text:we,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):ee.innerHTML=B(),le&&_?.useCaret&&!A&&P){let we=vc(),U=ee.querySelectorAll(".persona-stream-char, .persona-stream-word"),ke=U[U.length-1];if(ke?.parentNode)ke.parentNode.insertBefore(we,ke.nextSibling);else{let $e=ee.lastElementChild;$e?$e.appendChild(we):ee.appendChild(we)}}if(f&&h==="inline"&&t.createdAt){let we=vv(t,g,"span");we.classList.add("persona-timestamp-inline");let U=ee.lastElementChild;U?U.appendChild(we):ee.appendChild(we)}if(F.length>0){let we=XM(F,!A&&!!P,()=>{A&&R&&(R.style.display="")});we?E.appendChild(we):A&&R&&(R.style.display="")}let I=zM(t);if(I.length>0){let we=YM(I);we&&E.appendChild(we)}let Z=jM(t);if(Z.length>0){let we=JM(Z);we&&E.appendChild(we)}let V=VM(t);if(V.length>0){let we=ZM(V);we&&E.appendChild(we)}let ce=t.contentSegments?.length?null:KM(t.contextMentions);if(ce&&E.appendChild(ce),E.appendChild(ee),f&&h==="below"&&t.createdAt){let we=vv(t,g);we.classList.add("persona-mt-1"),E.appendChild(we)}let ie=t.role==="assistant"?FM(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let we=!!(S&&S.trim()),U=L.placeholder==="skeleton",ke=U&&L.buffer==="line"&&we;if(we)ke&&E.appendChild(ya());else if(U)E.appendChild(ya());else{let $e=eE("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);$e&&E.appendChild($e)}}ie&&t.stopReason&&!t.streaming&&(P||(ee.style.display="none"),E.appendChild(UM(t.stopReason,ie)));let me=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,Te=i?.actionEligibility,Le=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Te?.canEdit===!0||o?.showQuote===!0&&Te?.canQuote===!0||Sv(o,"user").length>0);if((me||Le)&&o){let we=rE(t,Le?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,Te);E.appendChild(we)}if(!u||t.role==="system")return E;let Ce=k("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),Ze=tE(p,t.role);return v==="right"||v==="left"&&t.role==="user"?Ce.append(E,Ze):Ce.append(Ze,E),Ce};var sE=40,iE=(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,sE);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(X("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(X("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},xv=(t,e,n={})=>{let o=X("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=X("div",{className:"persona-welcome-head-text"},s,i),p=X("div",{className:"persona-welcome-title-row"},o,c);return{host:X("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}},bi=(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)},sd=(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==="",iE(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")},aE="data-persona-welcome-plugin",Av="data-persona-welcome-overlay",rd="persona-welcome-overlay-active",tg=new WeakMap,ng=(t,e,n)=>{n.setAttribute(aE,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(Av,""),t.classList.contains(rd)||(tg.set(t,t.scrollTop),t.classList.add(rd),t.scrollTop=0)},og=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(Av),t.classList.contains(rd)&&(t.classList.remove(rd),t.scrollTop=tg.get(t)??t.scrollTop,tg.delete(t))},Mv=()=>{let t=X("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},id=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",s=X("div",{className:$a("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(X("div",{className:"persona-flex"},s)),t.hidden=!1},Ev=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Tv=(t,e)=>{if(Ev()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,s=0,i=0,l=0;if(o){let x=getComputedStyle(o);s=parseFloat(x.rowGap)||0;let E=t.previousElementSibling,M=t.nextElementSibling,P=o.getBoundingClientRect().top+(parseFloat(x.borderTopWidth)||0)+(parseFloat(x.paddingTop)||0)-o.scrollTop;i=Math.max(0,E?n.top-E.getBoundingClientRect().bottom-s:n.top-P),l=Math.max(0,M?M.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let p=getComputedStyle(t),g=parseFloat(p.paddingTop)||0,u=parseFloat(p.paddingBottom)||0,f=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${g}px`,paddingBottom:`${u}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},kv=(t,e,n)=>{if(e<=1||Ev()||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 lE="Hello \u{1F44B}",cE="I can answer questions and help you get things done here.",Pv=new WeakSet,un=(t,e)=>!!t&&t[e]!==void 0,dE=(t,e)=>{!t||t.debug!==!0||!e.length||Pv.has(t)||(Pv.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},tr=t=>{let e=t?.welcome,n=t?.copy,o=un(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",s=o==="hero"?"on-first-message":un(e,"dismiss")?e.dismiss:"never",i=[];un(e,"title")&&un(n,"welcomeTitle")&&i.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),un(e,"subtitle")&&un(n,"welcomeSubtitle")&&i.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),un(e,"variant")&&un(n,"showWelcomeCard")&&i.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&un(e,"message")&&i.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&un(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=Ra(e?.anchorComposerTop)!==null;return un(e,"anchorComposerTop")&&!c&&i.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),l!=="center"&&(un(e,"anchorComposerTop")||un(e,"composerGap"))&&i.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),dE(t,i),{title:un(e,"title")?e.title:n?.welcomeTitle??lE,kicker:e?.kicker??"",subtitle:un(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??cE,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()||Qc}},Iv=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",vi=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var Lv="16px",sg="10px",ig="14px",Hv=t=>{let e=t?.launcher?.enabled??!0,n=Lt(t);if(Oa(t)){let u=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=u.expandedSize??"anchored",f.style.zIndex=String(t?.launcher?.zIndex??sn);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=u.expandedSize??"anchored",h.style.zIndex=String(t?.launcher?.zIndex??sn),{wrapper:f,panel:v,pillRoot:h}}if(n){let u=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 u.appendChild(f),{wrapper:u,panel:f}}if(!e){let u=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 u.style.width=v,f.style.width="100%",u.appendChild(f),{wrapper:u,panel:f}}let s=t?.launcher??{},i=s.position&&_n[s.position]?_n[s.position]:_n["bottom-right"],l=k("div",`persona-widget-wrapper persona-fixed ${i} persona-transition`);l.style.zIndex=String(t?.launcher?.zIndex??sn);let c=k("div","persona-widget-panel persona-relative persona-min-h-[320px]"),g=t?.launcher?.width??t?.launcherWidth??er;return c.style.width=g,c.style.maxWidth=g,l.appendChild(c),{wrapper:l,panel:c}},ag=t=>{let e=X("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Ku(t)}});return e.hidden=!0,e},Rv=(t,e)=>{let n=ag("starter"),o=xv(t,n,{flatShadow:Lt(t)}),s=tr(t);sd(o,s),bi(e,o.host,vi(s,t?.initialMessages));let i=Mv();return id(i,s.message,t),{welcome:o,greetingHost:i}},pE=(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}=hi(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:Lv,iconSize:sg});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 _=yi(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Lv,iconSize:ig});l=_.button,c=_.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let p=X("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),g=X("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"}});g.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:f}=Rv(t,g),{host:v,title:h,subtitle:x}=u,E=u.starterSuggestions,M=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),F=ag("followUp"),P=Rr(t,!0);P&&(M.style.maxWidth=P,M.style.marginLeft="auto",M.style.marginRight="auto",M.style.width="100%"),g.append(v,f,M,F);let K=X("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),A=nd({config:t}),{root:L,textNode:w}=hv();return n.append(p,s,g,K),c&&n.appendChild(c),{container:n,body:g,messagesWrapper:M,starterSuggestions:E,transcriptSuggestions:F,composerOverlay:K,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:v,welcomeIconHolder:u.iconHolder,greetingHost:f,introKicker:u.kicker,introTitle:h,introSubtitle:x,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:k("span"),headerTitle:k("span"),headerSubtitle:k("span"),header:p,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:L,peekTextNode:w}},Wv=(t,e=!0)=>{if(Oa(t))return pE(t,e);let n=X("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?td(t,o,{showClose:e}):Cs({config:t,showClose:e}),l=X("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}=Rv(t,l),{host:g,title:u,subtitle:f}=c,v=c.starterSuggestions,h=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),x=ag("followUp"),E=Rr(t,!1);E&&(h.style.maxWidth=E,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),l.append(g,p,h,x);let M=Fa({config:t}),F=t?.layout?.showFooter!==!1;s?Na(n,i,t):(i.header.style.display="none",Na(n,i,t)),n.append(l);let P=X("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||(M.footer.style.display="none"),n.append(M.footer),n.append(P),{container:n,body:l,messagesWrapper:h,starterSuggestions:v,transcriptSuggestions:x,composerOverlay:P,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,welcomeHost:g,welcomeIconHolder:c.iconHolder,greetingHost:p,introKicker:c.kicker,introTitle:u,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:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode}};var lg=(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 g=[];i&&g.push(ko(i)),g.push(...s.contentParts),g.push(...e.contentParts),e.contentParts=g}else if(p){let g=[];l&&g.push(ko(l)),g.push(...s.contentParts),e.contentParts=g}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=wc(),l=ai();this.activeAssistantMessageId=null;let c=n?.contentParts&&Ec(n.contentParts)?ui:"",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 g=new AbortController;if(this.abortController=g,n?.mentions){let m=this.messages.find(v=>v.id===i)??p;if(await this.applyMentionBundle(m,o,n.mentions.finalize),g.signal.aborted||this.abortController!==g)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(h=>h.id===i)??p,v=Ky({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});v.contentParts&&(m.contentParts=v.contentParts),v.llmContent!==void 0&&(m.llmContent=v.llmContent),(v.contentParts||v.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,g,l,i,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let v=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!v){let h=Su(m,this.config.errorMessage);if(h){let x={id:l,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(x)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(e,n){let o=Gy(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 g=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}},u=i?this.toComposerOptionsPayload(i.options):s.composerOptions,m=i?i.contentSegments:s.contentSegments,v=i?i.options?.quote:void 0,h=i?i.viaVoice:s.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(l??"",{...c?.length?{contentParts:[...c]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...v?{quote:v}:{},...g&&Object.keys(g).length>0?{replayFields:g}:{},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=ai();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;let i=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!i){let l=Su(s,this.config.errorMessage);if(l){let c={id:e,role:"assistant",createdAt:new Date().toISOString(),content:l,sequence:this.nextSequence()};this.appendMessage(c)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,i||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(i){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let s=this.messages.find(i=>i.id===e);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let s=`approval-${e.id}`,i={...e,status:n,resolvedAt:Date.now()},l=this.messages.find(u=>u.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,g=p&&typeof p=="object"?p.onDecision:void 0;try{let u;if(g?u=await g({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let v=await u.json().catch(()=>null);throw new Error(v?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}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(u=>u.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 u=e.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let v=typeof m[0]?.question=="string"?m[0].question:"";v&&(l={[v]:n})}}this.markAskUserQuestionResolved(e,l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=e.toolCall.id,p=e.toolCall?.args,g=Array.isArray(p?.questions)?p.questions:[];if(g.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,v])=>`${m}: ${Array.isArray(v)?v.join(", "):v}`).join(" | ");this.appendMessage({id:`ask-user-answer-${c}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=l??{};g.forEach((m,v)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let x=u[h],E=Array.isArray(x)?x.join(", "):typeof x=="string"?x:"";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:E||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(s,{[i]:n},{after:this.resumable?.executionId===s?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}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!==Pr?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,s=Date.now(),i){this.messages.some(l=>l.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...i},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:s,duration:void 0,durationMs:Math.max(0,s-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let i=async p=>{let g=p.toolCall?.name,u=p.toolCall?.id;if(!g||!u)return null;let m=`${e}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(m),o.push(m);let v=this.markWebMcpToolRunning(p),h=p.agentMetadata?.webMcpToolCallId??g;if(g===Pr)return{dedupeKey:m,resumeKey:h,output:Ey(),toolMessage:p,startedAt:v,completedAt:Date.now()};let x=this.client.executeWebMcpToolCall(g,p.toolCall?.args,s.signal),E;if(!x)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await x}catch(M){let F=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));return F||this.callbacks.onError?.(M instanceof Error?M:new Error(String(M))),this.markWebMcpToolComplete(p,xu(F?"Aborted by cancel()":pA(M)),v),this.webMcpInflightKeys.delete(m),null}return s.signal.aborted?(this.markWebMcpToolComplete(p,xu("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:E,toolMessage:p,startedAt:v,completedAt:Date.now()}},l;if(this.config.webmcp?.execution==="sequential"){l=[];for(let p of n)l.push(await i(p))}else l=await Promise.all(n.map(i));let c=[];try{if(c=l.filter(u=>u!==null),c.length===0)return;let p={};for(let u of c)p[u.resumeKey]=u.output;let g=await this.client.resumeFlow(e,p,{signal:s.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!g.ok){let u=await g.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${g.status}`)}for(let u of c)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===Pr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let u of c)this.markWebMcpToolComplete(u.toolMessage,xu("Aborted by cancel()"),u.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);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,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!i.ok){let l=await i.json().catch(()=>null);throw new Error(l?.error??`Resume failed: ${i.status}`)}s?.onHttpOk?.(),i.body?await this.connectStream(i.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=Er(this.config.features?.artifacts,e),s=Ca(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=Er(this.config.features?.artifacts,n),i=Ca(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=Zy().then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,s)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>Su(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=ai(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let s=Cu(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return bu(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=Cu(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,i)=>{if(i!==o)return s;let l={...s,...n};if(s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(l.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(l.agentMetadata={...l.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let u=s.approval,m=n.approval;l.approval={...u,...m,executionId:m.executionId||u.executionId,toolName:m.toolName||u.toolName,description:m.description||u.description,toolType:m.toolType??u.toolType,reason:m.reason??u.reason,parameters:m.parameters??u.parameters}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,g=n.toolCall?.id;if(c&&eb(c)&&p&&g&&n.agentMetadata?.awaitingLocalTool===!0){let u=`${p}:${g}`,m=this.webMcpInflightKeys.has(u),v=this.webMcpResolvedKeys.has(u),h=s.toolCall?.name,x=s.agentMetadata?.executionId===p&&s.toolCall?.id===g&&h!==void 0&&eb(h)&&s.toolCall?.status==="complete";(m||v||x)&&(l.agentMetadata={...l.agentMetadata??{},awaitingLocalTool:!1},l.toolCall=s.toolCall,l.streaming=s.streaming)}return l}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),i=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=n.sequence??0,c=o.sequence??0;return l!==c?l-c:n.id.localeCompare(o.id)})}};import{File as uA,FileCode as gA,FileSpreadsheet as fA,FileText as Au,X as mA}from"lucide";var hA={add:t=>Ry(t)},yA=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Hc={allowedTypes:er,maxFileSize:10*1024*1024,maxFiles:4};function bA(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vA(t){return t==="application/pdf"?Au:t.startsWith("text/")?Au:t.includes("word")?Au:t.includes("excel")||t.includes("spreadsheet")?fA:t==="application/json"?gA:uA}var ka=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Hc.allowedTypes,maxFileSize:e.maxFileSize??Hc.maxFileSize,maxFiles:e.maxFiles??Hc.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:hA}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:Hc.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=Wy(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:bA(),file:o,previewUrl:Tc(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=yA(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=Tc(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 u=k("img");u.src=e.previewUrl,u.alt=e.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=k("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=vA(e.file.type),v=tn(m,20,"var(--persona-muted, #6b7280)",1.5);v&&u.appendChild(v);let h=k("span");h.textContent=By(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",u.appendChild(h),o.appendChild(u)}let s=X("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=X("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=me("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);c?l.appendChild(c):l.textContent="\u21BB",l.addEventListener("click",u=>{u.preventDefault(),u.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 g=tn(mA,10,"var(--persona-text-inverse, #ffffff)",2);g?p.appendChild(g):(p.textContent="\xD7",p.style.color="var(--persona-text-inverse, #ffffff)",p.style.fontSize="14px",p.style.lineHeight="1"),p.addEventListener("click",u=>{u.preventDefault(),u.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 tb=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),CA=(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 nb(){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 u=i();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:u,inputDisabled:t.inputDisabled,sendDisabled:u!=="idle"||t.sendDisabled||t.inputDisabled})},c=()=>(n||(n=l()),n),p=()=>{if(o=!1,s||e.size===0)return;let u=c();for(let m of[...e])try{m(u)}catch(v){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",v)}},g=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(p))};return{getState:c,subscribe:u=>(e.add(u),()=>e.delete(u)),setText:u=>{t.text!==u&&(t.text=u,g())},setAttachments:u=>{CA(t.attachments,u)||(t.attachments=[...u],g())},setMentionRefs:u=>{tb(t.mentionRefs,u)||(t.mentionRefs=[...u],g())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,g())},setActiveModeIds:u=>{tb(t.activeModeIds,u)||(t.activeModeIds=[...u],g())},setQuote:u=>{let m=t.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(t.quote=u?{...u}:void 0,g())},setPendingSubmission:u=>{t.pendingSubmission!==u&&(t.pendingSubmission=u,g())},setPreparing:u=>{t.preparing!==u&&(t.preparing=u,g())},setStreaming:u=>{t.streaming!==u&&(t.streaming=u,g())},setInputDisabled:u=>{t.inputDisabled!==u&&(t.inputDisabled=u,g())},setSendDisabled:u=>{t.sendDisabled!==u&&(t.sendDisabled=u,g())},flush:()=>{o&&p()},destroy:()=>{s=!0,o=!1,e.clear()}}}var xn=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},ob=(t,e)=>{let n=k("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function rb(t,e={}){let n=xn(t,"[data-persona-composer-form]"),o=xn(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:xn(t,"[data-persona-composer-header]"),body:xn(t,"[data-persona-composer-body]"),actionsStart:xn(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:xn(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:xn(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:xn(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:xn(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=ob("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=(M,F,P,K,A)=>{if(F)return F;i.add(M);let H=ob(P,K);return A.appendChild(H),H},g=p("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=p("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=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=[],x=(M,F)=>M.target===F.target&&M.type===F.type&&M.handler===F.handler,E=xn(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:l,body:c,actionsStart:g,actionsEnd:u,suggestions:m,status:v,attachmentInput:E,attachmentPreviews:xn(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:xn(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:xn(t,"[data-persona-composer-submit]")??void 0,micButton:xn(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(M,F,P,K)=>{M.addEventListener(F,P,K),h.push({target:M,type:F,handler:P,options:K})},removeListener:(M,F,P,K)=>{M.removeEventListener(F,P,K),h=h.filter(A=>!x(A,{target:M,type:F,handler:P}))},destroy:()=>{for(let M of h)M.target.removeEventListener(M.type,M.handler,M.options);h=[]}}}var wA=8,SA=8,Mu=10,sb=200,ib=300,ab=0,Wc=t=>Math.max(0,t);function lb(t){t.delayMs!==void 0&&(sb=Wc(t.delayMs)),t.skipDelayMs!==void 0&&(ib=Wc(t.skipDelayMs))}var xA=()=>Date.now()<ab,AA=t=>{ab=t>0?Date.now()+t:0},Rc=new WeakMap,Tu="data-persona-tooltip-suppressed",MA=t=>typeof t.closest=="function"&&t.closest(`[${Tu}]`)!==null;function cb(t){Rc.get(t)?.hide()}var db=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,EA=t=>{let e=t.getRootNode?.();return db(e)?e:t.ownerDocument.body},Eu=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),TA=[...["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){Rc.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:s,enabled:i=!0,gap:l=wA,viewportPadding:c=SA}=t,p=()=>e.ownerDocument,g=()=>p().defaultView??window,u=null,m=null,v=null,h=null,x,E=!1,M=!1,F=!1,P=()=>(typeof o=="function"?o():o).trim(),K=()=>(typeof s=="function"?s():s??"").trim(),A=()=>Wc(t.delayMs??sb),H=()=>Wc(t.skipDelayMs??ib),w=()=>{x!==void 0&&(g().clearTimeout(x),x=void 0)},_=()=>{w();let fe=u!==null;h?.(),h=null,u?.remove(),u=null,m=null,v=null,fe&&AA(H())},G=()=>{if(!u)return;let fe=p(),Me=g(),Le=e.getBoundingClientRect(),be=u.getBoundingClientRect(),Je=fe.documentElement.clientWidth||Me.innerWidth,ve=fe.documentElement.clientHeight||Me.innerHeight,U=Je-c-be.width,Ee=Le.left+Le.width/2-be.width/2,Fe=Eu(Ee,c,U),yt=Le.top-c,Re=ve-c-Le.bottom,Pe=be.height+l,ye=yt>=Pe||yt>=Re?"top":"bottom",co=ye==="top"?Le.top-l-be.height:Le.bottom+l,po=ve-c-be.height,xs=Eu(co,c,po),It=Le.left+Le.width/2,uo=Math.max(Mu,be.width-Mu),Dn=Eu(It-Fe,Mu,uo);u.dataset.placement=ye,u.style.left=`${Fe}px`,u.style.top=`${xs}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${Dn}px`)},le=()=>{if(F||!i||u||!e.isConnected||MA(e))return;let fe=P(),Me=EA(e);if(!fe||!Me)return;let Le=p(),be=g();u=Le.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(mc);let Je=be.getComputedStyle?.(e);if(Je){for(let Pe of TA){let ye=Je.getPropertyValue(Pe).trim();ye&&u.style.setProperty(Pe,ye)}Je.fontFamily&&(u.style.fontFamily=Je.fontFamily)}m=Le.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=fe,u.appendChild(m);let ve=K();ve&&(v=Le.createElement("span"),v.className="persona-control-tooltip__hint",v.textContent=ve,u.appendChild(v));let U=Le.createElement("span");U.className="persona-control-tooltip__arrow",u.appendChild(U),Me.appendChild(u),G(),u.dataset.state="open";let Ee=()=>{if(!e.isConnected){_();return}m&&(m.textContent=P()),v&&(v.textContent=K()),G()};be.addEventListener("scroll",Ee,!0),be.addEventListener("resize",Ee);let Fe=e.getRootNode(),yt=db(Fe)?Fe:Le.documentElement,Re=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||_()});Re?.observe(yt,{childList:!0,subtree:!0}),h=()=>{be.removeEventListener("scroll",Ee,!0),be.removeEventListener("resize",Ee),Re?.disconnect()}},ee=fe=>{if(!(F||u)){if(w(),fe||A()<=0||xA()){le();return}x=g().setTimeout(()=>{x=void 0,le()},A())}},S=()=>{E||M?ee(M):_()},B=()=>{let fe=g();(!fe.matchMedia||!fe.matchMedia("(hover: none)").matches)&&(E=!0,S())},R=()=>{E=!1,S()},I=()=>{try{M=e.matches(":focus-visible")}catch{M=!0}S()},Z=()=>{M=!1,S()},V=()=>{E=!1,M=!1,_()},ce=fe=>{fe.key==="Escape"&&V()};n.addEventListener("mouseenter",B),n.addEventListener("mouseleave",R),e.addEventListener("focus",I),e.addEventListener("blur",Z),e.addEventListener("keydown",ce),e.addEventListener("click",V);let ie={get isOpen(){return u!==null},show:le,hide:_,reposition:G,destroy:()=>{F||(F=!0,_(),n.removeEventListener("mouseenter",B),n.removeEventListener("mouseleave",R),e.removeEventListener("focus",I),e.removeEventListener("blur",Z),e.removeEventListener("keydown",ce),e.removeEventListener("click",V),Rc.delete(e))}};return Rc.set(e,ie),ie}var pb=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function gi(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];pb(i)&&pb(s)?n[o]=gi(i,s):n[o]=s}return n}var tr="min(440px, calc(100vw - 24px))",gb="440px",ku="How can I help...",kA={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:tr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:kA,copy:{inputPlaceholder:ku,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ub(t,e){if(!(!t&&!e))return t?e?gi(t,e):t:e}function Bc(t){return t?{...rt,...t,theme:ub(rt.theme,t.theme),darkTheme:ub(rt.darkTheme,t.darkTheme),launcher:{...rt.launcher,...t.launcher,dock:{...rt.launcher?.dock,...t.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...rt.tooltip,...t.tooltip},copy:{...rt.copy,...t.copy},sendButton:{...rt.sendButton,...t.sendButton},statusIndicator:{...rt.statusIndicator,...t.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=rt.features?.artifacts,n=t.features?.artifacts,o=rt.features?.scrollToBottom,s=t.features?.scrollToBottom,i=rt.features?.scrollBehavior,l=t.features?.scrollBehavior,c=rt.features?.streamAnimation,p=t.features?.streamAnimation,g=rt.features?.askUserQuestion,u=t.features?.askUserQuestion,m=rt.features?.history,v=t.features?.history,h=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},x=o===void 0&&s===void 0?void 0:{...o,...s},E=i===void 0&&l===void 0?void 0:{...i,...l},M=c===void 0&&p===void 0?void 0:{...c,...p},F=g===void 0&&u===void 0?void 0:{...g,...u,styles:{...g?.styles,...u?.styles}},P=m===void 0&&v===void 0?void 0:{...m,...v,copy:{...m?.copy,...v?.copy}};return{...rt.features,...t.features,...x!==void 0?{scrollToBottom:x}:{},...E!==void 0?{scrollBehavior:E}:{},...h!==void 0?{artifacts:h}:{},...M!==void 0?{streamAnimation:M}:{},...F!==void 0?{askUserQuestion:F}:{},...P!==void 0?{history:P}:{}}})(),suggestionChips:t.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...rt.layout,...t.layout,header:{...rt.layout?.header,...t.layout?.header},messages:{...rt.layout?.messages,...t.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...t.layout?.slots}},markdown:{...rt.markdown,...t.markdown,options:{...rt.markdown?.options,...t.markdown?.options}},messageActions:{...rt.messageActions,...t.messageActions}}:rt}function Pu(t){let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return 20;let n=e.getComputedStyle(t).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function _c(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function fb(t,e){t.style.maxHeight=`${e*Pu(t)}px`,t.style.overflowY="auto"}function La(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 mb(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function hb(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||!mb(e)}function PA(t){return(t.submitKey??"enter")!=="enter"||mb(t)?"enter":"send"}function Oc(t,e){t.setAttribute("enterkeyhint",PA(e))}function Dc(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(s,i)=>{i===void 0?t.removeAttribute(s):t.setAttribute(s,i)};o("autocapitalize",typeof e?.autocapitalize=="string"?e.autocapitalize:void 0),o("spellcheck",typeof e?.spellcheck=="boolean"?String(e.spellcheck):void 0),o("inputmode",typeof e?.inputmode=="string"&&e.inputmode?e.inputmode:void 0),o("aria-label",typeof e?.ariaLabel=="string"&&e.ariaLabel?e.ariaLabel:void 0)}function Iu(t){return t===!0?{disabled:!0}:!t||typeof t!="object"?{disabled:!1}:{disabled:!0,reason:typeof t.reason=="string"&&t.reason?t.reason:void 0}}var _n="persona-composer-control",lo="persona-composer-control--glyph",Hu=40,dn=24,Nc=(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)}},Fc=(t,e)=>{let n=k("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??ku,n.dir="auto",Oc(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:La(n)}),Dc(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=_c(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 g=parseFloat(c);if(Number.isFinite(g)&&g>0)return g}let p=o*Pu(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}},LA="[data-persona-glyph-stack]",Ru=(t,e,n="send")=>{let o=X("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},Uc=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",g=t?.copy?.stopButtonLabel??"Stop",u=e.showTooltip??!1,m=e.size,v=parseFloat(m??"")||Hu,h=e.backgroundColor,x=e.textColor,E=k("div","persona-send-button-wrapper"),M=X("button",{className:Bn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${_n}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!x&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?x||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":x||void 0,backgroundColor:n&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),F=null,P=null,K=null;if(n){let w=parseFloat(e.iconSize??"")||Math.round(v*.5),_=e.iconStrokeWidth??2,G=x?.trim()||"currentColor";s&&(F=me(s,w,G,_)),P=me(i,w,G,_),F&&P?(K=Ru(F,P),M.appendChild(K)):F?M.appendChild(F):(M.textContent=o,P=null)}else M.textContent=p;M.setAttribute("aria-label",l),E.appendChild(M),Yt({anchor:M,trigger:E,text:()=>M.getAttribute("aria-label")??"",enabled:u});let A="send";return{button:M,wrapper:E,setMode:w=>{if(w===A)return;A=w;let _=w==="stop"?c:l;M.setAttribute("aria-label",_),M.setAttribute("data-persona-send-mode",w),n?(M.querySelector(LA)??K)?.setAttribute("data-mode",w):M.textContent=w==="stop"?g:p},glyphStack:K}},fi=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,g=parseFloat(p??"")||dn,u=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,v=k("div","persona-send-button-wrapper"),h=X("button",{className:Bn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",_n,!p&&lo),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:m||"var(--persona-text, #111827)",backgroundColor:u||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}}),E=me(c,g,m||"currentColor",1.5);E?h.appendChild(E):h.textContent="\u{1F3A4}",v.appendChild(h);let M=e.tooltipText??"Start voice recognition",F=e.showTooltip??!1;return Yt({anchor:h,trigger:v,text:()=>h.getAttribute("aria-label")??M,enabled:F}),{button:h,wrapper:v}},$c=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??er).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=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${_n} ${lo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),c=me(s,dn,"currentColor",1.5);c?l.appendChild(c):l.textContent="\u{1F4CE}",l.addEventListener("click",g=>{g.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}},qc=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},zc=()=>X("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var HA='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',RA=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],Wu="data-persona-menu-focus",WA=new Set(["ArrowDown","ArrowUp","Home","End"]);function yb(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(HA)??t}var BA=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function bb(t){let e=t.label,n=!1,o=k("div","persona-send-button-wrapper"),s=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${_n} ${lo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=X("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 Z=me("plus",dn,"currentColor",1.5);Z?s.appendChild(Z):s.textContent="+"},c=()=>{s.setAttribute("aria-label",e),s.setAttribute("title",e),i.setAttribute("aria-label",e)};c(),l();let p=[],g=-1,u=!1,m=()=>{let Z=i.getRootNode().activeElement;return Z instanceof HTMLElement?Z:null},v=()=>{let I=m();for(let Z of p){let V=!!I&&yb(Z)===I;Z.toggleAttribute(Wu,V&&u)}},h=()=>p.filter(I=>I.isConnected||i.contains(I)).map(yb).filter(I=>!BA(I)),x=(I,Z)=>{I.forEach((V,ce)=>{V.setAttribute("tabindex",ce===Z?"0":"-1")})},E=I=>{let Z=h();if(Z.length===0)return;let V=(I%Z.length+Z.length)%Z.length;g=V,x(Z,V),Z[V].focus(),v()},M=()=>o.ownerDocument??document,F=null,P=null,K=null,A=()=>{F&&(M().removeEventListener("focusin",F,!0),F=null)},H=()=>{P&&(i.removeEventListener("focusin",P),P=null),K&&(i.removeEventListener("pointerdown",K,!0),K=null)},w=null,_=()=>(w||(w=hc({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),A()}})),w),G=()=>w?.isOpen===!0,le=(I=!1)=>{if(G()){w?.close(),s.setAttribute("aria-expanded","false"),A(),H(),g=-1,u=!1;for(let Z of p)Z.removeAttribute(Wu);I&&s.focus()}},ee=(I=0,Z=!1)=>{if(n||G())return;u=Z,Nc(s,i,RA),_().open(),s.setAttribute("aria-expanded","true");let V=h();x(V,-1),E(I<0?V.length-1:I),F=ce=>{let ie=typeof ce.composedPath=="function"?ce.composedPath():[];ie.includes(i)||ie.includes(o)||le()},M().addEventListener("focusin",F,!0),P=()=>v(),i.addEventListener("focusin",P),K=()=>{u=!1},i.addEventListener("pointerdown",K,!0)},S=I=>{I.preventDefault(),I.stopPropagation(),G()?le(!0):ee(0)},B=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),u=!0,G()?E(0):ee(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),u=!0,G()?E(-1):ee(-1,!0))},R=I=>{switch(WA.has(I.key)&&(u=!0),I.key){case"ArrowDown":I.preventDefault(),E(g+1);return;case"ArrowUp":I.preventDefault(),E(g-1);return;case"Home":I.preventDefault(),E(0);return;case"End":I.preventDefault(),E(h().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),le(!0);return;case"Tab":le(!0);return;default:}};return s.addEventListener("click",S),s.addEventListener("keydown",B),i.addEventListener("keydown",R),{trigger:o,triggerButton:s,panel:i,setItems:I=>{for(let V of p)I.includes(V)||V.removeAttribute(Wu);if(p=[...I],!G())return;let Z=h();x(Z,Math.min(g,Z.length-1)),v()},isOpen:G,open:()=>ee(0),close:le,setLabel:I=>{I!==e&&(e=I,c())},applyButtonSize:l,destroy:()=>{n=!0,A(),H(),s.removeEventListener("click",S),s.removeEventListener("keydown",B),i.removeEventListener("keydown",R),w?.destroy(),w=null,o.remove(),i.remove(),p=[]}}}var Io={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},vb="data-persona-composer-action",Bu="data-persona-composer-disable-when-streaming",_A="core:overflow",OA=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function DA(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 _u(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 Cb=(t,e)=>{!t||typeof console>"u"||console.warn(e)},NA=(t,e)=>e.includes(":")?e:`${t}:${e}`;function FA(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let p=o.get(c.id);if(p){Cb(e,`[Persona] composer action "${c.id}" is already contributed by ${wb(p)}; the ${wb(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,g)=>{let u=g?NA(g,c.id):c.id,m=c.order??Io.custom;c.placement==="end"&&m>=Io.send&&(Cb(e,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${Io.send-1}.`),m=Io.send-1),i({id:u,placement:c.placement,presentation:c.presentation??"bar",order:m,sequence:s++,source:p,pluginId:g,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(g){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,g);continue}for(let g of p??[])l(g,"plugin",c.id)}return n.sort((c,p)=>c.order===p.order?c.sequence-p.sequence:c.order-p.order)}var wb=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",Sb=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,UA=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function $A(t,e){if(!t||t==="always")return!0;let n=UA(e);return t==="when-text"?n:!n}var Hr=t=>t.kind==="custom",Ou=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,qA=t=>{let e=Ou(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},zA='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function jA(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(zA)||o.childNodes.forEach(n)};return n(t),e.trim()}var VA=t=>jA(t).length===0;function xb(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(S,B)=>{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",B.tooltipText?R.setAttribute("title",B.tooltipText):R.removeAttribute("title"),R.replaceChildren();let I=k("span","persona-composer-overflow-menu__icon");if(B.iconName){let V=me(B.iconName,16,"currentColor",1.5);V&&I.appendChild(V)}let Z=k("span","persona-composer-overflow-menu__label");Z.textContent=B.shortLabel??B.label,R.append(I,Z)},l=(S,B)=>{let R=S.button;if(!R)return;if(R.setAttribute("aria-label",B.label),B.pressed===void 0?R.removeAttribute("aria-pressed"):R.setAttribute("aria-pressed",B.pressed?"true":"false"),R.toggleAttribute(Bu,B.disableWhenStreaming===!0),S.mode==="menu"){S.tooltip?.destroy(),S.tooltip=void 0,i(S,B);return}R.removeAttribute("role"),R.removeAttribute("tabindex"),R.removeAttribute("title");let I=s(),Z=!!B.shortLabel;if(R.className=Bn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",_n,lo,Z&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),R.style.width=I&&!Z?I:"",R.style.height=I??"",R.style.minWidth=I&&!Z?I:"",R.style.minHeight=I??"",R.style.fontSize=Z?"":"18px",R.style.lineHeight="1",R.style.color=B.iconColor??"",R.style.backgroundColor=B.backgroundColor??"",R.replaceChildren(),B.iconName){let V=me(B.iconName,dn,"currentColor",1.5);V&&R.appendChild(V)}if(Z){let V=k("span","persona-composer-action-button__label");V.textContent=B.shortLabel,R.appendChild(V)}else R.firstChild||(R.textContent=B.label);S.tooltip?.destroy(),S.tooltip=Yt({anchor:R,trigger:S.element,text:()=>B.tooltipText??B.label,enabled:!!B.tooltipText})},c=(S,B)=>{let R=S.action,I=X("button",{attrs:{type:"button"}}),Z=I;if(B==="bar"){let ie=k("div","persona-send-button-wrapper");ie.appendChild(I),Z=ie}Z.setAttribute(vb,S.id);let V={resolved:S,element:Z,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:B},ce=ie=>{if(ie.preventDefault(),ie.stopPropagation(),V.busy||I.disabled)return;let fe=V.resolved.action;V.mode==="menu"&&h?.close(!0);let Me;try{Me=fe.onSelect(t.actionContext,ie)}catch(Le){t.reportError(Le,{actionId:V.resolved.id});return}!Me||typeof Me.then!="function"||(V.busy=!0,I.setAttribute("aria-busy","true"),Me.catch(Le=>{t.reportError(Le,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",ce),V.detach=()=>I.removeEventListener("click",ce),l(V,R),V},p=S=>{let B=S.action,R;try{R=B.render({...t.actionContext,id:S.id,action:B})}catch(I){return t.reportError(I,{actionId:S.id}),null}return R?.element?(R.element.setAttribute(vb,S.id),R.element.toggleAttribute(Bu,B.disableWhenStreaming===!0),{resolved:S,element:R.element,owned:!0,managed:!0,destroy:R.destroy,busy:!1,visible:!0,mode:"bar"}):null},g=(S,B)=>{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?Hr(R)?p(S):c(S,B):null},u=S=>{if(S.detach?.(),S.tooltip?.destroy(),S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0,S.owned){try{S.destroy?.()}catch(B){t.reportError(B,{actionId:S.resolved.id})}S.element.remove()}},m=(S,B)=>{for(let R=0;R<B.length;R++){let I=B[R];if(!I.managed)continue;let Z=null;for(let V=R+1;V<B.length;V++){let ce=B[V];if(!ce.managed&&ce.element.parentElement===S){Z=ce.element;break}}Z?(I.element.parentElement!==S||I.element.nextSibling!==Z)&&S.insertBefore(I.element,Z):S.lastChild!==I.element&&S.appendChild(I.element)}},v=(S,B)=>{if(S.button){S.button.disabled=B;return}if(!S.owned)return;let R=S.element;R.toggleAttribute("data-disabled",B),R.setAttribute("aria-disabled",B?"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=B)},h=null,x=null,E=null,M=0,F=()=>{let S=t.getOverflow?.();return S?.enabled===!0?S:void 0},P=()=>(h?h.setLabel(t.getOverflowLabel?.()??"More actions"):h=bb({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),h),K=S=>{x!==S&&(E?.disconnect(),x=S,M=_u(S),!(typeof ResizeObserver>"u")&&(E=new ResizeObserver(B=>{let I=B[B.length-1]?.contentRect?.width??_u(S);I!==M&&(M=I,le())}),E.observe(S)))},A=(S,B)=>{let R=DA(S.collapseAutoActionsBelow,B);if(R===null)return!1;let I=M||_u(B);return I>0&&I<R},H=(S,B,R)=>{if(!B)return"bar";if(S.resolved.builtIn){let Z=OA(S.resolved.id);return Z&&B.includeBuiltIns?.includes(Z)?"menu":"bar"}let I=S.resolved.presentation;return I==="overflow"||I==="auto"&&R?"menu":"bar"},w=S=>{let B=S.menuSlot;if(!B)return;if(!VA(S.element)){S.menuLabel?.remove(),S.menuLabel=void 0;return}let R=qA(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!==B&&B.appendChild(S.menuLabel)},_=(S,B)=>{if(S.mode===B)return S;let R=S.resolved.action;if(R&&!Hr(R)){u(S),e.delete(S.resolved.id);let I=c(S.resolved,B);return e.set(S.resolved.id,I),I}if(B==="menu"){let I=X("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Tu]:""}});I.appendChild(S.element),cb(Ou(S.element)),S.menuSlot=I;let Z=V=>{let ce=Ou(S.element);if(ce.disabled)return;let ie=V.target===ce||ce.contains(V.target);h?.close(!0),ie||ce.click()};I.addEventListener("click",Z,!0),S.detachMenuSlot=()=>I.removeEventListener("click",Z,!0),S.managed=!0,w(S)}else S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0;return S.mode=B,S},G=(S,B)=>{let R=B.map(I=>I.menuSlot??I.element);for(R.forEach((I,Z)=>{let V=S.children[Z];V!==I&&(V?S.insertBefore(I,V):S.appendChild(I))});S.children.length>R.length;)S.lastElementChild?.remove()},le=()=>{if(o)return;let S=t.getBindings();if(!S)return;let B=t.getState(),R=B.phase==="streaming",I=F();I&&K(S.footer);let Z=I?A(I,S.footer):!1,V={start:[],end:[]},ce=[];for(let ie of n){let fe=e.get(ie.id);if(!fe)continue;let Me=ie.action,Le=Me?Sb(Me.visible,B,!0)&&$A(Me.visibility,B):!0;if(fe.visible!==Le&&(fe.visible=Le,!Le&&fe.managed&&(fe.menuSlot??fe.element).remove()),!!Le){if(fe=_(fe,H(fe,I,Z)),Me){let be=Sb(Me.disabled,B,!1)||Me.disableWhenStreaming===!0&&R;v(fe,be),!Hr(Me)&&Me.pressed!==void 0&&fe.button?.setAttribute("aria-pressed",Me.pressed?"true":"false")}fe.mode==="menu"?(w(fe),ce.push(fe)):V[ie.placement].push(fe)}}if(ce.length>0){let ie=P();G(ie.panel,ce),ie.setItems(ce.map(be=>be.menuSlot??be.element)),ie.applyButtonSize();let fe=Number.isFinite(I?.order)?I?.order:Io.overflow,Me=V.start.findIndex(be=>be.resolved.order>fe),Le={resolved:{id:_A,placement:"start",presentation:"bar",order:fe,sequence:-1,source:"core"},element:ie.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(Me<0?V.start.length:Me,0,Le)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(S.actionsStart,V.start),m(S.actionsEnd,V.end)};return{resolve:()=>{if(o)return;let S=FA(t.collect()),B=new Set(S.map(R=>R.id));for(let[R,I]of e)B.has(R)||(u(I),e.delete(R));for(let R of S){let I=e.get(R.id);if(!I){let ie=g(R,"bar");ie&&e.set(R.id,ie);continue}let Z=I.resolved.action,V=R.action;if(!!Z!=!!V||Z&&V&&Hr(Z)!==Hr(V)||Z&&V&&Hr(Z)&&Hr(V)&&Z.render!==V.render){u(I),e.delete(R.id);let ie=g(R,I.mode);ie&&e.set(R.id,ie);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&&!Hr(V)?l(I,V):V&&I.element.toggleAttribute(Bu,V.disableWhenStreaming===!0)}n=S,le()},sync:le,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,E?.disconnect(),E=null,x=null;for(let S of e.values())u(S);e.clear(),h?.destroy(),h=null,n=[]}}}}var KA="core:model",GA=700,Ab=16,QA=["--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"],Mb=()=>{let t=X("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=X("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Eb(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=p=>{let g=t.getSelectedModelId();return p.find(u=>u.id===g)??p[0]},i=()=>{let p=X("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),g="",u=()=>{let E=t.getModels(),M=E.map(F=>`${F.id}:${F.label}`).join("|");M!==g&&(g=M,p.replaceChildren(...E.map(F=>{let P=X("option",{attrs:{value:F.id}});return P.textContent=F.label,P}))),p.value=s(E)?.id??""};u(),o=u;let m=()=>{p.value&&t.onSelect(p.value)};p.addEventListener("change",m);let v=E=>E.stopPropagation();p.addEventListener("click",v);let{wrapper:h,chevron:x}=Mb();return h.append(p,x),{element:h,destroy:()=>{o===u&&(o=null),p.removeEventListener("change",m),p.removeEventListener("click",v)}}},l=()=>{let p=X("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"}}),g=k("span","persona-composer-model-picker-label"),u=k("span","persona-composer-model-picker-suffix");p.append(g,u);let m=X("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),v=new Map,h="",x=null,E=()=>x?.isOpen===!0,M=(B=!1)=>{E()&&(x?.close(),p.setAttribute("aria-expanded","false"),B&&p.focus())},F=B=>{let R=[...v.values()];if(R.length===0)return;let I=(B%R.length+R.length)%R.length;R[I].focus()},P=B=>{if(E())return;x||(x=hc({anchor:p,content:m,placement:"top-start",offset:6,onDismiss:()=>p.setAttribute("aria-expanded","false")})),Nc(p,m,QA),x.open(),p.setAttribute("aria-expanded","true");let I=[...v.keys()].indexOf(s(t.getModels())?.id??"");F(B??(I>=0?I:0))},K=B=>{M(!0),t.onSelect(B)},A=B=>{B.preventDefault(),B.stopPropagation();let R=B.currentTarget.getAttribute("data-persona-model-option");R&&K(R)},H=B=>{let R=X("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":B.id}});if(B.icon){let ie=me(B.icon,Ab,"currentColor",1.5);if(ie){let fe=k("span","persona-composer-model-option-icon");fe.appendChild(ie),R.appendChild(fe)}}let I=k("span","persona-composer-model-option-body"),Z=k("span","persona-composer-model-option-label");if(Z.textContent=B.label,I.appendChild(Z),B.description){let ie=k("span","persona-composer-model-option-description");ie.textContent=B.description,I.appendChild(ie)}R.appendChild(I);let V=k("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let ce=me("check",Ab,"currentColor",2);return ce&&V.appendChild(ce),R.appendChild(V),R.addEventListener("click",A),R},w=()=>{let B=t.getModels(),R=B.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",A);v.clear(),m.replaceChildren(...B.map(V=>{let ce=H(V);return v.set(V.id,ce),ce}))}let I=s(B);for(let[V,ce]of v)ce.setAttribute("aria-selected",String(V===I?.id));g.textContent=I?.label??"";let Z=t.getSuffix?.()??"";u.textContent=Z,p.setAttribute("aria-label",[e,[I?.label,Z].filter(Boolean).join(" ")].filter(Boolean).join(": "))};w(),o=w;let _=B=>{B.preventDefault(),B.stopPropagation(),E()?M(!0):P()},G=B=>{if(B.key==="ArrowDown"){B.preventDefault(),E()?F(0):P(0);return}B.key==="ArrowUp"&&(B.preventDefault(),E()?F(-1):P(-1))},le=B=>{let R=[...v.values()],I=R.indexOf(B.target?.closest?.(".persona-composer-model-option"));switch(B.key){case"ArrowDown":B.preventDefault(),F(I+1);return;case"ArrowUp":B.preventDefault(),F(I-1);return;case"Home":B.preventDefault(),F(0);return;case"End":B.preventDefault(),F(R.length-1);return;case"Escape":B.preventDefault(),B.stopPropagation(),M(!0);return;case"Tab":M(!0);return;default:}};p.addEventListener("click",_),p.addEventListener("keydown",G),m.addEventListener("keydown",le);let{wrapper:ee,chevron:S}=Mb();return ee.append(p,S),{element:ee,destroy:()=>{o===w&&(o=null),p.removeEventListener("click",_),p.removeEventListener("keydown",G),m.removeEventListener("keydown",le);for(let B of v.values())B.removeEventListener("click",A);v.clear(),x?.destroy(),x=null,m.remove()}}};return{action:{id:KA,kind:"custom",placement:"end",order:GA,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var XA=":scope > [data-persona-composer-mode]";function Tb(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=g=>{let u=X("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":g.id}});if(g.iconName){let x=k("span","persona-mention-chip-icon"),E=me(g.iconName,12,"currentColor",1.5);E&&x.appendChild(E),u.appendChild(x)}let m=k("span","persona-mention-chip-label");m.textContent=g.shortLabel??g.label,u.appendChild(m);let v=X("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${g.label}`}}),h=me("x",12,"currentColor",2);return h?v.appendChild(h):v.textContent="\xD7",v.addEventListener("click",x=>{x.preventDefault(),x.stopPropagation(),t.onRemove(g.id)}),u.appendChild(v),u},l=()=>Array.from(e.querySelectorAll(XA)),c=g=>{g.setAttribute("data-persona-chip-exit",""),g.setAttribute("aria-hidden","true"),g.style.pointerEvents="none";let u=()=>{g.remove(),yc(e)},m=e.ownerDocument.defaultView,v=typeof m?.getComputedStyle=="function"?m.getComputedStyle(g).animationName:"";if(!v||v==="none"){u();return}g.addEventListener("animationend",u,{once:!0}),g.addEventListener("animationcancel",u,{once:!0})},p=()=>{for(let g of l())g.remove()};return{element:e,render:(g,u)=>{if(o)return;let m=u.filter(E=>g.includes(E.id)),v=m.map(E=>`${E.id}:${E.shortLabel??E.label}`).join("|");if(v===n)return;n=v;let h=new Map;for(let E of l()){let M=E.getAttribute("data-persona-composer-mode");M&&m.some(P=>P.id===M)&&!E.hasAttribute("data-persona-chip-exit")?h.set(M,E):E.hasAttribute("data-persona-chip-exit")||c(E)}let x=e.firstChild;for(let E of m){let M=h.get(E.id);M||(M=i(E),s.has(E.id)||(M.setAttribute("data-persona-chip-enter",""),M.addEventListener("animationend",()=>M?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(E.id),M!==x&&e.insertBefore(M,x),x=M.nextSibling}yc(e)},destroy:()=>{o=!0,p(),yc(e)}}}var kb=t=>`core:mode:${t}`;var Du=t=>Math.min(300+t,499),Pb=t=>`core:mode-group:${t}`;function jc(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function YA(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Ib(t,e){return t?.length?t.filter(n=>!jc(n.groupId,e)&&!YA(n.groupId,e)):[]}var JA=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Lb(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(JA(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 Vc(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Hb(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Rb(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var ZA=16;function Wb(t){let e=null;return{action:{id:Pb(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=X("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=g=>{g.preventDefault(),g.stopPropagation();let m=g.currentTarget.getAttribute("data-persona-composer-mode");!m||t.getActiveIds().includes(m)&&t.getGroup()?.selection==="single"||t.onSelect(m)},c=g=>{let u=X("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":g.id,"aria-label":g.label}});if(g.iconName){let v=me(g.iconName,ZA,"currentColor",1.5);v&&u.appendChild(v)}let m=k("span","persona-composer-segmented-label");return m.textContent=g.shortLabel??g.label,u.appendChild(m),u.addEventListener("click",l),u},p=()=>{let g=t.getGroup();g?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",g.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=t.getModes(),m=u.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==i){i=m;for(let x of s.values())x.removeEventListener("click",l);s.clear();let h=u.map(x=>{let E=c(x);return s.set(x.id,E),E});o.replaceChildren(...h)}let v=t.getActiveIds();for(let[h,x]of s)x.setAttribute("aria-pressed",String(v.includes(h)))};return p(),e=p,{element:o,destroy:()=>{e===p&&(e=null);for(let g of s.values())g.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function Bb(t){let e=X("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,s=i=>{let l=k("span","persona-composer-quote-bar"),c=k("div","persona-composer-quote-content");if(i.sourceLabel){let m=k("div","persona-composer-quote-source");m.textContent=i.sourceLabel,c.appendChild(m)}let p=X("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});p.textContent=Pc(i.text),c.appendChild(p);let g=X("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=me("x",12,"currentColor",2);u?g.appendChild(u):g.textContent="\xD7",g.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),t.onDismiss()}),e.replaceChildren(l,c,g)};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 _b(t){let e=X("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,p,g)=>{let u=X("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[p]:""}}),m=me(l,12,"currentColor",2);return m?u.appendChild(m):u.textContent=c,u.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),g()}),u},i=l=>{let c=Pc(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(u=>u.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=X("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 Ob(t){let e=X("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=X("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,g,u)=>{let m=X("button",{className:`persona-message-edit-button ${p}`,attrs:{type:"button",[g]:""},text:c});return m.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),u()}),m},l=()=>{let c=n.value.trim();c&&t.onSave(c)};return s.append(i(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),i(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",l)),n.addEventListener("keydown",c=>{if(c.key==="Escape"){c.preventDefault(),c.stopPropagation(),t.onCancel();return}c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),l())}),e.append(n,s),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let c=n.value.length;n.setSelectionRange(c,c),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function Db(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 Nb(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 Fb(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 Ub(t){return t.wrapped||t.text.includes(`
17
+ `)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function $b(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function qb(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),s=Number.parseFloat(n.fontSize),i=Number.isFinite(o)&&o>0?o:Number.isFinite(s)&&s>0?s*1.4:0;if(!i)return!1;let l=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-l>i*1.5}function Nu(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function jb(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var eM=t=>typeof t?.then=="function";function zb(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 Vb(t,e,n){let o;try{o=t(Nu(e),{signal:n})}catch(s){return{status:"error",error:s}}return eM(o)?Promise.resolve(o).then(s=>n.aborted?{status:"aborted"}:zb(e,s),s=>n.aborted?{status:"aborted"}:{status:"error",error:s}):zb(e,o)}function Kb(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",s=e.buttonTooltipText??"Add context",i=k("div","persona-send-button-wrapper"),l=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${_n} ${lo}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":s,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),c=me(o,dn,"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:CP,load:tM}=Pt({fallbackImport:()=>import("./context-mentions-45MODWOY.js")});var Fu=tM;var{setLoader:xP,load:nM}=Pt({fallbackImport:()=>import("./context-mentions-inline-I2RDEBAK.js"),resetOnSetLoader:!0});var Gb=nM;function Ha(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=X("span",{className:Bn("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=me(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(X("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function Qb(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=qh(e).filter(A=>A.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(A=>A.sources.some(H=>typeof H.matchCommand=="function")),s=A=>o.some(H=>H.trigger?H.position==="line-start"?A.split(`
18
+ `).some(_=>_.startsWith(H.trigger)):(H.position==="anywhere"?A:A.split(`
19
+ `)[0]).startsWith(H.trigger):!1),i=(A,H)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:H}))}catch{}},l=!t.chipRow,c=t.chipRow??X("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),p=null,g=null,u=t.textarea,m=null,v=null,h=null,x=null,E=()=>{if(p)return Promise.resolve(p);if(g)return g;let A=Fu().then(H=>(H.setMentionIconRenderer(me),p=H.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:m??void 0,anchor:t.anchor,contextRow:c,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:K,emit:i}),p)).catch(H=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",H),g===A&&(g=null),null));return g=A,A},M=()=>{Gb().then(A=>{let H=A.mountInlineComposer({textarea:t.textarea,renderToken:_=>Ha(_,{render:e.renderMentionToken}),onMentionRemoved:_=>p?.untrackMention(_)});m=H.input,v=H.destroy;let w=u;w.replaceWith(H.element),u=H.element,x={next:H.element,prev:w},h?.(H.element,w),p?p.rebindComposer(H.input):g&&g.then(_=>_?.rebindComposer(H.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&M();let F=[],P=new Map;for(let A of n){if(!A.showButton)continue;let H=Kb({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{E().then(w=>w?.openMenu(A.trigger))}});F.push(H),P.set(A.trigger,H.button)}let K=(A,H,w)=>{let _=P.get(H);_&&(_.setAttribute("aria-expanded",A?"true":"false"),A?_.setAttribute("aria-controls",w):_.removeAttribute("aria-controls"))};return{affordanceButtons:F.map(A=>A.wrapper),contextRow:c,handleInput:A=>{if(p){p.handleInput();return}if(!$h(A))return;let H=u,w=H.selectionStart??0;Uh(H.value,w,n)&&E().then(_=>_?.handleInput())},handleKeydown:A=>{if(p?.isMenuOpen())return p.handleKeydown(A);if(A.key==="Backspace"&&p?.hasMentions()&&!x){let H=u,w=H.selectionStart===0&&H.selectionEnd===0;if((H.value.length===0||w)&&p.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>p?.isMenuOpen()??!1,hasMentions:()=>p?.hasMentions()??!1,getMentionRefs:()=>p?.getMentionRefs()??[],collectForSubmit:()=>p?.collectForSubmit()??null,takeInlineCommand:async A=>s(A)?(p??await E())?.dispatchInlineCommand(A)??null:null,clear:()=>p?.clear(),prefetch:()=>{Fu().catch(()=>{})},onComposerSwap:A=>{h=A,x&&A(x.next,x.prev)},destroy:()=>{p?.destroy(),v?.();for(let A of F)A.wrapper.remove();l&&c.remove()}}}var Kc="16px",Gc="transparent",oM=(()=>{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})(),rM={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:oM,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"}},sM={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"}},iM={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:tr,maxWidth:gb,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Kc,canvasBackground:Gc},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function pn(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."))?pn(t,o):o}function Yb(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=pn(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 aM(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 Jb(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]=Jb(i,s):n[o]=s}return n}function lM(t,e){return e?Jb(t,e):t}function mi(t,e={}){let n={palette:rM,semantic:sM,components:iM},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:lM(n.components,t?.components)};if(e.validate!==!1){let s=aM(o);if(!s.valid)throw new Error(`Theme validation failed: ${s.errors.map(i=>i.message).join(", ")}`)}if(e.plugins)for(let s of e.plugins)o=s.transform(o);return o}var Uu=t=>t.trim()==="0"?"0px":t,Xb="--persona-",cM=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 g=p.endsWith("%"),u=parseFloat(g?p.slice(0,-1):p);return g?u/100*255:u}))}}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},dM=.179,Jt=(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[Xb+i],s!==void 0)break;s!==void 0&&(t[Xb+n]=s)}};function Zb(t){let e=Yb(t),n={};for(let[U,Ee]of Object.entries(e)){let Fe=U.replace(/\./g,"-");n[`--persona-${Fe}`]=Ee.value}Jt(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"],Jt(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"]]),Jt(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"]}`,Jt(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"]??Kc,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Gc,Jt(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"]]),Jt(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"],Jt(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"],Jt(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 g=n["--persona-components-history-railHeader-border"];g&&(n["--persona-history-rail-header-border"]=g);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[U,Ee]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Fe=n[`--persona-components-history-overlay-${U}`];Fe&&(n[`--persona-history-overlay-${Ee}`]=Fe)}for(let[U,Ee]of[["background","bg"],["borderRadius","radius"]]){let Fe=n[`--persona-components-history-menu-${U}`];Fe&&(n[`--persona-history-menu-${Ee}`]=Fe)}let m=t.components?.history?.motion;if(m){let U=yt=>{if(yt===void 0)return;let Re=String(yt).trim();return/^\d+(\.\d+)?$/.test(Re)?`${Re}ms`:Re},Ee=U(m.enterDurationMs);Ee!==void 0&&(n["--persona-history-enter-ms"]=Ee);let Fe=U(m.exitDurationMs);Fe!==void 0&&(n["--persona-history-exit-ms"]=Fe),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let v=n["--persona-components-history-dangerForeground"];v&&(n["--persona-history-danger-fg"]=v),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let U of["scrim","shadow"]){let Ee=n[`--persona-components-history-confirm-${U}`];Ee&&(n[`--persona-history-confirm-${U}`]=Ee)}for(let[U,Ee]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Fe=n[`--persona-components-tooltip-${U}`];Fe&&(n[`--persona-tooltip-${Ee}`]=Fe)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[U,Ee]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Fe=n[`--persona-components-messageActions-${U}`];Fe&&(n[`--persona-message-action-${Ee}`]=Fe)}Jt(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],x=n["--persona-components-introCard-shadow"],E=(!h||h==="transparent"||h==="none")&&(!x||x==="none"),M=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=E&&M==="1.5rem"?"1.5rem 0":M,Jt(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),Jt(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 A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let H=n["--persona-components-markdown-prose-fontFamily"];H&&H!=="inherit"&&(n["--persona-md-prose-font-family"]=H),Jt(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"]]),Jt(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Jt(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Jt(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Jt(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"],Jt(n,[["message-border","components-message-border","border"]]),Jt(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 le=w?.toggleGroup;le&&(le.gap&&(n["--persona-toggle-group-gap"]=le.gap),le.borderRadius&&(n["--persona-toggle-group-radius"]=le.borderRadius));let ee=w?.artifact;if(ee?.toolbar){let U=ee.toolbar;U.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=U.iconHoverColor),U.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=U.iconHoverBackground),U.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=U.iconPadding),U.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=U.iconBorderRadius),U.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=U.iconBorder),U.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Uu(U.toggleGroupGap)),U.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=U.toggleBorderRadius),U.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Uu(U.toggleGroupPadding)),U.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=U.toggleGroupBorder),U.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=U.toggleGroupBorderRadius),U.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=pn(t,U.toggleGroupBackground)??U.toggleGroupBackground),U.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=U.copyBackground),U.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=U.copyBorder),U.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=U.copyColor),U.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Uu(U.copyBorderRadius)),U.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=U.copyPadding),U.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=U.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??U.copyMenuBackground),U.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=U.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??U.copyMenuBorder),U.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=U.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??U.copyMenuShadow),U.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=U.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??U.copyMenuBorderRadius),U.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=U.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??U.copyMenuItemHoverBackground),U.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=U.iconBackground),U.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=U.toolbarBorder)}if(ee?.tab){let U=ee.tab;U.background&&(n["--persona-artifact-tab-bg"]=U.background),U.activeBackground&&(n["--persona-artifact-tab-active-bg"]=U.activeBackground),U.activeBorder&&(n["--persona-artifact-tab-active-border"]=U.activeBorder),U.borderRadius&&(n["--persona-artifact-tab-radius"]=U.borderRadius),U.textColor&&(n["--persona-artifact-tab-color"]=U.textColor),U.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=U.hoverBackground),U.listBackground&&(n["--persona-artifact-tab-list-bg"]=U.listBackground),U.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=U.listBorderColor),U.listPadding&&(n["--persona-artifact-tab-list-padding"]=U.listPadding)}if(ee?.pane){let U=ee.pane;if(U.toolbarBackground){let Ee=pn(t,U.toolbarBackground)??U.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ee}}if(ee?.card){let U=ee.card;U.background&&(n["--persona-artifact-card-bg"]=U.background),U.border&&(n["--persona-artifact-card-border"]=U.border),U.borderRadius&&(n["--persona-artifact-card-radius"]=U.borderRadius),U.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=U.hoverBackground),U.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=U.hoverBorderColor)}if(ee?.inline){let U=ee.inline;U.background&&(n["--persona-artifact-inline-bg"]=pn(t,U.background)??U.background),U.border&&(n["--persona-artifact-inline-border"]=U.border),U.borderRadius&&(n["--persona-artifact-inline-radius"]=U.borderRadius),U.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=pn(t,U.chromeBackground)??U.chromeBackground),U.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=pn(t,U.chromeBorder)??U.chromeBorder),U.titleColor&&(n["--persona-artifact-inline-title-color"]=pn(t,U.titleColor)??U.titleColor),U.mutedColor&&(n["--persona-artifact-inline-muted-color"]=pn(t,U.mutedColor)??U.mutedColor),U.frameHeight&&(n["--persona-artifact-inline-frame-height"]=U.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"]=pn(t,S.background)??S.background));let B=n["--persona-surface"],R=n["--persona-container"],I=n["--persona-palette-colors-gray-100"]??"#f3f4f6",Z=n["--persona-palette-colors-gray-200"]??"#e5e7eb",V=n["--persona-palette-colors-gray-300"]??"#d1d5db",ce=!R||R===B,ie=cM(B??n["--persona-background"]),fe=ce&&ie!==void 0&&ie<dM,Me=fe?"rgba(255, 255, 255, 0.08)":I,Le=fe?"rgba(255, 255, 255, 0.12)":Z,be=fe?"rgba(255, 255, 255, 0.16)":V,Je=ce?Me:R,ve=ce?Le:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Je,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ve,ce&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??be),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Je,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Je,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Je,n}var pM={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"}}},uM={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},ev=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},$u=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",gM=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":$u()},tv=t=>gM(t),fM=t=>mi(t),mM=t=>{let e=gi(uM,t??{})??{};return mi({...e,palette:{...e.palette,colors:{...pM.colors,...e.palette?.colors}}},{validate:!1})},hi=t=>{let e=tv(t),n=ev(t?.theme),o=ev(t?.darkTheme);return e==="dark"?mM(gi(n??{},o??{})):fM(n)},hM=t=>Zb(t),Ra=(t,e)=>{let n=hi(e),o=hM(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",tv(e))},Qc=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t($u())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t($u());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};import{Activity as SC,Check as xC,Copy as AC}from"lucide";var Rr=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Xc="24px",qu=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",Wa=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},nv=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var ov=null;var zu=()=>{if(ov!==null)return ov;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},yM="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Yc=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},Jc=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 Yc("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Yc("unsupported",t),null):(n==="space"&&(o.key=" "),o)},bM=t=>yM.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),rv=(t,e)=>{let n=Jc(t);if(!n)return"";let o=zu(),s=bM(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("+")},Zc=t=>rv(t,!1),Ba=t=>rv(t,!0),vM=(t,e)=>e.key?.toLowerCase()===t.key&&(zu()?e.metaKey:e.ctrlKey)===t.mod&&!(zu()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,CM=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},sv=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(vM(c.parsed,i)&&c.when?.()!==!1&&o(c,i)&&!(!c.allowInInput&&CM(l))){i.preventDefault();try{c.run(i)}catch(p){Yc(`${c.id} threw on`,c.combo),console.warn(p)}return}};return n?.addEventListener("keydown",s),{register(i){let l=Jc(i.combo);if(!l)return()=>{};let c=`${l.mod?"m":""}${l.shift?"s":""}${l.alt?"a":""}${l.key}`,p=e.get(c);return p?(Yc(`${p.id} already owns`,i.combo),()=>{}):(e.set(c,{...i,parsed:l}),i.element?.setAttribute("aria-keyshortcuts",Ba(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 wM}from"idiomorph";var ed=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;wM.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 iv=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var ju={index:-1,draft:""};function av(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 lv(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 cv(){return new Map}function dv(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function pv(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function uv(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:YP,load:SM}=Pt({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var gv=SM;function Vu(t,e=an){let n=t.style.position,o=t.style.zIndex,s=t.style.isolation,i=getComputedStyle(t),l=i.position==="static"||i.position==="";return l&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{l&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=s}}var _a=0,Wr=null;function Ku(t=document){if(_a++,_a===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Wr={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,_a=Math.max(0,_a-1),_a===0&&Wr)){let n=t.body,o=t.defaultView??window;n.style.overflow=Wr.originalOverflow,n.style.position=Wr.originalPosition,n.style.top=Wr.originalTop,n.style.width=Wr.originalWidth,o.scrollTo(0,Wr.scrollY),Wr=null}}}var Oa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Rt=t=>(t?.launcher?.mountMode??"floating")==="docked",Da=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Yn=t=>{let e=t?.launcher?.dock;return{side:e?.side??Oa.side,width:e?.width??Oa.width,animate:e?.animate??Oa.animate,reveal:e?.reveal??Oa.reveal,maxHeight:e?.maxHeight??Oa.maxHeight}};import{ArrowRight as xM}from"lucide";var Gu=t=>t==="followUp"?"follow-up":t,Qu=(t,e=0)=>{if(typeof t=="string"){let s=t.trim();return s?{id:s,label:s,prompt:s,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},AM=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'}},fv=new WeakSet,MM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,EM=t=>{MM()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Xu=t=>{var K,A,H;let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:p,chipsConfig:g,session:u,getTextarea:m,eventTarget:v,submitPrompt:h}=t,x=o==="followUp",E=e.behavior,M=()=>{if(u.isStreaming())return;let w={suggestion:{...e},surface:o,source:s,behavior:E},_=v.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:w,bubbles:!0,composed:!0,cancelable:!0}));if(x&&v.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!_)return;for(let le of p)if(le.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let G=m();if(E==="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="",u.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=E,i==="chip"&&(g?.fontFamily&&(w.style.fontFamily=AM(g.fontFamily)),g?.fontWeight&&(w.style.fontWeight=g.fontWeight),g?.paddingX&&(w.style.paddingLeft=g.paddingX,w.style.paddingRight=g.paddingX),g?.paddingY&&(w.style.paddingTop=g.paddingY,w.style.paddingBottom=g.paddingY)),e.icon){let G=me(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(X("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&_.appendChild(X("span",{className:"persona-suggestion__description",text:e.description})),w.appendChild(_),i!=="chip"){let G=tn(xM,16,"currentColor",1.8);G&&(G.classList.add("persona-suggestion__arrow"),w.appendChild(G))}return w.addEventListener("click",M),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:M}),P))break;return P??(P=F()),(K=P.dataset).suggestionId||(K.suggestionId=e.id),(A=P.dataset).behavior||(A.behavior=E),(H=P.dataset).emphasis||(H.emphasis=e.emphasis),P instanceof HTMLButtonElement||P.setAttribute("aria-disabled",l?"true":"false"),P},Na=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 u=Math.max(0,t.scrollWidth-t.clientWidth);if(u<=1){i();return}let m=getComputedStyle(t).direction==="rtl",v=Math.min(u,Math.max(0,Math.abs(t.scrollLeft))),h=4,x=v<=h,E=v>=u-h,M=m?!E:!x,F=m?!x:!E;t.toggleAttribute("data-scroll-left",M),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:(u,m,v,h,x,E)=>{t.replaceChildren(),e.length=0,n.length=0;let M=E?.source??"config",F=E?.surface??(M==="config"?"starter":"followUp"),P=F==="followUp",K=E?.variant??"chip",A=E?.behavior??"send",H=E?.overflow??"wrap",w=E?.config??{},_=E?.plugins??[],G=typeof E?.maxItems=="number"?Math.max(0,Math.floor(E.maxItems)):void 0,le=P?"followUps":"starters";!fv.has(w)&&w.debug===!0&&K!=="chip"&&w.suggestions?.[le]?.overflow!==void 0&&(fv.add(w),console.info(`[persona] suggestions.${le}.overflow applies to the "chip" variant only; the "${K}" variant manages its own stacking.`));let ee=V=>V.map(Qu).filter(ce=>ce!==null).map(ce=>({...ce,behavior:ce.behavior??A})),S=ee(u??[]);_.forEach(V=>{V.transformSuggestions&&(S=ee(V.transformSuggestions({suggestions:S.map(ce=>({...ce})),surface:F,source:M,config:w})))});let B=G===void 0?S:S.slice(0,G);if(!B.length){t.hidden=!0,o=null,i();return}if(!P&&(h??m.getMessages()).some(ce=>ce.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=Gu(F),t.dataset.variant=K,t.dataset.overflow=H;let R=document.createDocumentFragment(),I=m.isStreaming();B.forEach((V,ce)=>{let ie=Xu({item:V,index:ce,surface:F,source:M,variant:K,streaming:I,config:w,plugins:_,chipsConfig:x,session:m,getTextarea:()=>v,eventTarget:t,submitPrompt:E?.submitPrompt});R.appendChild(ie),n.push(ie),[...ie instanceof HTMLButtonElement?[ie]:[],...Array.from(ie.querySelectorAll("button"))].forEach(Me=>{e.includes(Me)||(Me.disabled=I,e.push(Me))})}),t.appendChild(R),l(),c();let Z=JSON.stringify({normalized:B,surface:F,variant:K,source:M});Z!==o&&(o=Z,EM(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:B.map(V=>({...V})),surface:F,source:M,variant:K},bubbles:!0,composed:!0})),P&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:B.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var On={"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 TM="persona-header-control",kM="persona-header-control--glyph",PM="persona-header-control--sparse",IM=20,LM={x:[1.4,1.05]},mv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",HM="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",td=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=LM[e]??[1,1.5],c=!o;t.classList.toggle(kM,c),t.classList.toggle(PM,c&&i!==1);let p=parseFloat(o??"")||IM,g=me(e,`${Math.round(p*i)}px`,"currentColor",l);g?(g.style.display="block",c||(g.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((l/1.5).toFixed(4))})`),t.replaceChildren(g)):s&&(t.textContent=s)},vs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=mv,size:c,iconSize:p,color:g,backgroundColor:u,borderWidth:m,borderColor:v,borderRadius:h,paddingX:x,paddingY:E,hidden:M,extraClassName:F,attrs:P}=t,K=k("div",l),A=!!(m||v),H=X("button",{className:Bn(TM,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"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:M?"none":void 0,color:g||un.actionIconColor,backgroundColor:u,border:A?`${m||"0px"} solid ${v||"transparent"}`:void 0,borderRadius:h,paddingLeft:x,paddingRight:x,paddingTop:E,paddingBottom:E}});return s?td(H,s,{iconSize:p,iconText:i}):i&&(H.textContent=i),K.appendChild(H),Yt({anchor:H,trigger:K,text:()=>H.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:H,wrapper:K}},yi=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=mv,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",p=l.closeButtonShowTooltip??!0,{button:g,wrapper:u}=vs({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:g,wrapper:u}},bi=(t,e={})=>{let{wrapperClassName:n=HM,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",p=l.showTooltip??!0,{button:g,wrapper:u}=vs({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:g,wrapper:u}};var un={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},Yu={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},RM={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)"},Cs=t=>{let{config:e,showClose:n=!0}=t,o=X("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:un.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,g=X("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 H=parseFloat(i)||24,w=me(p,H*.6,"currentColor",1);w?g.replaceChildren(w):g.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let H=k("img");H.src=e.launcher.iconUrl,H.alt="",H.className="persona-rounded-xl persona-object-cover",H.style.height=i,H.style.width=i,g.replaceChildren(H)}else g.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let u=k("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=X("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:un.titleColor,...Yu}}),v=X("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:un.subtitleColor,...RM}});u.append(m,v),c?o.append(u):o.append(g,u);let h=s.clearChat??{},x=h.enabled??!0,E=h.placement??"inline",M=null,F=null;if(x){let w=bi(e,{wrapperClassName:E==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=w.button,F=w.wrapper,E==="top-right"&&(F.style.right="48px"),E==="inline"&&o.appendChild(F)}let P=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&E==="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:A}=yi(e,{showClose:n,wrapperClassName:P});return l!=="top-right"&&o.appendChild(A),{header:o,iconHolder:g,headerTitle:m,headerSubtitle:v,closeButton:K,closeButtonWrapper:A,clearChatButton:M,clearChatButtonWrapper:F}},Fa=(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 WM=t=>{let e=Cs({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 BM(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=vs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Zc(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=Ba(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=Jh({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 _M=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=un.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,g,u;if(p){let A=ey({label:l.title??"Chat Assistant",menuItems:p.menuItems,onSelect:H=>{let w=G=>{G===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:H}}))},_=p.onSelect(H);_ instanceof Promise?_.then(w,()=>{}):w(_)},hover:p.hover,className:""});g=A.element,g.style.color=un.titleColor,u=g.querySelector(".persona-combo-btn-label")??g}else{if(g=k("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=k("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=un.titleColor,Object.assign(u.style,Yu),u.textContent=l.title??"Chat Assistant",g.appendChild(u),s?.onTitleClick){g.style.cursor="pointer",g.setAttribute("role","button"),g.setAttribute("tabindex","0");let H=s.onTitleClick;g.addEventListener("click",w=>{w.target.closest("button")||H()}),g.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),H())})}let A=s?.titleRowHover;A&&(g.style.borderRadius=A.borderRadius??"10px",g.style.padding=A.padding??"6px 4px 6px 12px",g.style.margin="-6px 0 -6px -12px",g.style.border="1px solid transparent",g.style.transition="background-color 0.15s ease, border-color 0.15s ease",g.style.width="fit-content",g.style.flex="none",g.addEventListener("mouseenter",()=>{g.style.backgroundColor=A.background??"",g.style.borderColor=A.border??""}),g.addEventListener("mouseleave",()=>{g.style.backgroundColor="",g.style.borderColor="transparent"}))}c.appendChild(g);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:v,wrapper:h}=yi(e,{showClose:n,wrapperClassName:m});o&&v.addEventListener("click",o);let x=k("div","persona-flex persona-items-center persona-gap-1");p||BM(x,s?.trailingActions,s?.onAction??i);let E=l.clearChat??{},M=null,F=null;if(E.enabled??!0){let A=E.placement??"inline",H=bi(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});M=H.button,F=H.wrapper,A==="top-right"?F.style.right="48px":x.appendChild(F)}x.appendChild(h),c.appendChild(x);let P=k("div");P.style.display="none";let K=k("span");return K.style.display="none",{header:c,iconHolder:P,headerTitle:u,headerSubtitle:K,closeButton:v,closeButtonWrapper:h,clearChatButton:M,clearChatButtonWrapper:F}},hv={default:WM,minimal:_M},OM=t=>hv[t]??hv.default,nd=(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"),g=k("span"),u=k("button");u.style.display="none";let m=k("div");return m.style.display="none",{header:l,iconHolder:c,headerTitle:p,headerSubtitle:g,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=OM(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 Ua=t=>{let{config:e}=t,n=X("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=zc(),s=X("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}=Fc(e);l();let c=Uc(e),p=fi(e),g=$c(e),u=qc(e),m=X("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(m),g&&(g.previewsContainer.style.gap="8px",m.append(g.previewsContainer),s.append(g.input)),s.append(i);let v=X("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=X("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),x=X("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return g&&h.append(g.wrapper),p&&x.append(p.wrapper),x.append(c.wrapper),v.append(h,x),s.append(v),s.addEventListener("click",E=>{E.target!==c.button&&E.target!==c.wrapper&&E.target!==p?.button&&E.target!==p?.wrapper&&E.target!==g?.button&&E.target!==g?.wrapper&&i.focus()}),n.append(o,s,u),{footer:n,suggestions:o,composerForm:s,header:m,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:u,attachmentButton:g?.button??null,attachmentButtonWrapper:g?.wrapper??null,attachmentInput:g?.input??null,attachmentPreviewsContainer:g?.previewsContainer??null,actionsRow:v,leftActions:h,rightActions:x,setSendButtonMode:c.setMode}};import{ChevronUp as DM,MessageSquare as NM}from"lucide";var yv=()=>{let t=X("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=tn(NM,16,"currentColor",1.5);n&&e.appendChild(n);let o=k("span","persona-pill-peek__text"),s=k("span","persona-pill-peek__caret"),i=tn(DM,16,"currentColor",1.5);return i&&s.appendChild(i),t.append(e,o,s),{root:t,textNode:o}},od=t=>{let{config:e}=t,n=X("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=zc(),s=qc(e);s.style.display="none";let{textarea:i,attachAutoResize:l}=Fc(e,{defaultMaxLines:5});l();let c=Uc(e),p=fi(e),g=$c(e);g&&g.previewsContainer.classList.add("persona-pill-composer__previews");let u=X("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=X("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});g&&m.append(g.wrapper);let v=X("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),u.addEventListener("click",E=>{E.target!==c.button&&E.target!==c.wrapper&&E.target!==p?.button&&E.target!==p?.wrapper&&E.target!==g?.button&&E.target!==g?.wrapper&&i.focus()}),g&&u.append(g.input),u.append(m,i,v);let h=X("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),g&&h.append(g.previewsContainer),n.append(o,u,s);let x=u;return{footer:n,suggestions:o,composerForm:u,header:h,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:s,attachmentButton:g?.button??null,attachmentButtonWrapper:g?.wrapper??null,attachmentInput:g?.input??null,attachmentPreviewsContainer:g?.previewsContainer??null,actionsRow:x,leftActions:m,rightActions:v,setSendButtonMode:c.setMode}};var FM=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}},UM=(t,e)=>{if(!t)return null;let n=FM(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},$M=(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},qM=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Zu=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},eg=320,Sv=320,zM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),jM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),VM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),KM=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),GM=t=>{if(!t||t.length===0)return null;let e=X("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=X("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=k("span","persona-mention-chip-icon"),i=me(n.iconName??"at-sign",13,"currentColor",2);i&&s.appendChild(i),o.appendChild(s),o.appendChild(X("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},QM=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Ha(o.ref,{readonly:!0,render:e}))}return n},bv="\uE000",vv="\uE001",XM=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=v=>`${bv}${s}:${v}${vv}`,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(QM(e,o));return}t.innerHTML=c;let g=new RegExp(`${bv}${s}:(\\d+)${vv}`),u=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),m=[];for(let v=u.nextNode();v;v=u.nextNode())m.push(v);for(let v of m){let h=v;for(let x=g.exec(h.data);x;x=g.exec(h.data)){let E=e[Number(x[1])],M=h.splitText(x.index);M.data=M.data.slice(x[0].length),E?.kind==="mention"&&M.parentNode?.insertBefore(Ha(E.ref,{readonly:!0,render:o}),M),h=M}}},YM=(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 g=k("img");g.alt=c.alt?.trim()||`Attached image ${p+1}`,g.loading="lazy",g.decoding="async",g.referrerPolicy="no-referrer",g.style.display="block",g.style.width="100%",g.style.maxWidth=`${eg}px`,g.style.maxHeight=`${Sv}px`,g.style.height="auto",g.style.objectFit="contain",g.style.borderRadius="10px",g.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",g.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,g.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),g.remove(),s===0&&l())}),g.addEventListener("load",()=>{u=!0}),qM(c.image)?(g.src=c.image,o.appendChild(g)):(u=!0,s=Math.max(0,s-1),g.remove())}),s===0?(l(),null):o}catch{return n?.(),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","audio");let n=0;return t.forEach(o=>{if(!Zu(o.audio))return;let s=k("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${eg}px`,e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},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(!Zu(o.video))return;let s=k("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${eg}px`,s.style.maxHeight=`${Sv}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}},eE=t=>{if(t.length===0)return null;try{let e=k("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!Zu(o.data))return;let s=k("a");s.href=o.data,s.download=o.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},$a=()=>{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},tE=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:$a};if(e){let s=e(o);if(s!==null)return s}return $a()},nE=(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},Cv=(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},qa=(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},wv={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"}},oE=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=wv[n??"bubble"]??wv.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)`)},rd="custom:",rE=t=>`${rd}${t}`,xv=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),sE=(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,g=(e.showEdit??!1)&&o?.canEdit===!0,u=(e.showQuote??!1)&&o?.canQuote!==!1,m=xv(e,t.role);if(!s&&!i&&!l&&!c&&!p&&!g&&!u&&m.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",x=e.layout??"pill-inside",E={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],M={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[x],F=k("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${E} ${M} ${v==="hover"?"persona-message-actions-hover":""}`);F.id=`actions-${t.id}`,F.setAttribute("data-actions-for",t.id);let P=(K,A,H)=>{let w=Zh({icon:K,label:A,size:14,className:"persona-message-action-btn",chromeless:!0});return w.setAttribute("data-action",H),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")),g&&F.appendChild(P("pencil","Edit message","edit")),u&&F.appendChild(P("quote","Quote message","quote"));for(let K of m)F.appendChild(P(K.iconName??"ellipsis",K.label,rE(K.id)));return F},tg=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",p=l.avatar,g=l.timestamp,u=p?.show??!1,m=g?.show??!1,v=p?.position??"left",h=g?.position??"below",x=qa(t.role,c),E=k("div",x.join(" "));E.id=`bubble-${t.id}`,E.setAttribute("data-message-id",t.id),E.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let M=i?.widgetConfig?.theme?.components?.message;oE(E,t.role,c,t.role==="user"?M?.user:M?.assistant),c==="flat"?(E.style.backgroundColor="transparent",E.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(E.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",E.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(E.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",E.style.color="var(--persona-message-assistant-text, var(--persona-text))");let F=zM(t),P=t.content?.trim()??"",A=F.length>0&&P===ui,H=bc(i?.widgetConfig?.features?.streamAnimation),w=i?.widgetConfig?.features?.streamAnimation?.plugins,_=t.role==="assistant"&&H.type!=="none"?ha(H.type,w):null,G=t.role==="assistant"&&_?.isAnimating?.(t)===!0,le=t.role==="assistant"&&_!==null&&(!!t.streaming||G);le&&_?.bubbleClass&&E.classList.add(_.bubbleClass);let ee=document.createElement("div");ee.classList.add("persona-message-content"),t.streaming&&ee.classList.add("persona-content-streaming"),le&&_&&(_.containerClass&&ee.classList.add(_.containerClass),ee.style.setProperty("--persona-stream-step",`${H.speed}ms`),ee.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let S=le?vc(t.content??"",H.buffer,_,t,!!t.streaming):t.content??"",B=()=>{let ve=e({text:S,message:t,streaming:!!t.streaming,raw:t.rawContent});return le&&_?.wrap==="char"?ya(ve,"char",t.id,{skipTags:_.skipTags}):le&&_?.wrap==="word"?ya(ve,"word",t.id,{skipTags:_.skipTags}):ve},R=null;if(A?(R=document.createElement("div"),R.innerHTML=B(),R.style.display="none",ee.appendChild(R)):t.contentSegments?.length?XM(ee,t.contentSegments,ve=>e({text:ve,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):ee.innerHTML=B(),le&&_?.useCaret&&!A&&P){let ve=Cc(),U=ee.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ee=U[U.length-1];if(Ee?.parentNode)Ee.parentNode.insertBefore(ve,Ee.nextSibling);else{let Fe=ee.lastElementChild;Fe?Fe.appendChild(ve):ee.appendChild(ve)}}if(m&&h==="inline"&&t.createdAt){let ve=Cv(t,g,"span");ve.classList.add("persona-timestamp-inline");let U=ee.lastElementChild;U?U.appendChild(ve):ee.appendChild(ve)}if(F.length>0){let ve=YM(F,!A&&!!P,()=>{A&&R&&(R.style.display="")});ve?E.appendChild(ve):A&&R&&(R.style.display="")}let I=jM(t);if(I.length>0){let ve=JM(I);ve&&E.appendChild(ve)}let Z=VM(t);if(Z.length>0){let ve=ZM(Z);ve&&E.appendChild(ve)}let V=KM(t);if(V.length>0){let ve=eE(V);ve&&E.appendChild(ve)}let ce=t.contentSegments?.length?null:GM(t.contextMentions);if(ce&&E.appendChild(ce),E.appendChild(ee),m&&h==="below"&&t.createdAt){let ve=Cv(t,g);ve.classList.add("persona-mt-1"),E.appendChild(ve)}let ie=t.role==="assistant"?UM(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ve=!!(S&&S.trim()),U=H.placeholder==="skeleton",Ee=U&&H.buffer==="line"&&ve;if(ve)Ee&&E.appendChild(ba());else if(U)E.appendChild(ba());else{let Fe=tE("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);Fe&&E.appendChild(Fe)}}ie&&t.stopReason&&!t.streaming&&(P||(ee.style.display="none"),E.appendChild($M(t.stopReason,ie)));let fe=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,Me=i?.actionEligibility,Le=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Me?.canEdit===!0||o?.showQuote===!0&&Me?.canQuote===!0||xv(o,"user").length>0);if((fe||Le)&&o){let ve=sE(t,Le?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,Me);E.appendChild(ve)}if(!u||t.role==="system")return E;let be=k("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),Je=nE(p,t.role);return v==="right"||v==="left"&&t.role==="user"?be.append(E,Je):be.append(Je,E),be};var iE=40,aE=(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=me(e.name,iE);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(X("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(X("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},Av=(t,e,n={})=>{let o=X("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=X("div",{className:"persona-welcome-head-text"},s,i),p=X("div",{className:"persona-welcome-title-row"},o,c);return{host:X("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}},vi=(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)},id=(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==="",aE(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")},lE="data-persona-welcome-plugin",Mv="data-persona-welcome-overlay",sd="persona-welcome-overlay-active",ng=new WeakMap,og=(t,e,n)=>{n.setAttribute(lE,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(Mv,""),t.classList.contains(sd)||(ng.set(t,t.scrollTop),t.classList.add(sd),t.scrollTop=0)},rg=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(Mv),t.classList.contains(sd)&&(t.classList.remove(sd),t.scrollTop=ng.get(t)??t.scrollTop,ng.delete(t))},Ev=()=>{let t=X("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},ad=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",s=X("div",{className:qa("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(X("div",{className:"persona-flex"},s)),t.hidden=!1},Tv=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,kv=(t,e)=>{if(Tv()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,s=0,i=0,l=0;if(o){let x=getComputedStyle(o);s=parseFloat(x.rowGap)||0;let E=t.previousElementSibling,M=t.nextElementSibling,P=o.getBoundingClientRect().top+(parseFloat(x.borderTopWidth)||0)+(parseFloat(x.paddingTop)||0)-o.scrollTop;i=Math.max(0,E?n.top-E.getBoundingClientRect().bottom-s:n.top-P),l=Math.max(0,M?M.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let p=getComputedStyle(t),g=parseFloat(p.paddingTop)||0,u=parseFloat(p.paddingBottom)||0,m=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${g}px`,paddingBottom:`${u}px`,marginTop:`${i}px`,marginBottom:`${l}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-s}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),v=!1,h=()=>{v||(v=!0,t.style.overflow=c,e(m))};return m.finished.then(h).catch(h),m},Pv=(t,e,n)=>{if(e<=1||Tv()||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 cE="Hello \u{1F44B}",dE="I can answer questions and help you get things done here.",Iv=new WeakSet,gn=(t,e)=>!!t&&t[e]!==void 0,pE=(t,e)=>{!t||t.debug!==!0||!e.length||Iv.has(t)||(Iv.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},nr=t=>{let e=t?.welcome,n=t?.copy,o=gn(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",s=o==="hero"?"on-first-message":gn(e,"dismiss")?e.dismiss:"never",i=[];gn(e,"title")&&gn(n,"welcomeTitle")&&i.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),gn(e,"subtitle")&&gn(n,"welcomeSubtitle")&&i.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),gn(e,"variant")&&gn(n,"showWelcomeCard")&&i.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&gn(e,"message")&&i.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&gn(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=Wa(e?.anchorComposerTop)!==null;return gn(e,"anchorComposerTop")&&!c&&i.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),l!=="center"&&(gn(e,"anchorComposerTop")||gn(e,"composerGap"))&&i.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),pE(t,i),{title:gn(e,"title")?e.title:n?.welcomeTitle??cE,kicker:e?.kicker??"",subtitle:gn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??dE,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()||Xc}},Lv=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ci=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var Hv="16px",ig="10px",ag="14px",Rv=t=>{let e=t?.launcher?.enabled??!0,n=Rt(t);if(Da(t)){let u=t?.launcher?.composerBar??{},m=k("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=u.expandedSize??"anchored",m.style.zIndex=String(t?.launcher?.zIndex??an);let v=k("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");v.style.width="100%",m.appendChild(v);let h=k("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=u.expandedSize??"anchored",h.style.zIndex=String(t?.launcher?.zIndex??an),{wrapper:m,panel:v,pillRoot:h}}if(n){let u=k("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=k("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(m),{wrapper:u,panel:m}}if(!e){let u=k("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=k("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),v=t?.launcher?.width??"100%";return u.style.width=v,m.style.width="100%",u.appendChild(m),{wrapper:u,panel:m}}let s=t?.launcher??{},i=s.position&&On[s.position]?On[s.position]:On["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]"),g=t?.launcher?.width??t?.launcherWidth??tr;return c.style.width=g,c.style.maxWidth=g,l.appendChild(c),{wrapper:l,panel:c}},lg=t=>{let e=X("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Gu(t)}});return e.hidden=!0,e},Wv=(t,e)=>{let n=lg("starter"),o=Av(t,n,{flatShadow:Rt(t)}),s=nr(t);id(o,s),vi(e,o.host,Ci(s,t?.initialMessages));let i=Ev();return ad(i,s.message,t),{welcome:o,greetingHost:i}},uE=(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}=yi(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:Hv,iconSize:ig});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let i=t?.launcher?.clearChat?.enabled??!0,l=null,c=null;if(i){let _=bi(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Hv,iconSize:ag});l=_.button,c=_.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let p=X("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),g=X("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"}});g.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=Wv(t,g),{host:v,title:h,subtitle:x}=u,E=u.starterSuggestions,M=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),F=lg("followUp"),P=Rr(t,!0);P&&(M.style.maxWidth=P,M.style.marginLeft="auto",M.style.marginRight="auto",M.style.width="100%"),g.append(v,m,M,F);let K=X("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),A=od({config:t}),{root:H,textNode:w}=yv();return n.append(p,s,g,K),c&&n.appendChild(c),{container:n,body:g,messagesWrapper:M,starterSuggestions:E,transcriptSuggestions:F,composerOverlay:K,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:v,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:h,introSubtitle:x,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:k("span"),headerTitle:k("span"),headerSubtitle:k("span"),header:p,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:H,peekTextNode:w}},Bv=(t,e=!0)=>{if(Da(t))return uE(t,e);let n=X("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?nd(t,o,{showClose:e}):Cs({config:t,showClose:e}),l=X("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}=Wv(t,l),{host:g,title:u,subtitle:m}=c,v=c.starterSuggestions,h=k("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),x=lg("followUp"),E=Rr(t,!1);E&&(h.style.maxWidth=E,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),l.append(g,p,h,x);let M=Ua({config:t}),F=t?.layout?.showFooter!==!1;s?Fa(n,i,t):(i.header.style.display="none",Fa(n,i,t)),n.append(l);let P=X("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||(M.footer.style.display="none"),n.append(M.footer),n.append(P),{container:n,body:l,messagesWrapper:h,starterSuggestions:v,transcriptSuggestions:x,composerOverlay:P,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,welcomeHost:g,welcomeIconHolder:c.iconHolder,greetingHost:p,introKicker:c.kicker,introTitle:u,introSubtitle:m,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,header:i.header,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode}};var cg=(t,e)=>{let n=k("button");n.type="button",n.innerHTML=`
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 Su=t=>({isError:!0,content:[{type:"text",text:t}]
24
24
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
25
25
  </span>
26
26
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
27
- `,n.addEventListener("click",e);let o=i=>{let l=i.launcher??{},c=Lt(i),p=n.querySelector("[data-role='launcher-title']");if(p){let K=l.title??"Chat Assistant";p.textContent=K,p.setAttribute("title",K)}let g=n.querySelector("[data-role='launcher-subtitle']");if(g){let K=l.subtitle??"Here to help you get answers fast";g.textContent=K,g.setAttribute("title",K)}let u=n.querySelector(".persona-flex-col");u&&(l.textHidden||c?u.style.display="none":u.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 A=parseFloat(K)||24,L=he(l.agentIconName,A*.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 A=0;if(l.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=l.callToActionIconPadding,A=(parseFloat(l.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),l.callToActionIconHidden)h.style.display="none";else if(h.style.display=c?"none":"",h.innerHTML="",l.callToActionIconName){let L=parseFloat(K)||24,w=Math.max(L-A,8),_=he(l.callToActionIconName,w,"currentColor",1.5);_?h.appendChild(_):h.textContent=l.callToActionIconText??"\u2197"}else h.textContent=l.callToActionIconText??"\u2197"}let x=l.position&&_n[l.position]?_n[l.position]:_n["bottom-right"],E="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=c?M:`${E} ${x}`,c||(n.style.zIndex=String(l.zIndex??sn));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}},uE="teaser-dismissed",_v=new Set,Bv=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${uE}`},gE=(t,e)=>{if(_v.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},mE=(t,e)=>{if(_v.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},fE=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,hE=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||Lt(t??{})?null:e},Ov=(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,g=!1,u=!1,f=!1,v=!1,h=()=>(s?.frequency??"once")==="once"&&o.persistState!==!1,x=()=>{p!==null&&(clearTimeout(p),p=null)},E=()=>{!i||!g||(g=!1,i.hidden=!0)},M=Z=>{x(),f=!0,E(),mE(Bv(o),Z&&h())},F=Z=>{!s||f||M(Z==="user"&&g)},P=()=>{p=null,!(!i||f||v)&&(u=!0,g=!0,i.hidden=!1,!(fE()||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||u||v||gE(Bv(o),h())||(x(),p=setTimeout(P,Math.max(0,s.delayMs??0)))},A=()=>{M(h()),e()},L=Z=>{Z.stopPropagation(),M(h())},_=lg(t,()=>{F("user"),e()}),G=()=>{x(),c?.removeEventListener("click",A),l?.removeEventListener("click",L),i?.remove(),i=null,c=null,l=null,g=!1},le=()=>{c=X("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),c.addEventListener("click",A),l=X("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),l.addEventListener("click",L),i=X("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},c,l),n.insertBefore(i,_.element)},ee=()=>{let Z=o.launcher?.position??"bottom-right",V=_n[Z]??_n["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",_.element.style.position="";return}n.className=Wn("persona-launcher-surface",V),n.setAttribute("data-teaser",Z),n.style.zIndex=String(o.launcher?.zIndex??sn),_.element.style.position="static"},S=Z=>{let V=hE(Z);if(s=V,!V){G();return}i||le(),c.textContent=V.text,l.hidden=V.dismissible===!1,l.setAttribute("aria-label",V.dismissLabel??"Dismiss message"),K()},B=Z=>{o=Z,_.update(Z),S(Z),ee()},R=(Z,V="user")=>{v=Z,Z&&F(V)},I=()=>{G(),_.destroy(),n.remove()};return n.appendChild(_.element),t&&(S(t),ee()),{element:n,launcher:_,get teaser(){return i?{element:i,show:P,dismiss:M}:null},setPanelOpen:R,update:B,destroy:I}};var Dv=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:s}=Hv(t),i=Wv(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},g={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:g,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=>{g.footer.replaceWith(v),g.footer=v}}},cg=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>lg(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let s=Ov(t,n);return{instance:s,element:s.element}};var yE=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},bE=(t,e,n)=>`${yE(t)}plugin:${e}:${n}`,Nv=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=>bE(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),g=o();if(g)try{g.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 vE,ChevronUp as CE}from"lucide";var wE=["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"],SE="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",xE="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",AE=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ad=(t,e)=>{let n=k("div",["persona-message-bubble",t,...wE].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},ld=t=>{let e=k("button",t.expandable?SE:xE);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},dg=(t,e,n)=>{t.innerHTML="";let o=Zt(e?CE:vE,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},cd=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=k("div","persona-flex persona-items-center");dg(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},dd=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?.();AE(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},pd=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&dg(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"},ud=(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&&dg(p,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};var Ci=new Set,ME=(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
- `):""},Fv=(t,e)=>{ud(t,e,{stateSet:Ci,previewKind:"reasoning",iconColor:"currentColor"})},pg=(t,e)=>{let n=t.reasoning,o=ad("persona-reasoning-bubble",t.id);if(!n)return o;let s=e?.features?.reasoningDisplay??{},i=s.expandable!==!1,l=i&&Ci.has(t.id),c=n.status!=="complete",p=ME(t,s.previewMaxLines??3),g=ld({expandable:i,expanded:l,bubbleType:"reasoning"}),u=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??{},x=String(n.startedAt??Date.now()),E=()=>{let I=k("span","");return I.setAttribute("data-tool-elapsed",x),I.textContent=uc(n),I},M=h.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:v,previewText:p,isActive:c,config:e??{},elapsed:uc(n),createElapsedElement:E});typeof M=="string"&&M.trim()?(f.textContent=M,u.appendChild(f)):M instanceof HTMLElement?u.appendChild(M):(f.textContent=v,u.appendChild(f));let F=k("span","persona-text-xs persona-text-persona-primary");F.textContent=kh(n),u.appendChild(F);let P=s.loadingAnimation??"none",K=h.activeTextTemplate,A=h.completeTextTemplate,L=c?K:A,w=M instanceof HTMLElement,_=(I,Z)=>{f.textContent="";let V=gc(I,""),ce=0;for(let ie of V){let me=ie.styles.length>0?(()=>{let Te=k("span",ie.styles.map(Le=>`persona-tool-text-${Le}`).join(" "));return f.appendChild(Te),Te})():f;if(ie.isDuration&&c)me.appendChild(E());else{let Te=ie.isDuration?uc(n):ie.text;Z?ce=ri(me,Te,ce):me.appendChild(document.createTextNode(Te))}}};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`),_(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)),_(L,!0))}else _(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 Z=f.textContent||v;f.textContent="",ri(f,Z,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"),Z=he(s.iconName,16,"currentColor",2);Z&&(I.appendChild(Z),g.appendChild(I))}let G="currentColor",le=cd(g,u,{expandable:i,expanded:l,iconColor:G,metaGap:!1}),ee=dd({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(g,ee),o;let S=k("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");S.style.display=l?"":"none";let B=n.chunks.join(""),R=k("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return R.textContent=B||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),S.appendChild(R),pd({expanded:l,header:g,toggleIcon:le,content:S,collapsedPreview:ee,iconColor:G}),o.append(g,ee,S),o};var wi=new Set,Uv=t=>t.toggleTextColor||t.headerTextColor||"var(--persona-primary, #171717)",EE=(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
- `);let s=dc(n.args).trim();return s?s.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,e).join(`
30
- `):""},ug=(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)"},TE=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??"tool-call",i=EE(t,o?.previewMaxLines??3),l=n?Ph(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",p=e?.toolCall??{},g=l;return s==="tool-name"?g=n.name?.trim()||l:s==="tool-preview"&&i&&(g=i),c&&p.activeTextTemplate?g=Zp(n,p.activeTextTemplate,g):!c&&p.completeTextTemplate&&(g=Zp(n,p.completeTextTemplate,g)),{summary:g,previewText:i,isActive:c}},$v=(t,e,n)=>{ud(t,e,{stateSet:wi,previewKind:"tool",iconColor:Uv(n?.toolCall??{})})},gg=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},s=ad("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&&wi.has(t.id),{summary:p,previewText:g,isActive:u}=TE(t,e),f=ld({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 x=String(n.startedAt??Date.now()),E=()=>{let S=k("span","");return S.setAttribute("data-tool-elapsed",x),S.textContent=pc(n),S},M=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:g,collapsedMode:i.collapsedMode??"tool-call",isActive:u,config:e??{},elapsed:pc(n),createElapsedElement:E});typeof M=="string"&&M.trim()?(h.textContent=M,v.appendChild(h)):M instanceof HTMLElement?v.appendChild(M):(h.textContent=p,v.appendChild(h));let F=i.loadingAnimation??"none",P=o.activeTextTemplate,K=o.completeTextTemplate,A=u?P:K,L=M instanceof HTMLElement,w=(S,B)=>{h.textContent="";let R=n.name?.trim()||"tool",I=gc(S,R),Z=0;for(let V of I){let ce=V.styles.length>0?(()=>{let ie=k("span",V.styles.map(me=>`persona-tool-text-${me}`).join(" "));return h.appendChild(ie),ie})():h;if(V.isDuration&&u)ce.appendChild(E());else{let ie=V.isDuration?pc(n):V.text;B?Z=ri(ce,ie,Z):ce.appendChild(document.createTextNode(ie))}}};if(!L)if(u&&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`),A&&w(A,!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)),A)w(A,!0);else{let B=h.textContent||p;h.textContent="",ri(h,B,0)}}else A&&w(A,!1);let _=Uv(o),G=cd(f,v,{expandable:l,expanded:c,iconColor:_,metaGap:!0}),le=dd({bubble:s,previewKind:"tool",expanded:c,isActive:u,previewText:g,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:g,isActive:u,config:e??{}})});if(!l)return s.append(f,le),s;let ee=k("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(ee.style.display=c?"":"none",o.contentBackgroundColor&&(ee.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(ee.style.color=o.contentTextColor),o.contentPaddingX&&(ee.style.paddingLeft=o.contentPaddingX,ee.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(ee.style.paddingTop=o.contentPaddingY,ee.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,ee.appendChild(S)}if(n.args!==void 0){let S=k("div","persona-space-y-1"),B=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Arguments";let 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",ug(R,o),R.textContent=dc(n.args),S.append(B,R),ee.appendChild(S)}if(n.chunks&&n.chunks.length){let S=k("div","persona-space-y-1"),B=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Activity";let 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",ug(R,o),R.textContent=n.chunks.join(""),S.append(B,R),ee.appendChild(S)}if(n.status==="complete"&&n.result!==void 0){let S=k("div","persona-space-y-1"),B=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Result";let 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",ug(R,o),R.textContent=dc(n.result),S.append(B,R),ee.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`,ee.appendChild(S)}return pd({expanded:c,header:f,toggleIcon:G,content:ee,collapsedPreview:le,iconColor:_}),s.append(f,le,ee),s};var{setLoader:FL,load:kE,provide:UL,getSync:PE}=Tt({fallbackImport:()=>import("./approval-ui-RNNBR5R3.js")});var qv=kE;var zv=PE;var{setLoader:zL,load:IE}=Tt({fallbackImport:()=>import("./event-stream-view-73NWKWVQ.js")});var mg=IE;var fg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:XL,load:LE,provide:YL,getSync:HE}=Tt({fallbackImport:()=>import("./artifacts-ui-J6AKUGTS.js")}),Si=null,gd=new Set,jv=t=>{if(Si)return Si;Si=t,t.initArtifactsUi({componentRegistry:Jo});for(let o of fg)Jo.has(o)||Jo.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=ni();e?t.__provideMarkdownParsers(e):ac(()=>{let o=ni();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>_h());let n=[...gd];gd.clear();for(let o of n)try{o()}catch{}return t};var md=()=>LE().then(jv);var nr=()=>{if(Si)return Si;let t=HE();return t?jv(t):null},hg=t=>Si?()=>{}:(gd.add(t),()=>{gd.delete(t)});function gn(t){return t?.features?.artifacts?.enabled===!0}function Vv(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"),!gn(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 RE(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 Kv=["panel","seamless","detached"];function yg(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Kv.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function bg(t){return!t||!gn(t)?!1:yg(t)==="detached"}function qa(t,e){if(!gn(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"),RE(t),Vv(t,e);return}let n=e.features?.artifacts?.layout,o=yg(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 g=c?.trim();g?t.style.setProperty(p,g):t.style.removeProperty(p)}Vv(t,e)}function za(t,e){for(let c of Kv)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"),!gn(e))return;let n=e.features?.artifacts?.layout,o=yg(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 Gv(t,e){return!e||!gn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var WE=new Set(["__proto__","prototype","constructor"]),BE=new Set(["collapsed","card","panel","inline"]),Qv=new Set(["markdown","component"]),_E=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ws=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),hd=t=>!WE.has(t),vg=t=>typeof t=="string"&&BE.has(t),Ss=t=>Object.keys(t).length>0;function Lo(t,e,n,o){t.push({path:e,code:n,message:o})}var OE="Ignored because this key is not part of the persisted preference schema.",fd="Ignored an unsupported value.",DE="Expected collapsed, panel, or inline.",NE='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Xv={kind:"mode",message:fd},xi={kind:"string",message:"Expected a CSS length string."},or={kind:"boolean"},FE={paneWidth:xi,paneMaxWidth:xi,paneMinWidth:xi,expandedPanelWidth:xi,resizableMinWidth:xi,resizableMaxWidth:xi,expandLauncherPanelWhenOpen:or,resizable:or},UE={kind:"object",message:"Expected a preference object.",children:{showToolCalls:or,showReasoning:or,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:fd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:fd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:fd},expandable:or,grouped:or}},reasoningDisplay:{kind:"object",children:{expandable:or,activePreview:or}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Xv,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Xv,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Qv,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Qv}}},filePreview:{kind:"object",children:{enabled:or}},layout:{kind:"object",children:FE}}}}};function Yv(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Lo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Lo(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Lo(o,n,"invalid_value",e.message);case"mode":return vg(t)?Gn(t):Lo(o,n,"invalid_value",e.message);case"modeMap":{if(!ws(t))return Lo(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:si(l);hd(l)&&(s?s.has(l):_E.test(p))?vg(c)?i[p]=Gn(c):Lo(o,`${n}.${l}`,"invalid_value",DE):Lo(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":NE)}return Ss(i)?i:void 0}case"object":{if(e.bareMode&&vg(t))return Gn(t);if(!ws(t))return Lo(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))(!hd(c)||!s.includes(c))&&Lo(o,i(c),"unknown_key",OE);let l={};for(let c of s){let p=e.children[c],g=Yv(t[c],p,i(c),o);if(p.deprecated&&t[c]!==void 0&&Lo(o,i(c),"deprecated_key",p.deprecated),g===void 0)continue;let u=p.alias??c,f=l[u];l[u]=ws(f)&&ws(g)?{...f,...g}:g}return Ss(l)?l:void 0}}}function $E(t){let e=[];return{preferences:(t===null?void 0:Yv(t,UE,"",e))??{},issues:e}}function Ai(t){if(Array.isArray(t))return t.map(Ai);if(!ws(t))return t;let e={};for(let[n,o]of Object.entries(t))hd(n)&&o!==void 0&&(e[n]=Ai(o));return e}function Jv(t,e){let n=Ai(t);for(let[o,s]of Object.entries(e)){if(!hd(o)||s===void 0)continue;let i=n[o];n[o]=ws(i)&&ws(s)?Jv(i,s):Ai(s)}return n}function qE(t){let e={},n;for(let s of t){let i=$E(s).preferences;n=Zv(n,i.artifacts?.display),e=Jv(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function zE(t,e){if(e===void 0)return t===void 0?void 0:Ai(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}:{},...Ss(s)?{byMediaType:s}:{}};return Ss(i)?i:void 0}function Zv(t,e){if(e===void 0)return t===void 0?void 0:Ai(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=zE(n.files,e.files),l={...o?{default:o}:{},...Ss(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return Ss(l)?l:void 0}function jE(t={},e){let n=qE(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=Zv(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 Cg(t){let e=t.preferences;return!e||!Ss(e)?t:{...t,features:jE(t.features??{},[e])}}function VE(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 KE(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 GE(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function QE(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function wg(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 eC(t,e,n,o,s,i,l=200){let c=VE(s,200),p=QE(e,n,o,l);p=Math.max(c,p);let g=KE(i);return g!==null&&(p=Math.min(p,g)),GE(t,c,p)}var{setLoader:rH,load:XE,provide:sH,getSync:YE}=Tt({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var tC=XE;var nC=YE;var Sg=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()}},xg=new Sg;var oC=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),JE=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),rC=(t,e,n)=>{if(!oC(t)||!oC(e)||JE.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]=rC(t[s],e[s],i)}return o};function sC(t,e){let n=rC(t,e,"");return Wc(n)}var iC=()=>{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 ZE=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},eT=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},Mg=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=ZE(t),n=eT(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}},Ag=t=>typeof t=="string"?t:t==null?"":String(t),ja={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Ag(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Ag(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:Ag(n.text)}}},aC=t=>Array.isArray(t)?t.map(e=>String(e)):[],Eg=t=>{let e=new Set(aC(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(aC(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((g,u)=>g||u?.({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 g of t.handlers)if(g)try{let u=()=>{t.emit("action:resubmit",p)},f=g(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});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(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var tT=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}},nT=t=>t.map(e=>({...e,streaming:!1})),oT=t=>t.map(e=>({...e,status:"complete"})),lC=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?tT(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?nT(n.messages):void 0,artifacts:n.artifacts?oT(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 rT=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")},cC=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 rT(t)},sT=async(t,e)=>{let n=await cC(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await cC(`${t}\0${e}`)}`}};var dC=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,p=0,g=null,u=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 g;try{return w.getItem(o)}catch{return l=!0,g}},x=(w,_)=>{if(c||w===g)return;let G=g;g=w,p+=1;let le={previousToken:G,token:w,source:_,revision:p};for(let ee of f)ee(le)},E=w=>{c||w.key!==null&&w.key!==o||x(w.key===null?null:w.newValue??null,"external")},M=(async()=>{let w=await sT(t,e);o=w.storageKey,s=w.leaseKey,i=w.lockName,g=h(),!n&&typeof window<"u"&&window.addEventListener("storage",E)})(),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{}},A=w=>new Promise(_=>{let G=setTimeout(le,w);function le(){clearTimeout(G),window.removeEventListener("storage",ee),_()}function ee(S){(S.key===null||S.key===s)&&le()}window.addEventListener("storage",ee)}),L=async w=>{let _=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;Date.now()<G;){let le=v();if(!le)break;let ee=Date.now(),S=P();if(S&&S.expiresAt>ee&&S.ownerNonce!==_){await A(Math.min(S.expiresAt-ee,500));continue}try{le.setItem(s,JSON.stringify({ownerNonce:_,expiresAt:ee+1e4}))}catch{l=!0;break}if(await F(20+Math.random()*40),P()?.ownerNonce!==_){await A(500);continue}u=_;try{return await w()}finally{u=null,K(_)}}return w()};return{ready:M,async get(){return await M,x(h(),"external"),g},async set(w){await M;let _=v();if(_)try{_.setItem(o,w)}catch{l=!0}x(w,"local")},async clear(){await M;let w=v();if(w)try{w.removeItem(o)}catch{l=!0}x(null,"local")},revision(){return p},subscribe(w){return f.add(w),()=>{f.delete(w)}},async withFirstInitLock(w){await M;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",E),u&&K(u)}}};var{setLoader:fH,load:iT}=Tt({fallbackImport:()=>import("./history-view-BD6OXLNA.js")});var Tg=iT;var kg=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},rr=t=>Object.freeze({...t}),pC=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),uC=t=>t?rr(t):null;function gC(t){let{plugins:e,config:n}=t,o=!1,s=!1,i=!1,l=!1,c=null,p=[],g=()=>{for(let A of p.splice(0))try{A()}catch(L){kg("renderHistoryView cleanup",L)}},u=(A,L)=>{for(let w of e){let _=w[A];if(_)try{let G=_(L);if(G)return G}catch(G){kg(A,G)}}return null},f=()=>({presentation:t.getPresentation(),config:n}),v={header:A=>l?u("renderHistoryHeader",Object.freeze({...f(),returnSurface:t.getReturnSurface(),identityStatus:rr(A.identityStatus),pendingAction:uC(A.pendingAction),copy:rr(A.copy),actions:Object.freeze({close:E.close,startNewConversation:E.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>l?u("renderHistoryConversation",Object.freeze({...f(),conversation:pC(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>l?u("renderHistoryState",Object.freeze({...f(),state:rr(A.state),identityStatus:rr(A.identityStatus),copy:rr(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},h=e.flatMap(A=>(A.railSections??[]).map(L=>({...L,placement:L.placement??"above-conversations",items:[],render:w=>L.render(Object.freeze({collapsed:w,presentation:t.getPresentation(),actions:E}))}))),x=t.createView({slots:v,renderDom:!1,onModelChange:()=>K(),railSections:h}),E=Object.freeze({...x.operations,close:t.close}),M=()=>(l=!0,x.setDomRenderEnabled(!0),x.element),F=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(pC)),activeConversationId:A.activeConversationId,state:rr(A.state),pendingAction:uC(A.pendingAction),identityStatus:rr(A.identityStatus),nextCursor:A.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:rr(x.copy),actions:E,defaultRenderer:M,requestRender:()=>K(),onCleanup:L=>{p.push(L)}}),P=()=>{l=!1;let A=null;for(let w of e)if(w.renderHistoryView){try{A=w.renderHistoryView(F(x.getModel()))}catch(_){kg("renderHistoryView",_),A=null}if(A)break}let L=!A||A.contains(x.element);return l=L,x.setDomRenderEnabled(L),A??x.element};function K(){if(!(!i||o||s)){s=!0;try{g();let A=P();if(A===c)return;let L=c;c=A,t.onElementChanged(A,L)}finally{s=!1}}}return i=!0,K(),{view:x,get element(){return c??x.element},requestRender:K,dispose:()=>{o=!0,g()}}}var aT=null;function mC(){return aT}var lT=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"]]),cT=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."]]),Pg=t=>cT.get(t)??"Conversation history is unavailable right now.";function dT(t){if(t instanceof fs)return t;if(t instanceof Ue){let e=lT.get(t.code)??"unavailable";return new fs(e,Pg(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new fs("unavailable",Pg("unavailable"))}function fC(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 fs("unsupported_scope",Pg("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(g){throw dT(g)}},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 g=await e().getConversation(c,{...p.cursor?{messageCursor:p.cursor}:{},scope:p.context.scope}),u=_y(g.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:g.summary,messages:Aa([],u),conversationRevision:g.conversationRevision??"",nextCursor:g.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 pT="button:not([disabled])";function yd(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=X("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),l=X("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),c=X("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"}},X("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),X("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:s},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),X("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},i,l));for(let g of[i,l])g.style.minHeight="44px",g.style.minWidth="88px",g.style.padding="0 16px",g.style.borderRadius="var(--persona-radius-md, 0.5rem)",g.style.cursor="pointer",g.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=X("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(g=>{let u=!1,f=h=>{u||(u=!0,p.removeEventListener("keydown",v,!0),p.remove(),e?.focus(),g(h))};function v(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),f(!1);return}if(h.key!=="Tab")return;let x=Array.from(c.querySelectorAll(pT));if(x.length===0)return;let E=x[0],M=x[x.length-1],F=document.activeElement;h.shiftKey&&(F===E||!c.contains(F))?(h.preventDefault(),M.focus()):!h.shiftKey&&F===M&&(h.preventDefault(),E.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 EH,STR as TH,OBJ as kH}from"partial-json";function hC(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=Jo.get(t.component);if(!i){if(fg.includes(t.component)){md().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 yC(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 Ig(t){let e=yC(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 bC(t){let e=yC(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 uT=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vC(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:g=uT}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.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 x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,h.appendChild(x);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,h.appendChild(E),v.appendChild(h);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let 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":""}: ${g[w-1]}`),_.title=g[w-1],_.dataset.rating=String(w),_.innerHTML=`
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 g=n.querySelector("[data-role='launcher-subtitle']");if(g){let K=l.subtitle??"Here to help you get answers fast";g.textContent=K,g.setAttribute("title",K)}let u=n.querySelector(".persona-flex-col");u&&(l.textHidden||c?u.style.display="none":u.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(l.agentIconHidden)m.style.display="none";else{let K=l.agentIconSize??"40px";if(m.style.height=K,m.style.width=K,l.agentIconBackgroundColor?(m.style.backgroundColor=l.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",l.agentIconName){let A=parseFloat(K)||24,H=me(l.agentIconName,A*.6,"var(--persona-text-inverse, #ffffff)",1.5);H?(m.appendChild(H),m.style.display=""):(m.textContent=l.agentIconText??"\u{1F4AC}",m.style.display="")}else l.iconUrl?m.style.display="none":(m.textContent=l.agentIconText??"\u{1F4AC}",m.style.display="")}let 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 A=0;if(l.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=l.callToActionIconPadding,A=(parseFloat(l.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),l.callToActionIconHidden)h.style.display="none";else if(h.style.display=c?"none":"",h.innerHTML="",l.callToActionIconName){let H=parseFloat(K)||24,w=Math.max(H-A,8),_=me(l.callToActionIconName,w,"currentColor",1.5);_?h.appendChild(_):h.textContent=l.callToActionIconText??"\u2197"}else h.textContent=l.callToActionIconText??"\u2197"}let x=l.position&&On[l.position]?On[l.position]:On["bottom-right"],E="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=c?M:`${E} ${x}`,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}},gE="teaser-dismissed",Ov=new Set,_v=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${gE}`},fE=(t,e)=>{if(Ov.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},mE=(t,e)=>{if(Ov.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},hE=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,yE=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||Rt(t??{})?null:e},Dv=(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,g=!1,u=!1,m=!1,v=!1,h=()=>(s?.frequency??"once")==="once"&&o.persistState!==!1,x=()=>{p!==null&&(clearTimeout(p),p=null)},E=()=>{!i||!g||(g=!1,i.hidden=!0)},M=Z=>{x(),m=!0,E(),mE(_v(o),Z&&h())},F=Z=>{!s||m||M(Z==="user"&&g)},P=()=>{p=null,!(!i||m||v)&&(u=!0,g=!0,i.hidden=!1,!(hE()||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||m||u||v||fE(_v(o),h())||(x(),p=setTimeout(P,Math.max(0,s.delayMs??0)))},A=()=>{M(h()),e()},H=Z=>{Z.stopPropagation(),M(h())},_=cg(t,()=>{F("user"),e()}),G=()=>{x(),c?.removeEventListener("click",A),l?.removeEventListener("click",H),i?.remove(),i=null,c=null,l=null,g=!1},le=()=>{c=X("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),c.addEventListener("click",A),l=X("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),l.addEventListener("click",H),i=X("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},c,l),n.insertBefore(i,_.element)},ee=()=>{let Z=o.launcher?.position??"bottom-right",V=On[Z]??On["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",_.element.style.position="";return}n.className=Bn("persona-launcher-surface",V),n.setAttribute("data-teaser",Z),n.style.zIndex=String(o.launcher?.zIndex??an),_.element.style.position="static"},S=Z=>{let V=yE(Z);if(s=V,!V){G();return}i||le(),c.textContent=V.text,l.hidden=V.dismissible===!1,l.setAttribute("aria-label",V.dismissLabel??"Dismiss message"),K()},B=Z=>{o=Z,_.update(Z),S(Z),ee()},R=(Z,V="user")=>{v=Z,Z&&F(V)},I=()=>{G(),_.destroy(),n.remove()};return n.appendChild(_.element),t&&(S(t),ee()),{element:n,launcher:_,get teaser(){return i?{element:i,show:P,dismiss:M}:null},setPanelOpen:R,update:B,destroy:I}};var Nv=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:s}=Rv(t),i=Bv(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},g={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:g,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=>{g.footer.replaceWith(v),g.footer=v}}},dg=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>cg(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let s=Dv(t,n);return{instance:s,element:s.element}};var bE=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},vE=(t,e,n)=>`${bE(t)}plugin:${e}:${n}`,Fv=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=>vE(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),g=o();if(g)try{g.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 CE,ChevronUp as wE}from"lucide";var SE=["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"],xE="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",AE="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",ME=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ld=(t,e)=>{let n=k("div",["persona-message-bubble",t,...SE].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},cd=t=>{let e=k("button",t.expandable?xE:AE);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},pg=(t,e,n)=>{t.innerHTML="";let o=tn(e?wE:CE,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},dd=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=k("div","persona-flex persona-items-center");pg(o,n.expanded,n.iconColor);let s=k("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return s.append(o),t.append(e,s),o},pd=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?.();ME(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},ud=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&pg(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},gd=(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&&pg(p,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};var wi=new Set,EE=(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
+ `):""},Uv=(t,e)=>{gd(t,e,{stateSet:wi,previewKind:"reasoning",iconColor:"currentColor"})},ug=(t,e)=>{let n=t.reasoning,o=ld("persona-reasoning-bubble",t.id);if(!n)return o;let s=e?.features?.reasoningDisplay??{},i=s.expandable!==!1,l=i&&wi.has(t.id),c=n.status!=="complete",p=EE(t,s.previewMaxLines??3),g=cd({expandable:i,expanded:l,bubbleType:"reasoning"}),u=k("div","persona-flex persona-flex-col persona-text-left"),m=k("span","persona-text-xs persona-text-persona-primary"),v="Thinking...",h=e?.reasoning??{},x=String(n.startedAt??Date.now()),E=()=>{let I=k("span","");return I.setAttribute("data-tool-elapsed",x),I.textContent=gc(n),I},M=h.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:v,previewText:p,isActive:c,config:e??{},elapsed:gc(n),createElapsedElement:E});typeof M=="string"&&M.trim()?(m.textContent=M,u.appendChild(m)):M instanceof HTMLElement?u.appendChild(M):(m.textContent=v,u.appendChild(m));let F=k("span","persona-text-xs persona-text-persona-primary");F.textContent=kh(n),u.appendChild(F);let P=s.loadingAnimation??"none",K=h.activeTextTemplate,A=h.completeTextTemplate,H=c?K:A,w=M instanceof HTMLElement,_=(I,Z)=>{m.textContent="";let V=fc(I,""),ce=0;for(let ie of V){let fe=ie.styles.length>0?(()=>{let Me=k("span",ie.styles.map(Le=>`persona-tool-text-${Le}`).join(" "));return m.appendChild(Me),Me})():m;if(ie.isDuration&&c)fe.appendChild(E());else{let Me=ie.isDuration?gc(n):ie.text;Z?ce=si(fe,Me,ce):fe.appendChild(document.createTextNode(Me))}}};if(!w&&H)if(F.style.display="none",m.style.display="",c&&P!=="none"){let I=h.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),P==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${I}ms`),_(H,!1)):(m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${I}ms`),P==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor)),_(H,!0))}else _(H,!1);else if(!w&&c&&P!=="none"){m.style.display="";let I=h.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),P==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${I}ms`);else{m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${I}ms`),P==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor));let Z=m.textContent||v;m.textContent="",si(m,Z,0)}n.status==="complete"&&(m.style.display="none")}else w||(n.status==="complete"?m.style.display="none":m.style.display="");if(s.iconName&&!w){let I=k("span","persona-reasoning-header-icon"),Z=me(s.iconName,16,"currentColor",2);Z&&(I.appendChild(Z),g.appendChild(I))}let G="currentColor",le=dd(g,u,{expandable:i,expanded:l,iconColor:G,metaGap:!1}),ee=pd({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(g,ee),o;let S=k("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");S.style.display=l?"":"none";let B=n.chunks.join(""),R=k("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return R.textContent=B||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),S.appendChild(R),ud({expanded:l,header:g,toggleIcon:le,content:S,collapsedPreview:ee,iconColor:G}),o.append(g,ee,S),o};var Si=new Set,$v=t=>t.toggleTextColor||t.headerTextColor||"var(--persona-primary, #171717)",TE=(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
+ `);let s=pc(n.args).trim();return s?s.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,e).join(`
30
+ `):""},gg=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},kE=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??"tool-call",i=TE(t,o?.previewMaxLines??3),l=n?Ih(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",p=e?.toolCall??{},g=l;return s==="tool-name"?g=n.name?.trim()||l:s==="tool-preview"&&i&&(g=i),c&&p.activeTextTemplate?g=eu(n,p.activeTextTemplate,g):!c&&p.completeTextTemplate&&(g=eu(n,p.completeTextTemplate,g)),{summary:g,previewText:i,isActive:c}},qv=(t,e,n)=>{gd(t,e,{stateSet:Si,previewKind:"tool",iconColor:$v(n?.toolCall??{})})},fg=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},s=ld("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&&Si.has(t.id),{summary:p,previewText:g,isActive:u}=kE(t,e),m=cd({expandable:l,expanded:c,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let v=k("div","persona-flex persona-flex-col persona-text-left"),h=k("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(h.style.color=o.headerTextColor);let x=String(n.startedAt??Date.now()),E=()=>{let S=k("span","");return S.setAttribute("data-tool-elapsed",x),S.textContent=uc(n),S},M=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:g,collapsedMode:i.collapsedMode??"tool-call",isActive:u,config:e??{},elapsed:uc(n),createElapsedElement:E});typeof M=="string"&&M.trim()?(h.textContent=M,v.appendChild(h)):M instanceof HTMLElement?v.appendChild(M):(h.textContent=p,v.appendChild(h));let F=i.loadingAnimation??"none",P=o.activeTextTemplate,K=o.completeTextTemplate,A=u?P:K,H=M instanceof HTMLElement,w=(S,B)=>{h.textContent="";let R=n.name?.trim()||"tool",I=fc(S,R),Z=0;for(let V of I){let ce=V.styles.length>0?(()=>{let ie=k("span",V.styles.map(fe=>`persona-tool-text-${fe}`).join(" "));return h.appendChild(ie),ie})():h;if(V.isDuration&&u)ce.appendChild(E());else{let ie=V.isDuration?uc(n):V.text;B?Z=si(ce,ie,Z):ce.appendChild(document.createTextNode(ie))}}};if(!H)if(u&&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`),A&&w(A,!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)),A)w(A,!0);else{let B=h.textContent||p;h.textContent="",si(h,B,0)}}else A&&w(A,!1);let _=$v(o),G=dd(m,v,{expandable:l,expanded:c,iconColor:_,metaGap:!0}),le=pd({bubble:s,previewKind:"tool",expanded:c,isActive:u,previewText:g,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:g,isActive:u,config:e??{}})});if(!l)return s.append(m,le),s;let ee=k("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(ee.style.display=c?"":"none",o.contentBackgroundColor&&(ee.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(ee.style.color=o.contentTextColor),o.contentPaddingX&&(ee.style.paddingLeft=o.contentPaddingX,ee.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(ee.style.paddingTop=o.contentPaddingY,ee.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,ee.appendChild(S)}if(n.args!==void 0){let S=k("div","persona-space-y-1"),B=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Arguments";let R=k("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",gg(R,o),R.textContent=pc(n.args),S.append(B,R),ee.appendChild(S)}if(n.chunks&&n.chunks.length){let S=k("div","persona-space-y-1"),B=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Activity";let R=k("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",gg(R,o),R.textContent=n.chunks.join(""),S.append(B,R),ee.appendChild(S)}if(n.status==="complete"&&n.result!==void 0){let S=k("div","persona-space-y-1"),B=k("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Result";let R=k("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",gg(R,o),R.textContent=pc(n.result),S.append(B,R),ee.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`,ee.appendChild(S)}return ud({expanded:c,header:m,toggleIcon:G,content:ee,collapsedPreview:le,iconColor:_}),s.append(m,le,ee),s};var{setLoader:UL,load:PE,provide:$L,getSync:IE}=Pt({fallbackImport:()=>import("./approval-ui-K7R5Q5OC.js")});var zv=PE;var jv=IE;var{setLoader:jL,load:LE}=Pt({fallbackImport:()=>import("./event-stream-view-FKWDY3UB.js")});var mg=LE;var hg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:YL,load:HE,provide:JL,getSync:RE}=Pt({fallbackImport:()=>import("./artifacts-ui-F4N6VMKF.js")}),xi=null,fd=new Set,Vv=t=>{if(xi)return xi;xi=t,t.initArtifactsUi({componentRegistry:Zo});for(let o of hg)Zo.has(o)||Zo.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=oi();e?t.__provideMarkdownParsers(e):lc(()=>{let o=oi();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Oh());let n=[...fd];fd.clear();for(let o of n)try{o()}catch{}return t};var md=()=>HE().then(Vv);var or=()=>{if(xi)return xi;let t=RE();return t?Vv(t):null},yg=t=>xi?()=>{}:(fd.add(t),()=>{fd.delete(t)});function fn(t){return t?.features?.artifacts?.enabled===!0}function Kv(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"),!fn(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 WE(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 Gv=["panel","seamless","detached"];function bg(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Gv.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function vg(t){return!t||!fn(t)?!1:bg(t)==="detached"}function za(t,e){if(!fn(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"),WE(t),Kv(t,e);return}let n=e.features?.artifacts?.layout,o=bg(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let s=n?.paneBackground?.trim();s?t.style.setProperty("--persona-artifact-pane-bg",s):t.style.removeProperty("--persona-artifact-pane-bg");let i=n?.panePadding?.trim();i?t.style.setProperty("--persona-artifact-pane-padding",i):t.style.removeProperty("--persona-artifact-pane-padding");let l=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[c,p]of l){let g=c?.trim();g?t.style.setProperty(p,g):t.style.removeProperty(p)}Kv(t,e)}function ja(t,e){for(let c of Gv)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"),!fn(e))return;let n=e.features?.artifacts?.layout,o=bg(e);t.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let i=n?.paneShadow?.trim();i&&t.style.setProperty("--persona-artifact-pane-shadow",i);let l=n?.chatShadow?.trim();l&&t.style.setProperty("--persona-artifact-chat-shadow",l)}function Qv(t,e){return!e||!fn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var BE=new Set(["__proto__","prototype","constructor"]),_E=new Set(["collapsed","card","panel","inline"]),Xv=new Set(["markdown","component"]),OE=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ws=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),yd=t=>!BE.has(t),Cg=t=>typeof t=="string"&&_E.has(t),Ss=t=>Object.keys(t).length>0;function Lo(t,e,n,o){t.push({path:e,code:n,message:o})}var DE="Ignored because this key is not part of the persisted preference schema.",hd="Ignored an unsupported value.",NE="Expected collapsed, panel, or inline.",FE='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Yv={kind:"mode",message:hd},Ai={kind:"string",message:"Expected a CSS length string."},rr={kind:"boolean"},UE={paneWidth:Ai,paneMaxWidth:Ai,paneMinWidth:Ai,expandedPanelWidth:Ai,resizableMinWidth:Ai,resizableMaxWidth:Ai,expandLauncherPanelWhenOpen:rr,resizable:rr},$E={kind:"object",message:"Expected a preference object.",children:{showToolCalls:rr,showReasoning:rr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:hd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:hd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:hd},expandable:rr,grouped:rr}},reasoningDisplay:{kind:"object",children:{expandable:rr,activePreview:rr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Yv,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Yv,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Xv,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Xv}}},filePreview:{kind:"object",children:{enabled:rr}},layout:{kind:"object",children:UE}}}}};function Jv(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Lo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Lo(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Lo(o,n,"invalid_value",e.message);case"mode":return Cg(t)?Qn(t):Lo(o,n,"invalid_value",e.message);case"modeMap":{if(!ws(t))return Lo(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:ii(l);yd(l)&&(s?s.has(l):OE.test(p))?Cg(c)?i[p]=Qn(c):Lo(o,`${n}.${l}`,"invalid_value",NE):Lo(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":FE)}return Ss(i)?i:void 0}case"object":{if(e.bareMode&&Cg(t))return Qn(t);if(!ws(t))return Lo(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))(!yd(c)||!s.includes(c))&&Lo(o,i(c),"unknown_key",DE);let l={};for(let c of s){let p=e.children[c],g=Jv(t[c],p,i(c),o);if(p.deprecated&&t[c]!==void 0&&Lo(o,i(c),"deprecated_key",p.deprecated),g===void 0)continue;let u=p.alias??c,m=l[u];l[u]=ws(m)&&ws(g)?{...m,...g}:g}return Ss(l)?l:void 0}}}function qE(t){let e=[];return{preferences:(t===null?void 0:Jv(t,$E,"",e))??{},issues:e}}function Mi(t){if(Array.isArray(t))return t.map(Mi);if(!ws(t))return t;let e={};for(let[n,o]of Object.entries(t))yd(n)&&o!==void 0&&(e[n]=Mi(o));return e}function Zv(t,e){let n=Mi(t);for(let[o,s]of Object.entries(e)){if(!yd(o)||s===void 0)continue;let i=n[o];n[o]=ws(i)&&ws(s)?Zv(i,s):Mi(s)}return n}function zE(t){let e={},n;for(let s of t){let i=qE(s).preferences;n=eC(n,i.artifacts?.display),e=Zv(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function jE(t,e){if(e===void 0)return t===void 0?void 0:Mi(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}:{},...Ss(s)?{byMediaType:s}:{}};return Ss(i)?i:void 0}function eC(t,e){if(e===void 0)return t===void 0?void 0:Mi(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=jE(n.files,e.files),l={...o?{default:o}:{},...Ss(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return Ss(l)?l:void 0}function VE(t={},e){let n=zE(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=eC(s.display,n.artifacts.display);l!==void 0&&(i.display=l)}n.artifacts.filePreview&&(i.filePreview={...s.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...s.layout,...n.artifacts.layout}),o.artifacts=i}return o}function wg(t){let e=t.preferences;return!e||!Ss(e)?t:{...t,features:VE(t.features??{},[e])}}function KE(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 GE(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 QE(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function XE(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function Sg(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let i=/^([\d.]+)/.exec(o);return i?Number(i[1]):8}function tC(t,e,n,o,s,i,l=200){let c=KE(s,200),p=XE(e,n,o,l);p=Math.max(c,p);let g=GE(i);return g!==null&&(p=Math.min(p,g)),QE(t,c,p)}var{setLoader:sH,load:YE,provide:iH,getSync:JE}=Pt({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var nC=YE;var oC=JE;var xg=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(i=>i.id));return[...n.filter(i=>!o.has(i.id)),...e].sort((i,l)=>(l.priority??0)-(i.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Ag=new xg;var rC=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"]),sC=(t,e,n)=>{if(!rC(t)||!rC(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]=sC(t[s],e[s],i)}return o};function iC(t,e){let n=sC(t,e,"");return Bc(n)}var aC=()=>{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 eT=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},tT=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let s=n;s<e.length;s+=1){let i=e[s];if(i==="{"&&(o+=1),i==="}"&&(o-=1,o===0))return e.slice(n,s+1)}return null},Eg=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=eT(t),n=tT(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...i}=o;return{type:String(s),payload:i,raw:o}}catch{return null}},Mg=t=>typeof t=="string"?t:t==null?"":String(t),Va={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Mg(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Mg(n.element);if(o&&e.document?.querySelector){let s=e.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Mg(n.text)}}},lC=t=>Array.isArray(t)?t.map(e=>String(e)):[],Tg=t=>{let e=new Set(lC(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(lC(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((g,u)=>g||u?.({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 g of t.handlers)if(g)try{let u=()=>{t.emit("action:resubmit",p)},m=g(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let v=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:v,resubmit:m.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var nT=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}},oT=t=>t.map(e=>({...e,streaming:!1})),rT=t=>t.map(e=>({...e,status:"complete"})),cC=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?nT(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?oT(n.messages):void 0,artifacts:n.artifacts?rT(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 sT=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")},dC=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 sT(t)},iT=async(t,e)=>{let n=await dC(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await dC(`${t}\0${e}`)}`}};var pC=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,p=0,g=null,u=null,m=new Set,v=()=>{if(n||l)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return l=!0,null}},h=()=>{let w=v();if(!w)return g;try{return w.getItem(o)}catch{return l=!0,g}},x=(w,_)=>{if(c||w===g)return;let G=g;g=w,p+=1;let le={previousToken:G,token:w,source:_,revision:p};for(let ee of m)ee(le)},E=w=>{c||w.key!==null&&w.key!==o||x(w.key===null?null:w.newValue??null,"external")},M=(async()=>{let w=await iT(t,e);o=w.storageKey,s=w.leaseKey,i=w.lockName,g=h(),!n&&typeof window<"u"&&window.addEventListener("storage",E)})(),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{}},A=w=>new Promise(_=>{let G=setTimeout(le,w);function le(){clearTimeout(G),window.removeEventListener("storage",ee),_()}function ee(S){(S.key===null||S.key===s)&&le()}window.addEventListener("storage",ee)}),H=async w=>{let _=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;Date.now()<G;){let le=v();if(!le)break;let ee=Date.now(),S=P();if(S&&S.expiresAt>ee&&S.ownerNonce!==_){await A(Math.min(S.expiresAt-ee,500));continue}try{le.setItem(s,JSON.stringify({ownerNonce:_,expiresAt:ee+1e4}))}catch{l=!0;break}if(await F(20+Math.random()*40),P()?.ownerNonce!==_){await A(500);continue}u=_;try{return await w()}finally{u=null,K(_)}}return w()};return{ready:M,async get(){return await M,x(h(),"external"),g},async set(w){await M;let _=v();if(_)try{_.setItem(o,w)}catch{l=!0}x(w,"local")},async clear(){await M;let w=v();if(w)try{w.removeItem(o)}catch{l=!0}x(null,"local")},revision(){return p},subscribe(w){return m.add(w),()=>{m.delete(w)}},async withFirstInitLock(w){await M;let _=globalThis.navigator?.locks;return _?.request?_.request(i,()=>w()):v()?H(w):w()},matches(w,_,G){return w===t&&_===e&&G===n},destroy(){c=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",E),u&&K(u)}}};var{setLoader:hH,load:aT}=Pt({fallbackImport:()=>import("./history-view-BD6OXLNA.js")});var kg=aT;var Pg=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},sr=t=>Object.freeze({...t}),uC=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),gC=t=>t?sr(t):null;function fC(t){let{plugins:e,config:n}=t,o=!1,s=!1,i=!1,l=!1,c=null,p=[],g=()=>{for(let A of p.splice(0))try{A()}catch(H){Pg("renderHistoryView cleanup",H)}},u=(A,H)=>{for(let w of e){let _=w[A];if(_)try{let G=_(H);if(G)return G}catch(G){Pg(A,G)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),v={header:A=>l?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:sr(A.identityStatus),pendingAction:gC(A.pendingAction),copy:sr(A.copy),actions:Object.freeze({close:E.close,startNewConversation:E.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>l?u("renderHistoryConversation",Object.freeze({...m(),conversation:uC(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>l?u("renderHistoryState",Object.freeze({...m(),state:sr(A.state),identityStatus:sr(A.identityStatus),copy:sr(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},h=e.flatMap(A=>(A.railSections??[]).map(H=>({...H,placement:H.placement??"above-conversations",items:[],render:w=>H.render(Object.freeze({collapsed:w,presentation:t.getPresentation(),actions:E}))}))),x=t.createView({slots:v,renderDom:!1,onModelChange:()=>K(),railSections:h}),E=Object.freeze({...x.operations,close:t.close}),M=()=>(l=!0,x.setDomRenderEnabled(!0),x.element),F=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(uC)),activeConversationId:A.activeConversationId,state:sr(A.state),pendingAction:gC(A.pendingAction),identityStatus:sr(A.identityStatus),nextCursor:A.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:sr(x.copy),actions:E,defaultRenderer:M,requestRender:()=>K(),onCleanup:H=>{p.push(H)}}),P=()=>{l=!1;let A=null;for(let w of e)if(w.renderHistoryView){try{A=w.renderHistoryView(F(x.getModel()))}catch(_){Pg("renderHistoryView",_),A=null}if(A)break}let H=!A||A.contains(x.element);return l=H,x.setDomRenderEnabled(H),A??x.element};function K(){if(!(!i||o||s)){s=!0;try{g();let A=P();if(A===c)return;let H=c;c=A,t.onElementChanged(A,H)}finally{s=!1}}}return i=!0,K(),{view:x,get element(){return c??x.element},requestRender:K,dispose:()=>{o=!0,g()}}}var lT=null;function mC(){return lT}var cT=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"]]),dT=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),Ig=t=>dT.get(t)??"Conversation history is unavailable right now.";function pT(t){if(t instanceof ms)return t;if(t instanceof Ne){let e=cT.get(t.code)??"unavailable";return new ms(e,Ig(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new ms("unavailable",Ig("unavailable"))}function hC(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 ms("unsupported_scope",Ig("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(g){throw pT(g)}},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 g=await e().getConversation(c,{...p.cursor?{messageCursor:p.cursor}:{},scope:p.context.scope}),u=Oy(g.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:g.summary,messages:Ma([],u),conversationRevision:g.conversationRevision??"",nextCursor:g.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 uT="button:not([disabled])";function bd(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=X("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),l=X("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),c=X("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"}},X("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),X("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:s},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),X("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},i,l));for(let g of[i,l])g.style.minHeight="44px",g.style.minWidth="88px",g.style.padding="0 16px",g.style.borderRadius="var(--persona-radius-md, 0.5rem)",g.style.cursor="pointer",g.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=X("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(g=>{let u=!1,m=h=>{u||(u=!0,p.removeEventListener("keydown",v,!0),p.remove(),e?.focus(),g(h))};function v(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let x=Array.from(c.querySelectorAll(uT));if(x.length===0)return;let E=x[0],M=x[x.length-1],F=document.activeElement;h.shiftKey&&(F===E||!c.contains(F))?(h.preventDefault(),M.focus()):!h.shiftKey&&F===M&&(h.preventDefault(),E.focus())}p.addEventListener("keydown",v,!0),p.addEventListener("pointerdown",h=>{h.target===p&&m(!1)}),i.addEventListener("click",()=>m(!1)),l.addEventListener("click",()=>m(!0)),t.host.appendChild(p),i.focus()})}import{parse as TH,STR as kH,OBJ as PH}from"partial-json";function yC(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=Zo.get(t.component);if(!i){if(hg.includes(t.component)){md().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 bC(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Lg(t){let e=bC(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 vC(t){let e=bC(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 gT=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function CC(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:g=gT}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,v=document.createElement("div");v.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,h.appendChild(x);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,h.appendChild(E),v.appendChild(h);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let 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":""}: ${g[w-1]}`),_.title=g[w-1],_.dataset.rating=String(w),_.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,le)=>{let ee=le<w;G.classList.toggle("selected",ee),G.setAttribute("aria-checked",le===w-1?"true":"false")})}),F.push(_),M.appendChild(_)}v.appendChild(M);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 A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=c,A.addEventListener("click",()=>{n?.(),u.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){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.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),u.remove()}catch(w){L.disabled=!1,L.textContent=l,console.error("[CSAT Feedback] Failed to submit:",w)}}),K.appendChild(A),K.appendChild(L),v.appendChild(K),u.appendChild(v),u}function CC(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:g="Not likely",highLabel:u="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 x=document.createElement("div");x.className="persona-feedback-header";let E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=o,x.appendChild(E);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,x.appendChild(M),h.appendChild(x);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=g;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,P.appendChild(K),P.appendChild(A);let L=document.createElement("div");L.className="persona-feedback-numbers";let w=[];for(let S=0;S<=10;S++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-number-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`Rating ${S} out of 10`),B.textContent=String(S),B.dataset.rating=String(S),S<=6?B.classList.add("persona-feedback-detractor"):S<=8?B.classList.add("persona-feedback-passive"):B.classList.add("persona-feedback-promoter"),B.addEventListener("click",()=>{v=S,w.forEach((R,I)=>{R.classList.toggle("selected",I===S),R.setAttribute("aria-checked",I===S?"true":"false")})}),w.push(B),L.appendChild(B)}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 le=document.createElement("button");le.type="button",le.className="persona-feedback-btn persona-feedback-btn-skip",le.textContent=c,le.addEventListener("click",()=>{n?.(),f.remove()});let ee=document.createElement("button");return ee.type="button",ee.className="persona-feedback-btn persona-feedback-btn-submit",ee.textContent=l,ee.addEventListener("click",async()=>{if(v===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}ee.disabled=!0,ee.textContent="Submitting...";try{let S=_?.value.trim()||void 0;await e(v,S),f.remove()}catch(S){ee.disabled=!1,ee.textContent=l,console.error("[NPS Feedback] Failed to submit:",S)}}),G.appendChild(le),G.appendChild(ee),h.appendChild(G),f.appendChild(h),f}var Mi="persona-chat-history",fT=30*1e3,hT=641,Ei="data-persona-composer-reason",yT={"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 bT(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=yT[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 bd(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 vT(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 CT(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Lg=t=>!t||typeof t!="object"?{}:{...t},AC=t=>t.map(e=>({...e,streaming:!1})),MC=(t,e,n)=>{let o=t?.markdown?xh(t.markdown):null,s=Ah(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??"",g=c.message.rawContent??null;if(e){let v=e.process({text:p,raw:g??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 u=ni()!==null,f;if(t?.postprocessMessage){let v=t.postprocessMessage({...c,text:p,raw:g??c.text??""});f=s?s(v):v}else if(o){let v=c.streaming?oy(p):p,h=o(v);f=s&&u?s(h):h}else f=lc(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)),lc(c.text??"")}}};function EC(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 wT=(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},ST=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:wT(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),TC=(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=Wc(e),s=()=>{ab({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};s();let i=o.features;o=Cg(o);let l=xg.getForInstance(o.plugins),c=rv(t),p=[],g=!1,u=Nv(()=>o),f=null,v=null,h=null,x=!1,E=null,M=r=>{f=r,r.initApprovalUi({webMcpToolTitle:cc});let a=r.createBuiltInApprovalPlugin();v=a.plugin,h=a.teardown},F=()=>{if(f)return f;let r=zv();return r?(M(r),r):(qv().then(a=>{x||f||(M(a),E?.())}).catch(()=>{}),null)},P=!1,K=!1,A=null,L=(r,a,d,m)=>{if(!r.querySelector("[data-tv-form]"))return;let y=nC();if(y){y.enhanceWithForms(r,a,d,m);return}tC().then(()=>{P||K||!A||(K=!0,A())}).catch(()=>{})};o.components&&Jo.registerAll(o.components);let w=iC(),G=o.persistState===!1?null:o.storageAdapter??lC(),le=!!o.clientToken&&typeof o.reconnectStream!="function",ee={},S=null,B,R=new Promise(r=>{B=r}),I,Z=!1,V=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&&(Z=!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")S=r.then(a=>V(a??{messages:[],metadata:{}}));else{let d=V(r??{messages:[],metadata:{}});d.metadata&&(ee=Lg(d.metadata)),d.messages?.length&&(o={...o,initialMessages:d.messages}),d.artifacts?.length&&(o={...o,initialArtifacts:d.artifacts,initialSelectedArtifactId:d.selectedArtifactId??null}),I=d.draft}}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",r)}else if(o.onStateLoaded)try{let r=V({messages:[],metadata:{}});r.messages?.length&&(o={...o,initialMessages:r.messages})}catch(r){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",r)}S||B();let ce=()=>ee,ie=r=>{ee=r({...ee})??{},Os()},me=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Mg],Te=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ja.message,ja.messageAndClick],Le=Eg({parsers:me,handlers:Te,getSessionMetadata:ce,updateSessionMetadata:ie,emit:w.emit,documentRef:typeof document<"u"?document:null});Le.syncFromMetadata();let Ce=o.launcher?.enabled??!0,Ze=o.launcher?.autoExpand??!1,we=o.autoFocusInput??!1,U=Ze,ke=Ce,$e=o.layout?.header?.layout,mt=!1,Re=()=>Oa(o),Ie=()=>Ce||Re(),be=Re()?!1:Ce?Ze:!0,lo=!1,co=null,xs=()=>{lo=!0,co&&clearTimeout(co),co=setTimeout(()=>{lo&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),lo=!1)},1e4)},kt=MC(o,Le,xs),po=o.features?.showReasoning??!0,On=o.features?.showToolCalls??!0,en=o.features?.showEventStreamToggle??!1,uo=o.features?.scrollToBottom??{},Dn=o.features?.scrollBehavior??{},Yn=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",go=`${Yn()}event-stream`,Ho=null,Br=o.features?.eventStream?.maxEvents??2e3,et=null,xn=null,Jn=null,D=!1,Q=null,b=!1,O=null,N=0,$=(r,a)=>{et?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:r,timestamp:Date.now(),payload:JSON.stringify(a)})},te=(r,a)=>{xn?.processEvent(r,a),et?$(r,a):Jn&&(Jn.length>=Br&&Jn.shift(),Jn.push({type:r,payload:a}))},re=()=>{et||!en||(Jn??(Jn=[]),mg().then(r=>{if(D||et||!en)return;Ho=new r.EventStreamStore(go),et=new r.EventStreamBuffer(Br,Ho),xn=xn??new r.ThroughputTracker,Ho.open().then(()=>et?.restore()).catch(d=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",d)});let a=Jn??[];Jn=null;for(let d of a)xn?.processEvent(d.type,d.payload),$(d.type,d.payload)}).catch(()=>{}))};en&&re();let ae=!1,de=null,Ot=()=>{},Be=()=>{},Pt=()=>{},wt=()=>{},Ro=()=>{},sr=()=>b||ae&&de==="panel",Dt={onCopy:r=>{w.emit("message:copy",r),T?.isClientTokenMode()&&T.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),T?.isClientTokenMode()&&T.submitMessageFeedback(r.messageId,r.type).catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",a)}),o.messageActions?.onFeedback?.(r)}},Nt=o.statusIndicator??{},mn=r=>r==="idle"?Nt.idleText??_t.idle:r==="connecting"?Nt.connectingText??_t.connecting:r==="connected"?Nt.connectedText??_t.connected:r==="error"?Nt.errorText??_t.error:r==="paused"?Nt.pausedText??_t.paused:r==="resuming"?Nt.resumingText??_t.resuming:_t[r];function Ka(r,a,d,m){if(!r.hasAttribute(Ei))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 An=Dv({config:o,showClose:Ie()}),{wrapper:Ke,panel:xe,pillRoot:Vt}=An.shell,Ne=An.panelElements,{container:ue,body:ne,messagesWrapper:Pe,starterSuggestions:Cd,transcriptSuggestions:ki,suggestions:ir,textarea:pe,sendButton:Ae,composerForm:Zn,statusText:st,welcomeHost:fn,welcomeIconHolder:NC,greetingHost:Mn,introKicker:FC,introTitle:UC,introSubtitle:$C,closeButton:qe,iconHolder:St,headerTitle:ar,headerSubtitle:_r,header:Me,footer:He,actionsRow:qC}=Ne,wd=Ne.leftActions,Ga=Ne.rightActions,mo=Ne.sendButtonWrapper,Dg=Ne.setSendButtonMode,oe=Ne.micButton,En=Ne.micButtonWrapper,vt=Ne.attachmentButton,hn=Ne.attachmentButtonWrapper,gt=Ne.attachmentInput,yn=Ne.attachmentPreviewsContainer;ue.classList.add("persona-relative"),ne.classList.add("persona-relative");let zC=12,Pi=()=>uo.label??"",jC=()=>uo.iconName??"arrow-down",VC=()=>uo.enabled!==!1,Tn=()=>Dn.mode??"anchor-top",lr=()=>Tn()==="follow"||Tn()==="anchor-top"&&Ni,Ii=()=>Dn.anchorTopOffset??16,KC=()=>Dn.restorePosition??"bottom",Ng=()=>Dn.pauseOnInteraction===!0,Fg=()=>Dn.showActivityWhilePinned!==!1,Ug=()=>Dn.announce===!0,Sd=()=>Dn.scrollbar??"on-scroll",Ht=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");Ht.type="button",Ht.style.display="none",Ht.setAttribute("data-persona-scroll-to-bottom","true");let Li=k("span","persona-flex persona-items-center"),xd=k("span",""),Or=k("span","");Or.setAttribute("data-persona-scroll-to-bottom-count",""),Or.style.display="none",Ht.append(Li,xd,Or),ue.appendChild(Ht);let Nn=k("div","persona-stream-anchor-spacer");Nn.setAttribute("aria-hidden","true"),Nn.setAttribute("data-persona-anchor-spacer",""),Nn.style.flexShrink="0",Nn.style.pointerEvents="none",Nn.style.height="0px",Nn.style.display="none",ne.appendChild(Nn);let Wo=k("div","persona-sr-only");Wo.setAttribute("aria-live","polite"),Wo.setAttribute("aria-atomic","true"),Wo.setAttribute("role","status"),Wo.setAttribute("data-persona-live-region",""),Object.assign(Wo.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"}),ue.appendChild(Wo);let Hi=null,Qa=null,Xa=r=>{!Ug()||!r||(Qa=r,Hi===null&&(Hi=setTimeout(()=>{Hi=null,Qa&&Ug()&&(Wo.textContent=Qa),Qa=null},400)))},Ya="empty",Ja=0,Ad=()=>Ja||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Dr=()=>{let a=He.style.display==="none"?0:He.offsetHeight;Ht.style.bottom=`${a+Ad()+zC}px`};Dr();let Md=()=>{Ps||(He.style.marginBottom=Ja>0?`${Ja}px`:"")},Za=()=>{let r=$u(o,Re()),a=tr(o),m=He.style.display==="none"?0:He.offsetHeight,y=a.anchor==="center"&&Ya==="empty"?Ra(a.anchorComposerTop)??Ra("44%"):null,C=y===null||Re()?0:tv({columnHeight:ue.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`),Ja=r==="block"?C:0,Md(),Dr()},$g=()=>{let r=!!Pi();Ht.setAttribute("aria-label",Pi()||"Jump to latest"),Ht.title=Pi(),Ht.setAttribute("data-persona-scroll-to-bottom-has-label",r?"true":"false"),Li.innerHTML="";let a=he(jC(),"14px","currentColor",2);a?(Li.appendChild(a),Li.style.display=""):Li.style.display="none",xd.textContent=Pi(),xd.style.display=r?"":"none"};$g();let Ye=null,It=null,Se=tb(),GC=r=>{try{ue.dispatchEvent(new CustomEvent("persona:composer:state",{detail:r,bubbles:!0,composed:!0}))}catch{}};Se.subscribe(GC);let fo=()=>{Se.setText(pe?.value??"")},Nr=()=>{Se.setMentionRefs(It?.getMentionRefs()??[])},QC=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}),qg=r=>{let a=Object.freeze(r.map(QC));Se.setAttachments(a);try{o.attachments?.onChange?.(a)}catch(d){console.error("[AgentWidget] attachments.onChange failed:",d)}Yd()};Se.setSelectedModelId(o.composer?.selectedModelId);let Ri=()=>o.composer?.modes??[],Ms=()=>Pb(Ri(),o.composer?.modeGroups);{let r=jc(o.composer?.defaultActiveModeIds??[],Ri());r.length&&Se.setActiveModeIds(r)}function zg(r){if(Se.getState().selectedModelId!==r){Se.setSelectedModelId(r),cr?.repaint();try{o.composer?.onModelChange?.(r)}catch(a){console.error("[AgentWidget] composer.onModelChange failed:",a)}}}function el(r){Se.setActiveModeIds(r),Bo?.render(r,Ms()),Es.forEach(a=>a.repaint()),yo?.resolve(),Ml(),eo()}function Ed(r){el(Ib(Se.getState().activeModeIds,r,Ri(),o.composer?.modeGroups))}let cr=null,Td=null,Bo=null,Es=new Map,dr=null;function ho(r){Se.setQuote(r),dr?.render(Se.getState().quote),eo(),_m()}let jg=!1;function kd(){let r=o.composer?.streamingSubmitBehavior??"block";return r!=="interrupt"?r:o.clientToken?"interrupt":(!jg&&o.debug===!0&&(jg=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let pr=null;function Ts(r){Se.setPendingSubmission(r),pr?.render(Se.getState().pendingSubmission),eo()}let XC=r=>{let a=Es.get(r);if(a)return a;let d=Rb({groupId:r,getGroup:()=>o.composer?.modeGroups?.find(m=>m.id===r),getModes:()=>Ri().filter(m=>m.groupId===r),getActiveIds:()=>Se.getState().activeModeIds,onSelect:m=>Ed(m)});return Es.set(r,d),d},YC=()=>{let r=[],a=Se.getState().activeModeIds,d=new Set;if(Ri().forEach((m,y)=>{if(zc(m.groupId,o.composer?.modeGroups)){let C=m.groupId;if(d.has(C))return;d.add(C);let W=XC(C);W.action.order=Ou(y),W.action.label=o.composer?.modeGroups?.find(z=>z.id===C)?.label??C,r.push(W.action);return}r.push({id:Tb(m.id),kind:"button",placement:"start",order:Ou(y),presentation:m.presentation??"auto",label:m.label,shortLabel:m.shortLabel,iconName:m.iconName,pressed:a.includes(m.id),onSelect:()=>Ed(m.id)})}),o.composer?.models?.length&&!l.some(m=>m.renderComposer)){let m=o.composer?.modelPicker?.presentation??"native";(!cr||Td!==m)&&(Td=m,cr=Mb({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Se.getState().selectedModelId,onSelect:y=>zg(y),presentation:m,getSuffix:()=>o.composer?.modelPicker?.suffix})),r.push(cr.action)}return r},Pd=null,Vg=l.find(r=>r.renderHeader);if(Vg?.renderHeader){let r=Vg.renderHeader({config:o,defaultRenderer:()=>{let a=Cs({config:o,showClose:Ie()});return Na(ue,a,o),a.header},onClose:()=>ct(!1,"user")});if(r){let a=Me;a&&(a.replaceWith(r),Me=r,An.header.element=r)}}let Kg=()=>{Q&&(ne.style.display="none",He.parentNode?.insertBefore(Q.element,He),Q.update())},Id=()=>{if(!et){re();return}if(b=!0,Q?Kg():mg().then(a=>{Q||!b||!et||(Q=a.createEventStreamView({buffer:et,getFullHistory:()=>et.getAllFromStore(),onClose:()=>ks(),config:o,plugins:l,getThroughput:()=>xn?.getMetric()??{status:"idle"},renderIconByName:he}),Kg())}).catch(()=>{ks()}),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${pn.actionIconColor}`;let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(d=>d&&tt.classList.add(d))}let r=()=>{if(!b)return;let a=Date.now();a-N>=200&&(Q?.update(),N=a),O=requestAnimationFrame(r)};N=0,O=requestAnimationFrame(r),Ut(),w.emit("eventStream:opened",{timestamp:Date.now()})},ks=()=>{if(b){if(b=!1,Q&&Q.element.remove(),ne.style.display="",tt){tt.style.boxShadow="";let r=o.features?.eventStream?.classNames?.toggleButtonActive;r&&r.split(/\s+/).forEach(a=>a&&tt.classList.remove(a))}O!==null&&(cancelAnimationFrame(O),O=null),Ut(),w.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(en){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:"");tt=k("button",a),tt.style.width="28px",tt.style.height="28px",tt.style.color=pn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let d=Zt(wC,"18px","currentColor",1.5);d&&tt.appendChild(d);let m=Ne.clearChatButtonWrapper,y=Ne.closeButtonWrapper,C=m||y;C&&C.parentNode===Me?Me.insertBefore(tt,C):Me.appendChild(tt),tt.addEventListener("click",()=>{b?ks():Id()})}let Gg=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??Zo).join(","),y.multiple=(a.maxFiles??4)>1,y.style.display="none",y.setAttribute("aria-label",a.buttonTooltipText??"Attach files"),r.appendChild(y)}},Ps=!1,Qg=r=>{let a=l.find(y=>y.renderComposer);if(!a?.renderComposer)return null;let d=o.composer,m=g?T.isStreaming():!1;return a.renderComposer({config:o,defaultRenderer:r,requestRender:()=>ch(),storage:u(a.id),onSubmit:y=>{!T||T.isStreaming()||Jl(y.trim(),{consumeDraft:!1})},streaming:m,disabled:m,openAttachmentPicker:()=>{br()||gt?.click()},models:d?.models,selectedModelId:Se.getState().selectedModelId??d?.selectedModelId,onModelChange:y=>zg(y),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Pd?.()}:void 0})},Xg=Qg(()=>Fa({config:o}).footer);Xg&&(An.replaceComposer(Xg),He=An.composer.footer,Ps=!0);let nt=null,JC=r=>{Zn=r.form,pe=r.input,mo=r.sendButton?r.sendButton.parentElement:null,r.sendButton&&(Ae=r.sendButton),r.micButton&&(oe=r.micButton,En=r.micButton.parentElement),r.found.status&&(st=r.found.status),r.found.suggestions&&(ir=r.found.suggestions),r.attachmentButton&&(vt=r.attachmentButton,hn=r.attachmentButton.parentElement),gt=r.attachmentInput??null,yn=r.attachmentPreviews??null,r.found.actionsRow&&(qC=r.found.actionsRow),wd=r.found.actionsStart,Ga=r.found.actionsEnd};function Ld(){let r=pe;if(!r)return;let a=o.composer?.inputAttributes,d=!a?.ariaLabel&&!(r instanceof HTMLTextAreaElement)?r.getAttribute("aria-label"):null;Oc(r,a),d&&r.setAttribute("aria-label",d),_c(r,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Ia(r)}),gb(r,Bc(o.composer?.maxLines,Re()?5:3))}let Yg=r=>{nt=ob(r,{debug:o.debug===!0}),nt&&JC(nt),Ld()};Gg(He),Yg(He),fo();let Wi=Rr(o,Re());Wi&&(Pe.style.maxWidth=Wi,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",Mn.style.maxWidth=Wi,Mn.style.marginLeft="auto",Mn.style.marginRight="auto",Mn.style.width="100%",Cd.style.maxWidth=Wi,ki.style.maxWidth=Wi,ki.style.marginLeft="auto",ki.style.marginRight="auto",ki.style.width="100%");let Jg=()=>{let r=Rr(o,Re());if(!(!r||Re()))for(let a of[Zn,ir,yn,st])a&&(a.style.maxWidth=r,a.style.marginLeft="auto",a.style.marginRight="auto",a.style.width="100%")};Jg();let Zg=()=>{!o.attachments?.enabled||!gt||!yn||(Ye?Ye.remountPreviews(yn):(Ye=Ta.fromConfig(o.attachments,qg),Ye.setPreviewsContainer(yn)),nt?.addListener(gt,"change",r=>{let a=r.target;Ye?.handleFileSelect(a.files),a.value=""}),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(EC(o.attachments.dropOverlay)))};Zg();let ZC=()=>It?.prefetch(),em=()=>{if(!o.contextMentions?.enabled||!pe)return;let r=nt?.header??null,a=r?eu(r):void 0;if(It=Gb({config:o,textarea:pe,anchor:Zn??pe,getMessages:()=>T.getMessages(),liveRegionHost:ue,chipRow:a}),It&&!a){let d=pe;d.parentElement?.insertBefore(It.contextRow,d)}};em();let yo=null,ew={getState:()=>Se.getState(),getValue:()=>pe?.value??"",setValue:r=>{pe&&(pe.value=r,pe.dispatchEvent(new Event("input",{bubbles:!0})),fo())},submit:()=>{Nh(nt?.form??null)},openAttachmentPicker:()=>{br()||gt?.click()},toggleVoice:()=>{Pd?.()},requestRender:()=>yo?.resolve()},tw=()=>{let r=[];return(It?.affordanceButtons??[]).forEach((d,m)=>{r.push({id:`core:mention-${m}`,placement:"start",order:Io.mention+m,element:d,managed:!0})}),hn&&r.push({id:"core:attachment",placement:"start",order:Io.attachment,element:hn}),En&&r.push({id:"core:mic",placement:"end",order:Io.mic,element:En}),mo&&r.push({id:"core:send",placement:"end",order:Io.send,element:mo}),r},tm=()=>{yo?.destroy(),yo=Sb({getBindings:()=>nt,collect:()=>({builtIns:tw(),configActions:[...YC(),...o.composer?.actions??[]],plugins:l,contributionContext:{config:o,getState:()=>Se.getState(),requestRender:()=>yo?.resolve()},debug:o.debug===!0}),actionContext:ew,getState:()=>Se.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(r,a)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${a.actionId}" failed:`,r)}}),yo.resolve()};tm();let Hd=()=>{if(Bo?.destroy(),Bo=null,!Ms().length)return;let r=nt?.header;r&&(Bo=Eb({row:eu(r),onRemove:a=>Ed(a),initialIds:Se.getState().activeModeIds}),Bo.render(Se.getState().activeModeIds,Ms()))};Hd();let nm=()=>{dr?.destroy(),dr=null,pr?.destroy(),pr=null;let r=nt?.header;r&&(dr=Wb({onDismiss:()=>ho(void 0)}),r.appendChild(dr.element),dr.render(Se.getState().quote),kd()==="defer-one"&&(pr=Bb({onEdit:()=>PS(),onRemove:()=>Ts(void 0)}),r.appendChild(pr.element),pr.render(Se.getState().pendingSubmission)))};nm();let Rd=Ub(),nw=()=>{let r=nt?.header?.querySelector(Dh);if(r)return r.childElementCount>0;let a=Se.getState();return a.mentionRefs.length>0||jc(a.activeModeIds,Ms()).length>0},om=()=>!1;function eo(){let r=Se.getState(),a=Rd.observe($b(pe),r.text);He.toggleAttribute("data-persona-composer-compact",Fb({text:r.text,wrapped:a,hasAttachments:r.attachments.length>0,hasChips:nw(),hasQuote:r.quote!==void 0,hasPendingSubmission:r.pendingSubmission!==void 0,dictationActive:om()}))}function rm(){o.composer?.layout==="single-row"&&!Re()?He.setAttribute("data-persona-composer-layout","single-row"):He.removeAttribute("data-persona-composer-layout")}rm(),Se.subscribe(()=>{yo?.sync(),Yd(),xl(),eo(),_m()}),xl();let sm=!1,ow=r=>{if(sm||o.debug!==!0)return;let a=["messages","composer"].filter(d=>r[d]);a.length&&(sm=!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??{};ow(r);let a=m=>{switch(m){case"body-top":return ne.querySelector("[data-persona-intro-card]");case"messages":return Pe;case"footer-top":return ir;case"composer":return Zn;case"footer-bottom":return st;default:return null}},d=(m,y)=>{switch(m){case"header-left":case"header-center":case"header-right":if(m==="header-left")Me.insertBefore(y,Me.firstChild);else if(m==="header-right")Me.appendChild(y);else{let C=Me.querySelector(".persona-flex-col");C?C.parentNode?.insertBefore(y,C.nextSibling):Me.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":ir.replaceWith(y);break;case"footer-bottom":st.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 im=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")Ci.has(y)?Ci.delete(y):Ci.add(y),Fv(y,m);else if(C==="tool")wi.has(y)?wi.delete(y):wi.add(y),$v(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)}Rt.delete(y)};Pe.addEventListener("pointerdown",r=>{r.target.closest('button[data-expand-header="true"]')&&(r.preventDefault(),im(r))}),Pe.addEventListener("keydown",r=>{let a=r.target;(r.key==="Enter"||r.key===" ")&&a.closest('button[data-expand-header="true"]')&&(r.preventDefault(),im(r))}),Pe.addEventListener("copy",r=>{let{clipboardData:a}=r;if(!a)return;let d=Pe.getRootNode(),m=typeof d.getSelection=="function"?d.getSelection():window.getSelection();if(!m||m.isCollapsed)return;let y=m.toString(),C=sv(y);!C||C===y||(a.setData("text/plain",C),r.preventDefault())});let Wd=new Map,am=null,lm="idle",rw={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},sw=(r,a)=>{let{icon:d,label:m}=rw[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))},cm=()=>{Pe.querySelectorAll('[data-action="read-aloud"]').forEach(a=>{let m=a.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;sw(a,m&&m===am?lm:"idle")})};Pe.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=T.getMessages().find(q=>q.id===y);if(z&&Dt.onCopy){let q=z.content||"";navigator.clipboard.writeText(q).then(()=>{d.classList.add("persona-message-action-success");let j=Zt(SC,14,"currentColor",2);j&&(d.innerHTML="",d.appendChild(j)),setTimeout(()=>{d.classList.remove("persona-message-action-success");let Y=Zt(xC,14,"currentColor",2);Y&&(d.innerHTML="",d.appendChild(Y))},2e3)}).catch(j=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",j)}),Dt.onCopy(z)}}else if(C==="read-aloud")T.toggleReadAloud(y);else if(C==="upvote"||C==="downvote"){let z=(Wd.get(y)??null)===C,q=C==="upvote"?"thumbs-up":"thumbs-down";if(z){Wd.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",Y=m.querySelector(`[data-action="${j}"]`);if(Y){Y.classList.remove("persona-message-action-active");let dt=he(j==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);dt&&(Y.innerHTML="",Y.appendChild(dt))}Wd.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 Xe=T.getMessages().find(lt=>lt.id===y);Xe&&Dt.onFeedback&&Dt.onFeedback({type:C,messageId:Xe.id,message:Xe})}}else if(C==="regenerate")tl?.regenerate(y);else if(C==="edit")tl?.edit(y);else if(C==="quote")tl?.quote(y);else if(C?.startsWith(od)){let W=C.slice(od.length),z=o.messageActions?.custom?.find(j=>j.id===W),q=T.getMessages().find(j=>j.id===y);if(!z||!q)return;try{z.onSelect(q)}catch(j){console.error(`[AgentWidget] messageActions.custom "${W}" onSelect failed:`,j)}}});let tl=null;Pe.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 W=C==="approve"?"approved":"denied",q=T.getMessages().find(Y=>Y.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"?T.resolveWebMcpApproval(y,W):T.resolveApproval(q.approval,W)});let ze=null,dm=!1,Bi=null,Fr=()=>{},_i="none",nl=null,Fn={artifacts:[],selectedId:null},_o=!1,to=!1,Oi=!1,Is=!1,pm=()=>Is||Fn.artifacts.some(r=>Er(o.features?.artifacts,r)==="panel"),ol=()=>Fn.artifacts.length>0&&!_o&&pm(),at={current:null},Bd=(r,a)=>{let d=T.getArtifactById(a),m=d?.markdown,y=d?.title||"artifact",C=d?.file,W=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=T.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"&&(W=ge.props.artifactType)}catch{}}}return{markdown:m,title:y,file:C,artifactType:W}};Pe.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:W,file:z}=Bd(d,m);if(!C)return;let q=nr();q&&q.triggerArtifactDownload(q.downloadInfoFor({title:W,markdown:C,file:z}))}),Pe.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]"),W=y?y.getAttribute("data-artifact-inline"):C?.getAttribute("data-open-artifact")??null,q=(y?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(lt=>lt.id===m);if(!q)return;let{markdown:j,title:Y,file:se,artifactType:ge}=Bd(d,W??""),Xe={artifactId:W,title:Y,artifactType:ge,markdown:j,file:se};try{Promise.resolve(q.onClick(Xe)).catch(()=>{})}catch{}}),Pe.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=T.getArtifactById(m),C=nr();if(!C)return;let W="";if(y)W=C.artifactCopyText(y);else{let{markdown:z,file:q,artifactType:j}=Bd(d,m);j==="markdown"&&(W=C.artifactCopyText({id:m,artifactType:"markdown",status:"complete",markdown:z??"",...q?{file:q}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let z=Zt(SC,16,"currentColor",2);z&&(d.replaceChildren(z),setTimeout(()=>{let q=Zt(xC,16,"currentColor",2);q&&d.replaceChildren(q)},1500))}).catch(()=>{})}),Pe.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||(_o=!1,Is=!0,to=!0,Oi=!0,T.selectArtifact(m),no())}),Pe.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(),_o=!1,Is=!0,T.selectArtifact(m),no())}),Pe.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 Ls=Ne.composerOverlay,Hs=(r,a,d)=>{let m=a.trim();if(!m||!at.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})),di(Ls,y);let W=at.current.getMessages().find(z=>z.toolCall?.id===y);W?.agentMetadata?.awaitingLocalTool?at.current.resolveAskUserQuestion(W,d.structured??m):at.current.sendMessage(m)},Ur=r=>{let a=at.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:wc(r,m),currentIndex:Qn(r)})},um=r=>Object.entries(r).map(([a,d])=>`${a}: ${Array.isArray(d)?d.join(", "):d}`).join(" | "),_d=r=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let a=Qn(r),d=ci(r);if(a>=d-1)return;let m=at.current?.getMessages().find(y=>y.toolCall?.id===r.getAttribute("data-tool-call-id"));m&&(xc(r,m,o,a+1),Ur(r))};Ls.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})),di(Ls,C);let W=at.current?.getMessages().find(z=>z.toolCall?.id===C);W?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(W),at.current?.resolveAskUserQuestion(W,"(dismissed)"));return}if(y==="pick"){let C=d.getAttribute("data-option-label");if(!C)return;let W=m.getAttribute("data-multi-select")==="true",z=Tr(m);if(z&&W){let q=bs(m)[Qn(m)],j=new Set(Array.isArray(q)?q:[]);j.has(C)?j.delete(C):j.add(C),kr(m,Array.from(j)),Ur(m);return}if(z){kr(m,C),Ur(m),_d(m);return}if(W){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=pu(m).length===0);return}Hs(m,C,{source:"pick",values:[C]});return}if(y==="submit-multi"){let C=pu(m);if(C.length===0)return;Hs(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 W=m.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!W.trim())return;if(Tr(m)){kr(m,W.trim()),Ur(m),_d(m);return}Hs(m,W,{source:"free-text"});return}if(y==="next"||y==="back"){if(!at.current)return;let C=m.getAttribute("data-tool-call-id")??"",W=at.current.getMessages().find(se=>se.toolCall?.id===C);if(!W)return;let q=m.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(q){let se=bs(m)[Qn(m)];(typeof se!="string"||se!==q)&&kr(m,q)}let j=y==="next"?1:-1,Y=Qn(m)+j;xc(m,W,o,Y),Ur(m);return}if(y==="submit-all"){if(!at.current)return;let C=m.getAttribute("data-tool-call-id")??"",W=at.current.getMessages().find(se=>se.toolCall?.id===C);if(!W)return;let q=m.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";q&&kr(m,q);let j=wc(m,W);at.current.persistAskUserQuestionProgress(W,{answers:j,currentIndex:Qn(m)});let Y=um(j);Hs(m,Y||"(submitted)",{source:"submit-all",structured:j});return}if(y==="skip"){if(!at.current)return;let C=m.getAttribute("data-tool-call-id")??"",W=at.current.getMessages().find(ge=>ge.toolCall?.id===C);if(!W)return;let z=Tr(m),q=Qn(m),j=ci(m),Y=q>=j-1;if(!z){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),di(Ls,C),W.agentMetadata?.awaitingLocalTool&&(at.current.markAskUserQuestionResolved(W),at.current.resolveAskUserQuestion(W,"(dismissed)"));return}kr(m,"");let se=m.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),Y){let ge=wc(m,W),Xe=um(ge);Hs(m,Xe||"(skipped)",{source:"submit-all",structured:ge});return}xc(m,W,o,q+1),Ur(m);return}}),Ls.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(Tr(m)){kr(m,y.trim()),Ur(m),_d(m);return}Hs(m,y,{source:"free-text"})}});let gm=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=Ls.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",gm);let bo=null,ft=null,Di=null,rl=null,sl=()=>{},mm=!1,il="",al="";function Od(){rl?.(),rl=null}let iw=()=>{let r=js&&as?.isConnected?as:null,a=r?r.getBoundingClientRect().width:0;return a<=0?200:a+360},fm=()=>{if(!bo||!ft)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){ft.style.removeProperty("position"),ft.style.removeProperty("left"),ft.style.removeProperty("top"),ft.style.removeProperty("bottom"),ft.style.removeProperty("width"),ft.style.removeProperty("z-index");return}let m=bo.firstElementChild;if(!m||m===ft)return;let y=10;ft.style.position="absolute",ft.style.top="0",ft.style.bottom="0",ft.style.width=`${y}px`,ft.style.zIndex="5";let C=wg(bo,a),W=m.offsetWidth+C/2-y/2;ft.style.left=`${Math.max(0,W)}px`},ll=()=>{},aw=()=>{let r=t.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,d=o.launcher?.mobileBreakpoint??640;return!a||r.innerWidth>d?!1:Ce||Lt(o)},cl=()=>!gn(o)||!ol()||t.classList.contains("persona-artifact-narrow-host")||aw()||(t.ownerDocument.defaultView??window).innerWidth<hT?"none":bg(o)?"detached":"welded",no=()=>{if(!ze||!gn(o))return;qa(t,o),za(t,o),ll();let r=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,a=xe.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",a>0&&a<=r);let d=ol();ze.setVisible(d),ze.update(Fn),_o?(ze.setMobileOpen(!1),ze.element.classList.add("persona-hidden"),ze.backdrop?.classList.add("persona-hidden"),to=!1,Oi=!1):Fn.artifacts.length>0&&pm()?(ze.element.classList.remove("persona-hidden"),ze.setMobileOpen(!0)):(ze.setMobileOpen(!1),ze.element.classList.add("persona-hidden"),ze.backdrop?.classList.add("persona-hidden"),to=!1,Oi=!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&&!Oi&&(to=!1),to!==mm){let C=ze.element;to?(il=C.style.width,al=C.style.maxWidth,C.style.removeProperty("width"),C.style.removeProperty("max-width")):(il&&(C.style.width=il),al&&(C.style.maxWidth=al),il="",al=""),mm=to}t.classList.toggle("persona-artifact-expanded",to),ze.setExpanded(to);let y=cl();y!==_i&&(_i=y,Fr()),sl()};if(gn(o)){xe.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(ue),bo=a,a.appendChild(r),xe.appendChild(a);let d=y=>{dm||ze||(ze=y.createArtifactPane(o,{onSelect:C=>at.current?.selectArtifact(C),onDismiss:()=>{_o=!0,no()},onToggleExpand:()=>{let C=!to,W=Fn.selectedId??Fn.artifacts[Fn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:W,expanded:C})!==!0&&(to=C,C||(Oi=!1),no())}}),ze.element.classList.add("persona-hidden"),a.appendChild(ze.element),ze.backdrop&&xe.appendChild(ze.backdrop),sl(),no())},m=nr();m?d(m):(hg(()=>{let y=nr();y&&d(y)}),md().catch(()=>{})),sl=()=>{if(!bo||!ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Di?.(),Di=null,Od(),ft&&(ft.remove(),ft=null),ze.element.style.removeProperty("width"),ze.element.style.removeProperty("maxWidth");return}if(!ft){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 W=t.ownerDocument,z=W.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(),Od();let Y=j.clientX,se=ze.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,Xe=dt=>{let Kt=bo.getBoundingClientRect().width,Bt=t.classList.contains("persona-artifact-welded-split"),Mt=wg(bo,z),tn=Bt?0:C.getBoundingClientRect().width||6,Je=se-(dt.clientX-Y),nn=eC(Je,Kt,Mt,tn,ge?.resizableMinWidth,ge?.resizableMaxWidth,iw());ze.element.style.width=`${nn}px`,ze.element.style.maxWidth="none",fm()},lt=()=>{W.removeEventListener("pointermove",Xe),W.removeEventListener("pointerup",lt),W.removeEventListener("pointercancel",lt),rl=null;try{C.releasePointerCapture(j.pointerId)}catch{}};rl=lt,W.addEventListener("pointermove",Xe),W.addEventListener("pointerup",lt),W.addEventListener("pointercancel",lt);try{C.setPointerCapture(j.pointerId)}catch{}};C.addEventListener("pointerdown",q),ft=C,bo.insertBefore(C,ze.element),Di=()=>{C.removeEventListener("pointerdown",q)}}if(ft){let C=ol();ft.classList.toggle("persona-hidden",!C),fm()}},ll=()=>{if(!Ce||!ze||(o.launcher?.sidebarMode??!1)||Lt(o)&&Xn(o).reveal==="emerge")return;let C=t.ownerDocument.defaultView??window,W=o.launcher?.mobileFullscreen??!0,z=o.launcher?.mobileBreakpoint??640;if(W&&C.innerWidth<=z||!Gv(o,Ce))return;let q=o.launcher?.width??o.launcherWidth??er,j=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ol()?(xe.style.width=j,xe.style.maxWidth=j):(xe.style.width=q,xe.style.maxWidth=q)},typeof ResizeObserver<"u"&&(Bi=new ResizeObserver(()=>{no()}),Bi.observe(xe))}else xe.appendChild(ue);Re()&&Vt&&(Ne.peekBanner&&Vt.appendChild(Ne.peekBanner),Vt.appendChild(He)),t.appendChild(Ke),Vt&&t.appendChild(Vt);let Dd=()=>{if(Re()){xe.style.width="100%",xe.style.maxWidth="100%";let ve=o.launcher?.composerBar??{},Fe=Ke.dataset.state==="expanded",ut=ve.expandedSize??"anchored";if(!(Fe&&ut!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let jt=o.theme?.components?.panel,Rn=fi(o),gs=(ms,rc)=>ms==null||ms===""?rc:dn(Rn,ms)??ms,vh="1px solid var(--persona-border)",Ct="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Jp="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=gs(jt?.border,vh),ue.style.borderRadius=gs(jt?.borderRadius,Jp),ue.style.boxShadow=gs(jt?.shadow,Ct),ue.style.overflow="hidden";return}let r=Lt(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,W=fi(o),z=(ve,Fe)=>ve==null||ve===""?Fe:dn(W,ve)??ve,q=t.ownerDocument.defaultView??window,j=o.launcher?.mobileFullscreen??!0,Y=o.launcher?.mobileBreakpoint??640,se=q.innerWidth<=Y,ge=j&&se&&Ce,Xe=r&&j&&se,lt=o.launcher?.position??"bottom-left",dt=lt==="bottom-left"||lt==="top-left",Kt=o.launcher?.zIndex??sn,Bt="var(--persona-panel-border, 1px solid var(--persona-border))",Mt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",tn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Je=y&&!ge&&!Xe;Je?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let nn=Je?Bt:a||ge?"none":Bt,Xo=Je?Mt:ge?"none":a?dt?"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":Mt;r&&!ge&&!Je&&(Xo="none",nn="none");let Ao=Je?tn:a||ge?"0":tn,Mo=z(C?.border,nn),H=z(C?.shadow,Xo),_e=z(C?.borderRadius,Ao),De=cl(),fe=De==="detached",pt=De==="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)))))",Et=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&gn(o)&&bg(o)&&m&&!r;t.classList.toggle("persona-artifact-chat-flush",Et);let Ee=fe||Et?"none":H,qt=fe?Bt:pt?"none":Mo,zt=fe?tn:_e;Et&&(qt="none",zt="0");let Kn=C?.borderRadius!=null&&C.borderRadius!=="",We=Et&&!Kn?"0":_e,yt=ne.scrollTop;t.style.cssText="",Ke.style.cssText="",xe.style.cssText="",ue.style.cssText="",ne.style.cssText="",Ps||(He.style.cssText=""),b&&(ne.style.display="none"),(d||m)&&(t.style.minWidth="0");let Eo=()=>{if(yt<=0)return;(ne.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ne.scrollTop===yt)return;let Fe=ne.scrollHeight-ne.clientHeight;Fe<=0||(ne.scrollTop=Math.min(yt,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
+ `,_.addEventListener("click",()=>{m=w,F.forEach((G,le)=>{let ee=le<w;G.classList.toggle("selected",ee),G.setAttribute("aria-checked",le===w-1?"true":"false")})}),F.push(_),M.appendChild(_)}v.appendChild(M);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 A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=c,A.addEventListener("click",()=>{n?.(),u.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=l,H.addEventListener("click",async()=>{if(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let w=P?.value.trim()||void 0;await e(m,w),u.remove()}catch(w){H.disabled=!1,H.textContent=l,console.error("[CSAT Feedback] Failed to submit:",w)}}),K.appendChild(A),K.appendChild(H),v.appendChild(K),u.appendChild(v),u}function wC(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:g="Not likely",highLabel:u="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let v=null,h=document.createElement("div");h.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=o,x.appendChild(E);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,x.appendChild(M),h.appendChild(x);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=g;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,P.appendChild(K),P.appendChild(A);let H=document.createElement("div");H.className="persona-feedback-numbers";let w=[];for(let S=0;S<=10;S++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-number-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`Rating ${S} out of 10`),B.textContent=String(S),B.dataset.rating=String(S),S<=6?B.classList.add("persona-feedback-detractor"):S<=8?B.classList.add("persona-feedback-passive"):B.classList.add("persona-feedback-promoter"),B.addEventListener("click",()=>{v=S,w.forEach((R,I)=>{R.classList.toggle("selected",I===S),R.setAttribute("aria-checked",I===S?"true":"false")})}),w.push(B),H.appendChild(B)}F.appendChild(P),F.appendChild(H),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 le=document.createElement("button");le.type="button",le.className="persona-feedback-btn persona-feedback-btn-skip",le.textContent=c,le.addEventListener("click",()=>{n?.(),m.remove()});let ee=document.createElement("button");return ee.type="button",ee.className="persona-feedback-btn persona-feedback-btn-submit",ee.textContent=l,ee.addEventListener("click",async()=>{if(v===null){H.classList.add("persona-feedback-shake"),setTimeout(()=>H.classList.remove("persona-feedback-shake"),500);return}ee.disabled=!0,ee.textContent="Submitting...";try{let S=_?.value.trim()||void 0;await e(v,S),m.remove()}catch(S){ee.disabled=!1,ee.textContent=l,console.error("[NPS Feedback] Failed to submit:",S)}}),G.appendChild(le),G.appendChild(ee),h.appendChild(G),m.appendChild(h),m}var Ei="persona-chat-history",hT=30*1e3,yT=641,Ti="data-persona-composer-reason",bT={"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 vT(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=bT[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 vd(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 CT(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 wT(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Hg=t=>!t||typeof t!="object"?{}:{...t},MC=t=>t.map(e=>({...e,streaming:!1})),EC=(t,e,n)=>{let o=t?.markdown?xh(t.markdown):null,s=Ah(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??"",g=c.message.rawContent??null;if(e){let v=e.process({text:p,raw:g??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 u=oi()!==null,m;if(t?.postprocessMessage){let v=t.postprocessMessage({...c,text:p,raw:g??c.text??""});m=s?s(v):v}else if(o){let v=c.streaming?ry(p):p,h=o(v);m=s&&u?s(h):h}else m=cc(p);return m};return c=>{try{return l(c)}catch(p){return i||(i=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",p)),cc(c.text??"")}}};function TC(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=me(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 ST=(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},xT=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:ST(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),kC=(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=Bc(e),s=()=>{lb({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};s();let i=o.features;o=wg(o);let l=Ag.getForInstance(o.plugins),c=sv(t),p=[],g=!1,u=Fv(()=>o),m=null,v=null,h=null,x=!1,E=null,M=r=>{m=r,r.initApprovalUi({webMcpToolTitle:dc});let a=r.createBuiltInApprovalPlugin();v=a.plugin,h=a.teardown},F=()=>{if(m)return m;let r=jv();return r?(M(r),r):(zv().then(a=>{x||m||(M(a),E?.())}).catch(()=>{}),null)},P=!1,K=!1,A=null,H=(r,a,d,f)=>{if(!r.querySelector("[data-tv-form]"))return;let y=oC();if(y){y.enhanceWithForms(r,a,d,f);return}nC().then(()=>{P||K||!A||(K=!0,A())}).catch(()=>{})};o.components&&Zo.registerAll(o.components);let w=aC(),G=o.persistState===!1?null:o.storageAdapter??cC(),le=!!o.clientToken&&typeof o.reconnectStream!="function",ee={},S=null,B,R=new Promise(r=>{B=r}),I,Z=!1,V=r=>{if(o.onStateLoaded)try{let a=o.onStateLoaded(r);if(a&&typeof a=="object"&&"state"in a){let{state:d,open:f}=a;return f&&(Z=!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")S=r.then(a=>V(a??{messages:[],metadata:{}}));else{let d=V(r??{messages:[],metadata:{}});d.metadata&&(ee=Hg(d.metadata)),d.messages?.length&&(o={...o,initialMessages:d.messages}),d.artifacts?.length&&(o={...o,initialArtifacts:d.artifacts,initialSelectedArtifactId:d.selectedArtifactId??null}),I=d.draft}}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",r)}else if(o.onStateLoaded)try{let r=V({messages:[],metadata:{}});r.messages?.length&&(o={...o,initialMessages:r.messages})}catch(r){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",r)}S||B();let ce=()=>ee,ie=r=>{ee=r({...ee})??{},Os()},fe=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Eg],Me=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Va.message,Va.messageAndClick],Le=Tg({parsers:fe,handlers:Me,getSessionMetadata:ce,updateSessionMetadata:ie,emit:w.emit,documentRef:typeof document<"u"?document:null});Le.syncFromMetadata();let be=o.launcher?.enabled??!0,Je=o.launcher?.autoExpand??!1,ve=o.autoFocusInput??!1,U=Je,Ee=be,Fe=o.layout?.header?.layout,yt=!1,Re=()=>Da(o),Pe=()=>be||Re(),ye=Re()?!1:be?Je:!0,co=!1,po=null,xs=()=>{co=!0,po&&clearTimeout(po),po=setTimeout(()=>{co&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),co=!1)},1e4)},It=EC(o,Le,xs),uo=o.features?.showReasoning??!0,Dn=o.features?.showToolCalls??!0,nn=o.features?.showEventStreamToggle??!1,go=o.features?.scrollToBottom??{},Nn=o.features?.scrollBehavior??{},Jn=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",fo=`${Jn()}event-stream`,Ho=null,Br=o.features?.eventStream?.maxEvents??2e3,Ze=null,An=null,Zn=null,D=!1,Q=null,b=!1,O=null,N=0,$=(r,a)=>{Ze?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:r,timestamp:Date.now(),payload:JSON.stringify(a)})},te=(r,a)=>{An?.processEvent(r,a),Ze?$(r,a):Zn&&(Zn.length>=Br&&Zn.shift(),Zn.push({type:r,payload:a}))},re=()=>{Ze||!nn||(Zn??(Zn=[]),mg().then(r=>{if(D||Ze||!nn)return;Ho=new r.EventStreamStore(fo),Ze=new r.EventStreamBuffer(Br,Ho),An=An??new r.ThroughputTracker,Ho.open().then(()=>Ze?.restore()).catch(d=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",d)});let a=Zn??[];Zn=null;for(let d of a)An?.processEvent(d.type,d.payload),$(d.type,d.payload)}).catch(()=>{}))};nn&&re();let ae=!1,de=null,Nt=()=>{},Be=()=>{},Lt=()=>{},xt=()=>{},Ro=()=>{},ir=()=>b||ae&&de==="panel",Ft={onCopy:r=>{w.emit("message:copy",r),T?.isClientTokenMode()&&T.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),T?.isClientTokenMode()&&T.submitMessageFeedback(r.messageId,r.type).catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",a)}),o.messageActions?.onFeedback?.(r)}},Ut=o.statusIndicator??{},mn=r=>r==="idle"?Ut.idleText??Dt.idle:r==="connecting"?Ut.connectingText??Dt.connecting:r==="connected"?Ut.connectedText??Dt.connected:r==="error"?Ut.errorText??Dt.error:r==="paused"?Ut.pausedText??Dt.paused:r==="resuming"?Ut.resumingText??Dt.resuming:Dt[r];function Ga(r,a,d,f){if(!r.hasAttribute(Ti))if(f==="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 Mn=Nv({config:o,showClose:Pe()}),{wrapper:Ve,panel:Se,pillRoot:Vt}=Mn.shell,Oe=Mn.panelElements,{container:ue,body:ne,messagesWrapper:Te,starterSuggestions:wd,transcriptSuggestions:Pi,suggestions:ar,textarea:pe,sendButton:xe,composerForm:eo,statusText:st,welcomeHost:hn,welcomeIconHolder:FC,greetingHost:En,introKicker:UC,introTitle:$C,introSubtitle:qC,closeButton:Ue,iconHolder:At,headerTitle:lr,headerSubtitle:_r,header:Ae,footer:He,actionsRow:zC}=Oe,Sd=Oe.leftActions,Qa=Oe.rightActions,mo=Oe.sendButtonWrapper,Ng=Oe.setSendButtonMode,oe=Oe.micButton,Tn=Oe.micButtonWrapper,wt=Oe.attachmentButton,yn=Oe.attachmentButtonWrapper,ht=Oe.attachmentInput,bn=Oe.attachmentPreviewsContainer;ue.classList.add("persona-relative"),ne.classList.add("persona-relative");let jC=12,Ii=()=>go.label??"",VC=()=>go.iconName??"arrow-down",KC=()=>go.enabled!==!1,kn=()=>Nn.mode??"anchor-top",cr=()=>kn()==="follow"||kn()==="anchor-top"&&Fi,Li=()=>Nn.anchorTopOffset??16,GC=()=>Nn.restorePosition??"bottom",Fg=()=>Nn.pauseOnInteraction===!0,Ug=()=>Nn.showActivityWhilePinned!==!1,$g=()=>Nn.announce===!0,xd=()=>Nn.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 Hi=k("span","persona-flex persona-items-center"),Ad=k("span",""),Or=k("span","");Or.setAttribute("data-persona-scroll-to-bottom-count",""),Or.style.display="none",Wt.append(Hi,Ad,Or),ue.appendChild(Wt);let Fn=k("div","persona-stream-anchor-spacer");Fn.setAttribute("aria-hidden","true"),Fn.setAttribute("data-persona-anchor-spacer",""),Fn.style.flexShrink="0",Fn.style.pointerEvents="none",Fn.style.height="0px",Fn.style.display="none",ne.appendChild(Fn);let Wo=k("div","persona-sr-only");Wo.setAttribute("aria-live","polite"),Wo.setAttribute("aria-atomic","true"),Wo.setAttribute("role","status"),Wo.setAttribute("data-persona-live-region",""),Object.assign(Wo.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"}),ue.appendChild(Wo);let Ri=null,Xa=null,Ya=r=>{!$g()||!r||(Xa=r,Ri===null&&(Ri=setTimeout(()=>{Ri=null,Xa&&$g()&&(Wo.textContent=Xa),Xa=null},400)))},Ja="empty",Za=0,Md=()=>Za||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Dr=()=>{let a=He.style.display==="none"?0:He.offsetHeight;Wt.style.bottom=`${a+Md()+jC}px`};Dr();let Ed=()=>{Ps||(He.style.marginBottom=Za>0?`${Za}px`:"")},el=()=>{let r=qu(o,Re()),a=nr(o),f=He.style.display==="none"?0:He.offsetHeight,y=a.anchor==="center"&&Ja==="empty"?Wa(a.anchorComposerTop)??Wa("44%"):null,C=y===null||Re()?0:nv({columnHeight:ue.clientHeight,footerHeight:f,fraction:y});t.style.setProperty("--persona-composer-overlay-height",`${f}px`),t.style.setProperty("--persona-composer-lift",`${r==="overlay"?C:0}px`),Za=r==="block"?C:0,Ed(),Dr()},qg=()=>{let r=!!Ii();Wt.setAttribute("aria-label",Ii()||"Jump to latest"),Wt.title=Ii(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",r?"true":"false"),Hi.innerHTML="";let a=me(VC(),"14px","currentColor",2);a?(Hi.appendChild(a),Hi.style.display=""):Hi.style.display="none",Ad.textContent=Ii(),Ad.style.display=r?"":"none"};qg();let Xe=null,Ht=null,Ce=nb(),QC=r=>{try{ue.dispatchEvent(new CustomEvent("persona:composer:state",{detail:r,bubbles:!0,composed:!0}))}catch{}};Ce.subscribe(QC);let ho=()=>{Ce.setText(pe?.value??"")},Nr=()=>{Ce.setMentionRefs(Ht?.getMentionRefs()??[])},XC=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}),zg=r=>{let a=Object.freeze(r.map(XC));Ce.setAttachments(a);try{o.attachments?.onChange?.(a)}catch(d){console.error("[AgentWidget] attachments.onChange failed:",d)}Jd()};Ce.setSelectedModelId(o.composer?.selectedModelId);let Wi=()=>o.composer?.modes??[],Ms=()=>Ib(Wi(),o.composer?.modeGroups);{let r=Vc(o.composer?.defaultActiveModeIds??[],Wi());r.length&&Ce.setActiveModeIds(r)}function jg(r){if(Ce.getState().selectedModelId!==r){Ce.setSelectedModelId(r),dr?.repaint();try{o.composer?.onModelChange?.(r)}catch(a){console.error("[AgentWidget] composer.onModelChange failed:",a)}}}function tl(r){Ce.setActiveModeIds(r),Bo?.render(r,Ms()),Es.forEach(a=>a.repaint()),bo?.resolve(),El(),to()}function Td(r){tl(Lb(Ce.getState().activeModeIds,r,Wi(),o.composer?.modeGroups))}let dr=null,kd=null,Bo=null,Es=new Map,pr=null;function yo(r){Ce.setQuote(r),pr?.render(Ce.getState().quote),to(),Df()}let Vg=!1;function Pd(){let r=o.composer?.streamingSubmitBehavior??"block";return r!=="interrupt"?r:o.clientToken?"interrupt":(!Vg&&o.debug===!0&&(Vg=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ur=null;function Ts(r){Ce.setPendingSubmission(r),ur?.render(Ce.getState().pendingSubmission),to()}let YC=r=>{let a=Es.get(r);if(a)return a;let d=Wb({groupId:r,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===r),getModes:()=>Wi().filter(f=>f.groupId===r),getActiveIds:()=>Ce.getState().activeModeIds,onSelect:f=>Td(f)});return Es.set(r,d),d},JC=()=>{let r=[],a=Ce.getState().activeModeIds,d=new Set;if(Wi().forEach((f,y)=>{if(jc(f.groupId,o.composer?.modeGroups)){let C=f.groupId;if(d.has(C))return;d.add(C);let W=YC(C);W.action.order=Du(y),W.action.label=o.composer?.modeGroups?.find(z=>z.id===C)?.label??C,r.push(W.action);return}r.push({id:kb(f.id),kind:"button",placement:"start",order:Du(y),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:a.includes(f.id),onSelect:()=>Td(f.id)})}),o.composer?.models?.length&&!l.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!dr||kd!==f)&&(kd=f,dr=Eb({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Ce.getState().selectedModelId,onSelect:y=>jg(y),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),r.push(dr.action)}return r},Id=null,Kg=l.find(r=>r.renderHeader);if(Kg?.renderHeader){let r=Kg.renderHeader({config:o,defaultRenderer:()=>{let a=Cs({config:o,showClose:Pe()});return Fa(ue,a,o),a.header},onClose:()=>pt(!1,"user")});if(r){let a=Ae;a&&(a.replaceWith(r),Ae=r,Mn.header.element=r)}}let Gg=()=>{Q&&(ne.style.display="none",He.parentNode?.insertBefore(Q.element,He),Q.update())},Ld=()=>{if(!Ze){re();return}if(b=!0,Q?Gg():mg().then(a=>{Q||!b||!Ze||(Q=a.createEventStreamView({buffer:Ze,getFullHistory:()=>Ze.getAllFromStore(),onClose:()=>ks(),config:o,plugins:l,getThroughput:()=>An?.getMetric()??{status:"idle"},renderIconByName:me}),Gg())}).catch(()=>{ks()}),et){et.style.boxShadow=`inset 0 0 0 1.5px ${un.actionIconColor}`;let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(d=>d&&et.classList.add(d))}let r=()=>{if(!b)return;let a=Date.now();a-N>=200&&(Q?.update(),N=a),O=requestAnimationFrame(r)};N=0,O=requestAnimationFrame(r),qt(),w.emit("eventStream:opened",{timestamp:Date.now()})},ks=()=>{if(b){if(b=!1,Q&&Q.element.remove(),ne.style.display="",et){et.style.boxShadow="";let r=o.features?.eventStream?.classNames?.toggleButtonActive;r&&r.split(/\s+/).forEach(a=>a&&et.classList.remove(a))}O!==null&&(cancelAnimationFrame(O),O=null),qt(),w.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(nn){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:"");et=k("button",a),et.style.width="28px",et.style.height="28px",et.style.color=un.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let d=tn(SC,"18px","currentColor",1.5);d&&et.appendChild(d);let f=Oe.clearChatButtonWrapper,y=Oe.closeButtonWrapper,C=f||y;C&&C.parentNode===Ae?Ae.insertBefore(et,C):Ae.appendChild(et),et.addEventListener("click",()=>{b?ks():Ld()})}let Qg=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??er).join(","),y.multiple=(a.maxFiles??4)>1,y.style.display="none",y.setAttribute("aria-label",a.buttonTooltipText??"Attach files"),r.appendChild(y)}},Ps=!1,Xg=r=>{let a=l.find(y=>y.renderComposer);if(!a?.renderComposer)return null;let d=o.composer,f=g?T.isStreaming():!1;return a.renderComposer({config:o,defaultRenderer:r,requestRender:()=>dh(),storage:u(a.id),onSubmit:y=>{!T||T.isStreaming()||Zl(y.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{vr()||ht?.click()},models:d?.models,selectedModelId:Ce.getState().selectedModelId??d?.selectedModelId,onModelChange:y=>jg(y),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Id?.()}:void 0})},Yg=Xg(()=>Ua({config:o}).footer);Yg&&(Mn.replaceComposer(Yg),He=Mn.composer.footer,Ps=!0);let tt=null,ZC=r=>{eo=r.form,pe=r.input,mo=r.sendButton?r.sendButton.parentElement:null,r.sendButton&&(xe=r.sendButton),r.micButton&&(oe=r.micButton,Tn=r.micButton.parentElement),r.found.status&&(st=r.found.status),r.found.suggestions&&(ar=r.found.suggestions),r.attachmentButton&&(wt=r.attachmentButton,yn=r.attachmentButton.parentElement),ht=r.attachmentInput??null,bn=r.attachmentPreviews??null,r.found.actionsRow&&(zC=r.found.actionsRow),Sd=r.found.actionsStart,Qa=r.found.actionsEnd};function Hd(){let r=pe;if(!r)return;let a=o.composer?.inputAttributes,d=!a?.ariaLabel&&!(r instanceof HTMLTextAreaElement)?r.getAttribute("aria-label"):null;Dc(r,a),d&&r.setAttribute("aria-label",d),Oc(r,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:La(r)}),fb(r,_c(o.composer?.maxLines,Re()?5:3))}let Jg=r=>{tt=rb(r,{debug:o.debug===!0}),tt&&ZC(tt),Hd()};Qg(He),Jg(He),ho();let Bi=Rr(o,Re());Bi&&(Te.style.maxWidth=Bi,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",En.style.maxWidth=Bi,En.style.marginLeft="auto",En.style.marginRight="auto",En.style.width="100%",wd.style.maxWidth=Bi,Pi.style.maxWidth=Bi,Pi.style.marginLeft="auto",Pi.style.marginRight="auto",Pi.style.width="100%");let Zg=()=>{let r=Rr(o,Re());if(!(!r||Re()))for(let a of[eo,ar,bn,st])a&&(a.style.maxWidth=r,a.style.marginLeft="auto",a.style.marginRight="auto",a.style.width="100%")};Zg();let ef=()=>{!o.attachments?.enabled||!ht||!bn||(Xe?Xe.remountPreviews(bn):(Xe=ka.fromConfig(o.attachments,zg),Xe.setPreviewsContainer(bn)),tt?.addListener(ht,"change",r=>{let a=r.target;Xe?.handleFileSelect(a.files),a.value=""}),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(TC(o.attachments.dropOverlay)))};ef();let ew=()=>Ht?.prefetch(),tf=()=>{if(!o.contextMentions?.enabled||!pe)return;let r=tt?.header??null,a=r?tu(r):void 0;if(Ht=Qb({config:o,textarea:pe,anchor:eo??pe,getMessages:()=>T.getMessages(),liveRegionHost:ue,chipRow:a}),Ht&&!a){let d=pe;d.parentElement?.insertBefore(Ht.contextRow,d)}};tf();let bo=null,tw={getState:()=>Ce.getState(),getValue:()=>pe?.value??"",setValue:r=>{pe&&(pe.value=r,pe.dispatchEvent(new Event("input",{bubbles:!0})),ho())},submit:()=>{Fh(tt?.form??null)},openAttachmentPicker:()=>{vr()||ht?.click()},toggleVoice:()=>{Id?.()},requestRender:()=>bo?.resolve()},nw=()=>{let r=[];return(Ht?.affordanceButtons??[]).forEach((d,f)=>{r.push({id:`core:mention-${f}`,placement:"start",order:Io.mention+f,element:d,managed:!0})}),yn&&r.push({id:"core:attachment",placement:"start",order:Io.attachment,element:yn}),Tn&&r.push({id:"core:mic",placement:"end",order:Io.mic,element:Tn}),mo&&r.push({id:"core:send",placement:"end",order:Io.send,element:mo}),r},nf=()=>{bo?.destroy(),bo=xb({getBindings:()=>tt,collect:()=>({builtIns:nw(),configActions:[...JC(),...o.composer?.actions??[]],plugins:l,contributionContext:{config:o,getState:()=>Ce.getState(),requestRender:()=>bo?.resolve()},debug:o.debug===!0}),actionContext:tw,getState:()=>Ce.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(r,a)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${a.actionId}" failed:`,r)}}),bo.resolve()};nf();let Rd=()=>{if(Bo?.destroy(),Bo=null,!Ms().length)return;let r=tt?.header;r&&(Bo=Tb({row:tu(r),onRemove:a=>Td(a),initialIds:Ce.getState().activeModeIds}),Bo.render(Ce.getState().activeModeIds,Ms()))};Rd();let of=()=>{pr?.destroy(),pr=null,ur?.destroy(),ur=null;let r=tt?.header;r&&(pr=Bb({onDismiss:()=>yo(void 0)}),r.appendChild(pr.element),pr.render(Ce.getState().quote),Pd()==="defer-one"&&(ur=_b({onEdit:()=>IS(),onRemove:()=>Ts(void 0)}),r.appendChild(ur.element),ur.render(Ce.getState().pendingSubmission)))};of();let Wd=$b(),ow=()=>{let r=tt?.header?.querySelector(Nh);if(r)return r.childElementCount>0;let a=Ce.getState();return a.mentionRefs.length>0||Vc(a.activeModeIds,Ms()).length>0},rf=()=>!1;function to(){let r=Ce.getState(),a=Wd.observe(qb(pe),r.text);He.toggleAttribute("data-persona-composer-compact",Ub({text:r.text,wrapped:a,hasAttachments:r.attachments.length>0,hasChips:ow(),hasQuote:r.quote!==void 0,hasPendingSubmission:r.pendingSubmission!==void 0,dictationActive:rf()}))}function sf(){o.composer?.layout==="single-row"&&!Re()?He.setAttribute("data-persona-composer-layout","single-row"):He.removeAttribute("data-persona-composer-layout")}sf(),Ce.subscribe(()=>{bo?.sync(),Jd(),Al(),to(),Df()}),Al();let af=!1,rw=r=>{if(af||o.debug!==!0)return;let a=["messages","composer"].filter(d=>r[d]);a.length&&(af=!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??{};rw(r);let a=f=>{switch(f){case"body-top":return ne.querySelector("[data-persona-intro-card]");case"messages":return Te;case"footer-top":return ar;case"composer":return eo;case"footer-bottom":return st;default:return null}},d=(f,y)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Ae.insertBefore(y,Ae.firstChild);else if(f==="header-right")Ae.appendChild(y);else{let C=Ae.querySelector(".persona-flex-col");C?C.parentNode?.insertBefore(y,C.nextSibling):Ae.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":ar.replaceWith(y);break;case"footer-bottom":st.replaceWith(y);break;default:break}};for(let[f,y]of Object.entries(r))if(y)try{let C=y({config:o,defaultContent:()=>a(f)});C&&d(f,C)}catch(C){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${f}":`,C)}})();let lf=r=>{let d=r.target.closest('button[data-expand-header="true"]');if(!d)return;let f=d.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!f)return;let y=f.getAttribute("data-message-id");if(!y)return;let C=d.getAttribute("data-bubble-type");if(C==="reasoning")wi.has(y)?wi.delete(y):wi.add(y),Uv(y,f);else if(C==="tool")Si.has(y)?Si.delete(y):Si.add(y),qv(y,f,o);else if(C==="approval"&&m){let z=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",q=m.approvalDetailsExpansionState.get(y)??z;m.approvalDetailsExpansionState.set(y,!q),m.updateApprovalDetailsUI(y,f,o)}Bt.delete(y)};Te.addEventListener("pointerdown",r=>{r.target.closest('button[data-expand-header="true"]')&&(r.preventDefault(),lf(r))}),Te.addEventListener("keydown",r=>{let a=r.target;(r.key==="Enter"||r.key===" ")&&a.closest('button[data-expand-header="true"]')&&(r.preventDefault(),lf(r))}),Te.addEventListener("copy",r=>{let{clipboardData:a}=r;if(!a)return;let d=Te.getRootNode(),f=typeof d.getSelection=="function"?d.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let y=f.toString(),C=iv(y);!C||C===y||(a.setData("text/plain",C),r.preventDefault())});let Bd=new Map,cf=null,df="idle",sw={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},iw=(r,a)=>{let{icon:d,label:f}=sw[a];r.setAttribute("aria-label",f),r.title=f,r.setAttribute("aria-pressed",a==="idle"?"false":"true"),r.classList.toggle("persona-message-action-active",a!=="idle"),r.classList.toggle("persona-message-action-loading",a==="loading");let y=me(d,14,"currentColor",2);y&&(r.innerHTML="",r.appendChild(y))},pf=()=>{Te.querySelectorAll('[data-action="read-aloud"]').forEach(a=>{let f=a.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;iw(a,f&&f===cf?df:"idle")})};Te.addEventListener("click",r=>{let d=r.target.closest(".persona-message-action-btn[data-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let f=d.closest("[data-actions-for]");if(!f)return;let y=f.getAttribute("data-actions-for");if(!y)return;let C=d.getAttribute("data-action");if(C==="copy"){let z=T.getMessages().find(q=>q.id===y);if(z&&Ft.onCopy){let q=z.content||"";navigator.clipboard.writeText(q).then(()=>{d.classList.add("persona-message-action-success");let j=tn(xC,14,"currentColor",2);j&&(d.innerHTML="",d.appendChild(j)),setTimeout(()=>{d.classList.remove("persona-message-action-success");let Y=tn(AC,14,"currentColor",2);Y&&(d.innerHTML="",d.appendChild(Y))},2e3)}).catch(j=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",j)}),Ft.onCopy(z)}}else if(C==="read-aloud")T.toggleReadAloud(y);else if(C==="upvote"||C==="downvote"){let z=(Bd.get(y)??null)===C,q=C==="upvote"?"thumbs-up":"thumbs-down";if(z){Bd.delete(y),d.classList.remove("persona-message-action-active");let j=me(q,14,"currentColor",2);j&&(d.innerHTML="",d.appendChild(j))}else{let j=C==="upvote"?"downvote":"upvote",Y=f.querySelector(`[data-action="${j}"]`);if(Y){Y.classList.remove("persona-message-action-active");let ut=me(j==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ut&&(Y.innerHTML="",Y.appendChild(ut))}Bd.set(y,C),d.classList.add("persona-message-action-active");let se=me(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 Qe=T.getMessages().find(ct=>ct.id===y);Qe&&Ft.onFeedback&&Ft.onFeedback({type:C,messageId:Qe.id,message:Qe})}}else if(C==="regenerate")nl?.regenerate(y);else if(C==="edit")nl?.edit(y);else if(C==="quote")nl?.quote(y);else if(C?.startsWith(rd)){let W=C.slice(rd.length),z=o.messageActions?.custom?.find(j=>j.id===W),q=T.getMessages().find(j=>j.id===y);if(!z||!q)return;try{z.onSelect(q)}catch(j){console.error(`[AgentWidget] messageActions.custom "${W}" onSelect failed:`,j)}}});let nl=null;Te.addEventListener("click",r=>{let d=r.target.closest("button[data-approval-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let f=d.closest(".persona-approval-bubble");if(!f)return;let y=f.getAttribute("data-message-id");if(!y)return;let C=d.getAttribute("data-approval-action");if(!C)return;let W=C==="approve"?"approved":"denied",q=T.getMessages().find(Y=>Y.id===y);if(!q?.approval)return;let j=f.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"?T.resolveWebMcpApproval(y,W):T.resolveApproval(q.approval,W)});let qe=null,uf=!1,_i=null,Fr=()=>{},Oi="none",ol=null,Un={artifacts:[],selectedId:null},_o=!1,no=!1,Di=!1,Is=!1,gf=()=>Is||Un.artifacts.some(r=>Er(o.features?.artifacts,r)==="panel"),rl=()=>Un.artifacts.length>0&&!_o&&gf(),lt={current:null},_d=(r,a)=>{let d=T.getArtifactById(a),f=d?.markdown,y=d?.title||"artifact",C=d?.file,W=d?.artifactType??"markdown";if(!f){let j=r.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(j){let se=T.getMessages().find(ge=>ge.id===j);if(se?.rawContent)try{let ge=JSON.parse(se.rawContent);f=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"&&(W=ge.props.artifactType)}catch{}}}return{markdown:f,title:y,file:C,artifactType:W}};Te.addEventListener("click",r=>{let d=r.target.closest("[data-download-artifact]");if(!d)return;r.preventDefault(),r.stopPropagation();let f=d.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:C,title:W,file:z}=_d(d,f);if(!C)return;let q=or();q&&q.triggerArtifactDownload(q.downloadInfoFor({title:W,markdown:C,file:z}))}),Te.addEventListener("click",r=>{let d=r.target.closest("[data-artifact-custom-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let f=d.getAttribute("data-artifact-custom-action");if(!f)return;let y=d.closest("[data-artifact-inline]"),C=y?null:d.closest("[data-open-artifact]"),W=y?y.getAttribute("data-artifact-inline"):C?.getAttribute("data-open-artifact")??null,q=(y?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ct=>ct.id===f);if(!q)return;let{markdown:j,title:Y,file:se,artifactType:ge}=_d(d,W??""),Qe={artifactId:W,title:Y,artifactType:ge,markdown:j,file:se};try{Promise.resolve(q.onClick(Qe)).catch(()=>{})}catch{}}),Te.addEventListener("click",r=>{let d=r.target.closest("[data-copy-artifact]");if(!d)return;r.preventDefault(),r.stopPropagation();let f=d.getAttribute("data-copy-artifact");if(!f)return;let y=T.getArtifactById(f),C=or();if(!C)return;let W="";if(y)W=C.artifactCopyText(y);else{let{markdown:z,file:q,artifactType:j}=_d(d,f);j==="markdown"&&(W=C.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:z??"",...q?{file:q}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let z=tn(xC,16,"currentColor",2);z&&(d.replaceChildren(z),setTimeout(()=>{let q=tn(AC,16,"currentColor",2);q&&d.replaceChildren(q)},1500))}).catch(()=>{})}),Te.addEventListener("click",r=>{let d=r.target.closest("[data-expand-artifact-inline]");if(!d)return;r.preventDefault(),r.stopPropagation();let f=d.getAttribute("data-expand-artifact-inline");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(_o=!1,Is=!0,no=!0,Di=!0,T.selectArtifact(f),oo())}),Te.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 f=d.getAttribute("data-open-artifact");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(r.preventDefault(),r.stopPropagation(),_o=!1,Is=!0,T.selectArtifact(f),oo())}),Te.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 Ls=Oe.composerOverlay,Hs=(r,a,d)=>{let f=a.trim();if(!f||!lt.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:f,answers:d.structured,values:d.values??(d.source==="multi"?f.split(", "):[f]),isFreeText:C,source:d.source},bubbles:!0,composed:!0})),pi(Ls,y);let W=lt.current.getMessages().find(z=>z.toolCall?.id===y);W?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(W,d.structured??f):lt.current.sendMessage(f)},Ur=r=>{let a=lt.current;if(!a)return;let d=r.getAttribute("data-tool-call-id")??"",f=a.getMessages().find(y=>y.toolCall?.id===d);f&&a.persistAskUserQuestionProgress(f,{answers:Sc(r,f),currentIndex:Xn(r)})},ff=r=>Object.entries(r).map(([a,d])=>`${a}: ${Array.isArray(d)?d.join(", "):d}`).join(" | "),Od=r=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let a=Xn(r),d=di(r);if(a>=d-1)return;let f=lt.current?.getMessages().find(y=>y.toolCall?.id===r.getAttribute("data-tool-call-id"));f&&(Ac(r,f,o,a+1),Ur(r))};Ls.addEventListener("click",r=>{let d=r.target.closest("[data-ask-user-action]");if(!d)return;let f=d.closest("[data-persona-ask-sheet-for]");if(!f)return;let y=d.getAttribute("data-ask-user-action");if(r.preventDefault(),r.stopPropagation(),y==="dismiss"){let C=f.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),pi(Ls,C);let W=lt.current?.getMessages().find(z=>z.toolCall?.id===C);W?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(W),lt.current?.resolveAskUserQuestion(W,"(dismissed)"));return}if(y==="pick"){let C=d.getAttribute("data-option-label");if(!C)return;let W=f.getAttribute("data-multi-select")==="true",z=Tr(f);if(z&&W){let q=bs(f)[Xn(f)],j=new Set(Array.isArray(q)?q:[]);j.has(C)?j.delete(C):j.add(C),kr(f,Array.from(j)),Ur(f);return}if(z){kr(f,C),Ur(f),Od(f);return}if(W){let q=d.getAttribute("aria-pressed")==="true";d.setAttribute("aria-pressed",q?"false":"true"),d.classList.toggle("persona-ask-pill-selected",!q);let j=f.querySelector('[data-ask-user-action="submit-multi"]');j&&(j.disabled=uu(f).length===0);return}Hs(f,C,{source:"pick",values:[C]});return}if(y==="submit-multi"){let C=uu(f);if(C.length===0)return;Hs(f,C.join(", "),{source:"multi",values:C});return}if(y==="open-free-text"){let C=f.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"){f.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let W=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!W.trim())return;if(Tr(f)){kr(f,W.trim()),Ur(f),Od(f);return}Hs(f,W,{source:"free-text"});return}if(y==="next"||y==="back"){if(!lt.current)return;let C=f.getAttribute("data-tool-call-id")??"",W=lt.current.getMessages().find(se=>se.toolCall?.id===C);if(!W)return;let q=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(q){let se=bs(f)[Xn(f)];(typeof se!="string"||se!==q)&&kr(f,q)}let j=y==="next"?1:-1,Y=Xn(f)+j;Ac(f,W,o,Y),Ur(f);return}if(y==="submit-all"){if(!lt.current)return;let C=f.getAttribute("data-tool-call-id")??"",W=lt.current.getMessages().find(se=>se.toolCall?.id===C);if(!W)return;let q=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";q&&kr(f,q);let j=Sc(f,W);lt.current.persistAskUserQuestionProgress(W,{answers:j,currentIndex:Xn(f)});let Y=ff(j);Hs(f,Y||"(submitted)",{source:"submit-all",structured:j});return}if(y==="skip"){if(!lt.current)return;let C=f.getAttribute("data-tool-call-id")??"",W=lt.current.getMessages().find(ge=>ge.toolCall?.id===C);if(!W)return;let z=Tr(f),q=Xn(f),j=di(f),Y=q>=j-1;if(!z){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),pi(Ls,C),W.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(W),lt.current.resolveAskUserQuestion(W,"(dismissed)"));return}kr(f,"");let se=f.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),Y){let ge=Sc(f,W),Qe=ff(ge);Hs(f,Qe||"(skipped)",{source:"submit-all",structured:ge});return}Ac(f,W,o,q+1),Ur(f);return}}),Ls.addEventListener("keydown",r=>{if(r.key!=="Enter")return;let d=r.target;if(!d.matches?.('[data-ask-free-text-input="true"]'))return;let f=d.closest("[data-persona-ask-sheet-for]");if(!f)return;r.preventDefault();let y=d.value;if(y.trim()){if(Tr(f)){kr(f,y.trim()),Ur(f),Od(f);return}Hs(f,y,{source:"free-text"})}});let mf=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=Ls.querySelector("[data-persona-ask-sheet-for]");if(!d||d.getAttribute("data-ask-layout")!=="rows"||d.getAttribute("data-multi-select")==="true")return;let f=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"]')[f-1];C&&(r.preventDefault(),C.click())};document.addEventListener("keydown",mf);let vo=null,bt=null,Ni=null,sl=null,il=()=>{},hf=!1,al="",ll="";function Dd(){sl?.(),sl=null}let aw=()=>{let r=js&&as?.isConnected?as:null,a=r?r.getBoundingClientRect().width:0;return a<=0?200:a+360},yf=()=>{if(!vo||!bt)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){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let f=vo.firstElementChild;if(!f||f===bt)return;let y=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${y}px`,bt.style.zIndex="5";let C=Sg(vo,a),W=f.offsetWidth+C/2-y/2;bt.style.left=`${Math.max(0,W)}px`},cl=()=>{},lw=()=>{let r=t.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,d=o.launcher?.mobileBreakpoint??640;return!a||r.innerWidth>d?!1:be||Rt(o)},dl=()=>!fn(o)||!rl()||t.classList.contains("persona-artifact-narrow-host")||lw()||(t.ownerDocument.defaultView??window).innerWidth<yT?"none":vg(o)?"detached":"welded",oo=()=>{if(!qe||!fn(o))return;za(t,o),ja(t,o),cl();let r=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,a=Se.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",a>0&&a<=r);let d=rl();qe.setVisible(d),qe.update(Un),_o?(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),no=!1,Di=!1):Un.artifacts.length>0&&gf()?(qe.element.classList.remove("persona-hidden"),qe.setMobileOpen(!0)):(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),no=!1,Di=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(qe.setExpandToggleVisible(f),qe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),qe.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),qe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),qe.setTabFade(o.features?.artifacts?.layout?.tabFade),qe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!Di&&(no=!1),no!==hf){let C=qe.element;no?(al=C.style.width,ll=C.style.maxWidth,C.style.removeProperty("width"),C.style.removeProperty("max-width")):(al&&(C.style.width=al),ll&&(C.style.maxWidth=ll),al="",ll=""),hf=no}t.classList.toggle("persona-artifact-expanded",no),qe.setExpanded(no);let y=dl();y!==Oi&&(Oi=y,Fr()),il()};if(fn(o)){Se.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(ue),vo=a,a.appendChild(r),Se.appendChild(a);let d=y=>{uf||qe||(qe=y.createArtifactPane(o,{onSelect:C=>lt.current?.selectArtifact(C),onDismiss:()=>{_o=!0,oo()},onToggleExpand:()=>{let C=!no,W=Un.selectedId??Un.artifacts[Un.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:W,expanded:C})!==!0&&(no=C,C||(Di=!1),oo())}}),qe.element.classList.add("persona-hidden"),a.appendChild(qe.element),qe.backdrop&&Se.appendChild(qe.backdrop),il(),oo())},f=or();f?d(f):(yg(()=>{let y=or();y&&d(y)}),md().catch(()=>{})),il=()=>{if(!vo||!qe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ni?.(),Ni=null,Dd(),bt&&(bt.remove(),bt=null),qe.element.style.removeProperty("width"),qe.element.style.removeProperty("maxWidth");return}if(!bt){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 W=t.ownerDocument,z=W.defaultView??window,q=j=>{if(!qe||j.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||z.innerWidth<=640)return;j.preventDefault(),Dd();let Y=j.clientX,se=qe.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,Qe=ut=>{let Kt=vo.getBoundingClientRect().width,Ot=t.classList.contains("persona-artifact-welded-split"),Tt=Sg(vo,z),on=Ot?0:C.getBoundingClientRect().width||6,Ye=se-(ut.clientX-Y),rn=tC(Ye,Kt,Tt,on,ge?.resizableMinWidth,ge?.resizableMaxWidth,aw());qe.element.style.width=`${rn}px`,qe.element.style.maxWidth="none",yf()},ct=()=>{W.removeEventListener("pointermove",Qe),W.removeEventListener("pointerup",ct),W.removeEventListener("pointercancel",ct),sl=null;try{C.releasePointerCapture(j.pointerId)}catch{}};sl=ct,W.addEventListener("pointermove",Qe),W.addEventListener("pointerup",ct),W.addEventListener("pointercancel",ct);try{C.setPointerCapture(j.pointerId)}catch{}};C.addEventListener("pointerdown",q),bt=C,vo.insertBefore(C,qe.element),Ni=()=>{C.removeEventListener("pointerdown",q)}}if(bt){let C=rl();bt.classList.toggle("persona-hidden",!C),yf()}},cl=()=>{if(!be||!qe||(o.launcher?.sidebarMode??!1)||Rt(o)&&Yn(o).reveal==="emerge")return;let C=t.ownerDocument.defaultView??window,W=o.launcher?.mobileFullscreen??!0,z=o.launcher?.mobileBreakpoint??640;if(W&&C.innerWidth<=z||!Qv(o,be))return;let q=o.launcher?.width??o.launcherWidth??tr,j=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";rl()?(Se.style.width=j,Se.style.maxWidth=j):(Se.style.width=q,Se.style.maxWidth=q)},typeof ResizeObserver<"u"&&(_i=new ResizeObserver(()=>{oo()}),_i.observe(Se))}else Se.appendChild(ue);Re()&&Vt&&(Oe.peekBanner&&Vt.appendChild(Oe.peekBanner),Vt.appendChild(He)),t.appendChild(Ve),Vt&&t.appendChild(Vt);let Nd=()=>{if(Re()){Se.style.width="100%",Se.style.maxWidth="100%";let De=o.launcher?.composerBar??{},gt=Ve.dataset.state==="expanded",nt=De.expandedSize??"anchored";if(!(gt&&nt!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let ft=o.theme?.components?.panel,Yo=hi(o),Gt=(fs,sc)=>fs==null||fs===""?sc:pn(Yo,fs)??fs,Gn="1px solid var(--persona-border)",mt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Zp="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Gt(ft?.border,Gn),ue.style.borderRadius=Gt(ft?.borderRadius,Zp),ue.style.boxShadow=Gt(ft?.shadow,mt),ue.style.overflow="hidden";return}let r=Rt(o),a=o.launcher?.sidebarMode??!1,d=r||a||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,y=o.launcher?.detachedPanel===!0,C=o.theme?.components?.panel,W=hi(o),z=(De,gt)=>De==null||De===""?gt:pn(W,De)??De,q=t.ownerDocument.defaultView??window,j=o.launcher?.mobileFullscreen??!0,Y=o.launcher?.mobileBreakpoint??640,se=q.innerWidth<=Y,ge=j&&se&&be,Qe=r&&j&&se,ct=o.launcher?.position??"bottom-left",ut=ct==="bottom-left"||ct==="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)))",on="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ye=y&&!ge&&!Qe;Ye?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let rn=Ye?Ot:a||ge?"none":Ot,Mo=Ye?Tt:ge?"none":a?ut?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":f?"none":Tt;r&&!ge&&!Ye&&(Mo="none",rn="none");let Xo=Ye?on:a||ge?"0":on,Eo=z(C?.border,rn),ni=z(C?.shadow,Mo),gs=z(C?.borderRadius,Xo),L=dl(),ke=L==="detached",We=L==="welded";t.classList.toggle("persona-artifact-detached-split",ke),t.classList.toggle("persona-artifact-welded-split",We);let we="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)))))",at=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&fn(o)&&vg(o)&&f&&!r;t.classList.toggle("persona-artifact-chat-flush",at);let Ie=ke||at?"none":ni,io=ke?Ot:We?"none":Eo,St=ke?on:gs;at&&(io="none",St="0");let Zt=C?.borderRadius!=null&&C.borderRadius!=="",jt=at&&!Zt?"0":gs,kt=ne.scrollTop;t.style.cssText="",Ve.style.cssText="",Se.style.cssText="",ue.style.cssText="",ne.style.cssText="",Ps||(He.style.cssText=""),b&&(ne.style.display="none"),(d||f)&&(t.style.minWidth="0");let _e=()=>{if(kt<=0)return;(ne.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ne.scrollTop===kt)return;let gt=ne.scrollHeight-ne.clientHeight;gt<=0||(ne.scrollTop=Math.min(kt,gt))})};if(ge){Ve.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"),Ve.style.cssText=`
35
35
  position: fixed !important;
36
36
  inset: 0 !important;
37
37
  width: 100% !important;
@@ -43,7 +43,7 @@ _Details: ${n.message}_`:o}var Su=t=>({isError:!0,content:[{type:"text",text:t}]
43
43
  flex-direction: column !important;
44
44
  z-index: ${Kt} !important;
45
45
  background-color: var(--persona-surface, #ffffff) !important;
46
- `,xe.style.cssText=`
46
+ `,Se.style.cssText=`
47
47
  position: relative !important;
48
48
  display: flex !important;
49
49
  flex-direction: column !important;
@@ -67,11 +67,11 @@ _Details: ${n.message}_`:o}var Su=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",He.style.flexShrink="0",Md(),mt=!0,Eo();return}let Oe=o?.launcher?.width??o?.launcherWidth??er;if(!a&&!r)m&&d?(xe.style.width="100%",xe.style.maxWidth="100%"):(xe.style.width=Oe,xe.style.maxWidth=Oe);else if(r)if(Xn(o).reveal==="emerge"&&!y){let Fe=Xn(o).width;xe.style.width=Fe,xe.style.maxWidth=Fe}else xe.style.width="100%",xe.style.maxWidth="100%";if(ll(),xe.style.boxShadow=Ee,xe.style.borderRadius=We,fe?xe.style.border="none":pt&&(xe.style.border=Mo),ue.style.border=qt,ue.style.borderRadius=zt,ue.style.boxShadow=fe&&!Et?$t:"",Et&&(ue.style.background="transparent",ne.style.background="transparent",He.style.background="transparent",He.style.borderTop="none"),pt){let ve=o.features?.artifacts?.layout;nl=ve?.unifiedSplitOuterRadius?.trim()||ve?.paneBorderRadius?.trim()||_e}else nl=null;if(r&&!ge&&!Je&&!fe&&!pt&&C?.border===void 0&&(ue.style.border="none",Xn(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),r&&!ge&&pt&&C?.border===void 0&&(Xn(o).side==="right"?xe.style.borderLeft="1px solid var(--persona-border)":xe.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"),xe.style.display="flex",xe.style.flexDirection="column",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.maxHeight="100%",xe.style.height="100%",fe||(xe.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",He.style.flexShrink="0"),m&&(Je||fe||Et)&&!r&&(Et||(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&&(_n[lt]??_n["bottom-right"]).split(" ").forEach(Fe=>Ke.classList.add(Fe)),a){let ve=o.launcher?.sidebarWidth??"420px";y?Ke.style.cssText=`
70
+ `,ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",He.style.flexShrink="0",Ed(),yt=!0,_e();return}let $e=o?.launcher?.width??o?.launcherWidth??tr;if(!a&&!r)f&&d?(Se.style.width="100%",Se.style.maxWidth="100%"):(Se.style.width=$e,Se.style.maxWidth=$e);else if(r)if(Yn(o).reveal==="emerge"&&!y){let gt=Yn(o).width;Se.style.width=gt,Se.style.maxWidth=gt}else Se.style.width="100%",Se.style.maxWidth="100%";if(cl(),Se.style.boxShadow=Ie,Se.style.borderRadius=jt,ke?Se.style.border="none":We&&(Se.style.border=Eo),ue.style.border=io,ue.style.borderRadius=St,ue.style.boxShadow=ke&&!at?we:"",at&&(ue.style.background="transparent",ne.style.background="transparent",He.style.background="transparent",He.style.borderTop="none"),We){let De=o.features?.artifacts?.layout;ol=De?.unifiedSplitOuterRadius?.trim()||De?.paneBorderRadius?.trim()||gs}else ol=null;if(r&&!ge&&!Ye&&!ke&&!We&&C?.border===void 0&&(ue.style.border="none",Yn(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),r&&!ge&&We&&C?.border===void 0&&(Yn(o).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),d&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",f&&(t.style.width="100%"),Ve.style.display="flex",Ve.style.flexDirection="column",Ve.style.flex="1 1 0%",Ve.style.minHeight="0",Ve.style.maxHeight="100%",Ve.style.height="100%",f&&(Ve.style.overflow="hidden"),Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.height="100%",ke||(Se.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",He.style.flexShrink="0"),f&&(Ye||ke||at)&&!r&&(at||(Ve.style.padding="var(--persona-panel-inset)"),Ve.style.background="var(--persona-panel-canvas-bg)"),Ve.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!a&&!f&&!r&&(On[ct]??On["bottom-right"]).split(" ").forEach(gt=>Ve.classList.add(gt)),a){let De=o.launcher?.sidebarWidth??"420px";y?Ve.style.cssText=`
71
71
  position: fixed !important;
72
72
  top: var(--persona-panel-inset) !important;
73
73
  bottom: var(--persona-panel-inset) !important;
74
- width: ${ve} !important;
74
+ width: ${De} !important;
75
75
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
76
76
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
77
77
  margin: 0 !important;
@@ -79,12 +79,12 @@ _Details: ${n.message}_`:o}var Su=t=>({isError:!0,content:[{type:"text",text:t}]
79
79
  display: flex !important;
80
80
  flex-direction: column !important;
81
81
  z-index: ${Kt} !important;
82
- ${dt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
83
- `:Ke.style.cssText=`
82
+ ${ut?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
83
+ `:Ve.style.cssText=`
84
84
  position: fixed !important;
85
85
  top: 0 !important;
86
86
  bottom: 0 !important;
87
- width: ${ve} !important;
87
+ width: ${De} !important;
88
88
  height: 100vh !important;
89
89
  max-height: 100vh !important;
90
90
  margin: 0 !important;
@@ -92,8 +92,8 @@ _Details: ${n.message}_`:o}var Su=t=>({isError:!0,content:[{type:"text",text:t}]
92
92
  display: flex !important;
93
93
  flex-direction: column !important;
94
94
  z-index: ${Kt} !important;
95
- ${dt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
96
- `,xe.style.cssText=`
95
+ ${ut?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
96
+ `,Se.style.cssText=`
97
97
  position: relative !important;
98
98
  display: flex !important;
99
99
  flex-direction: column !important;
@@ -104,10 +104,10 @@ _Details: ${n.message}_`:o}var Su=t=>({isError:!0,content:[{type:"text",text:t}]
104
104
  min-height: 0 !important;
105
105
  margin: 0 !important;
106
106
  padding: 0 !important;
107
- box-shadow: ${Ee} !important;
108
- border-radius: ${We} !important;
109
- ${fe?"border: none !important;":pt?`border: ${Mo} !important;`:""}
110
- `,xe.style.setProperty("width","100%","important"),xe.style.setProperty("max-width","100%","important"),ue.style.cssText=`
107
+ box-shadow: ${Ie} !important;
108
+ border-radius: ${jt} !important;
109
+ ${ke?"border: none !important;":We?`border: ${Eo} !important;`:""}
110
+ `,Se.style.setProperty("width","100%","important"),Se.style.setProperty("max-width","100%","important"),ue.style.cssText=`
111
111
  display: flex !important;
112
112
  flex-direction: column !important;
113
113
  flex: 1 1 0% !important;
@@ -116,16 +116,16 @@ _Details: ${n.message}_`:o}var Su=t=>({isError:!0,content:[{type:"text",text:t}]
116
116
  min-height: 0 !important;
117
117
  max-height: 100% !important;
118
118
  overflow: hidden !important;
119
- border-radius: ${zt} !important;
120
- border: ${qt} !important;
121
- ${fe&&!Et?`box-shadow: ${$t} !important;`:""}
122
- ${Et?"background: transparent !important;":""}
119
+ border-radius: ${St} !important;
120
+ border: ${io} !important;
121
+ ${ke&&!at?`box-shadow: ${we} !important;`:""}
122
+ ${at?"background: transparent !important;":""}
123
123
  `,Ps||(He.style.cssText=`
124
124
  flex-shrink: 0 !important;
125
125
  border-top: none !important;
126
126
  padding: 8px 16px 12px 16px !important;
127
- ${Et?"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??sn} !important;`;Ke.style.cssText+=ve+Fe+ut}Md(),Eo()},Nd=()=>{t.style.setProperty("--persona-content-max-width",Rr(o,Re()))},hm=!1,ym=()=>{let r=$u(o,Re());Re()&&o.composer?.placement&&o.debug===!0&&!hm&&(hm=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let a=tr(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??Qc),Za()},bm=()=>{if(Re())return;let r=Lt(o),a=o.launcher?.sidebarMode??!1;if(r||a||(o.launcher?.fullHeight??!1)||!Ce)return;let m=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,C=o.launcher?.mobileBreakpoint??640;if(y&&m.innerWidth<=C)return;let W=m.innerHeight,z=64,q=o.launcher?.heightOffset??0,j=Math.max(200,W-z),Y=Math.min(640,j);xe.style.height=`${Math.max(200,Y-q)}px`};Dd(),Ha(t,o),qa(t,o),za(t,o),Nd(),ym(),Fr=()=>{Dd(),bm(),Ha(t,o),qa(t,o),za(t,o),Nd(),ym(),nl?t.style.setProperty("--persona-artifact-welded-outer-radius",nl):t.style.removeProperty("--persona-artifact-welded-outer-radius"),Be(),Ot()};let ye=[];ye.push(()=>{dm=!0}),ye.push(()=>{p.forEach(r=>r()),c.destroy()}),ye.push(()=>{document.removeEventListener("keydown",gm)}),ye.push(()=>{Hi!==null&&clearTimeout(Hi)});let vo=null,Co=null;ye.push(()=>{vo?.(),vo=null,Co?.(),Co=null}),Bi&&ye.push(()=>{Bi?.disconnect(),Bi=null}),ye.push(()=>{Di?.(),Di=null,Od(),ft&&(ft.remove(),ft=null),ze?.element.style.removeProperty("width"),ze?.element.style.removeProperty("maxWidth"),ze?.destroy()}),en&&ye.push(()=>{D=!0,Jn=null,O!==null&&(cancelAnimationFrame(O),O=null),Q?.destroy(),Q=null,et?.destroy(),et=null,Ho=null});let $r=null,vm=()=>{$r&&($r(),$r=null),o.colorScheme==="auto"&&($r=Gc(()=>{Ha(t,o)}))};vm(),ye.push(()=>{$r&&($r(),$r=null)}),ye.push(()=>{x=!0,h?.()}),ye.push(()=>{P=!0});let Cm=!1;ye.push(()=>{Cm=!0});let Fd=(r,a)=>{let d=fa(r,a);return d||!Qh.includes(r)?d:(uv().then(m=>{if(Cm)return;nu(m.wipe),nu(m.glyphCycle);let y=fa(r,a);y&&ba(y,t)}).catch(()=>{}),null)},dl=o.features?.streamAnimation;if(dl?.type&&dl.type!=="none"){let r=Fd(dl.type,dl.plugins);r&&ba(r,t),ye.push(()=>Xh(t))}let Oo=Da(ir),wm=Da(Cd),Sm=Da(ki),qr=[Oo,wm,Sm];ye.push(()=>{qr.forEach(r=>r.destroy())});let zr=null,T,jr=null,xm=!1,Am=0,Mm=null,Em=r=>r.reduce((a,d)=>d.role==="user"?a+1:a,0),Tm=r=>{for(let a=r.length-1;a>=0;a--)if(Sa(r[a]))return r[a].id??null;return null},km=!1,lw=()=>{km||o.debug!==!0||(km=!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".'))},Pm=!1,Im=!1,Lm=(r,a)=>{Pm||o.debug!==!0||!a.enabled||a.expose||xm||Im&&(T.isStreaming()||r.some(Sa)||(Pm=!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.")))},Rs=r=>{if(!T)return;let a=r??T.getMessages(),d=j=>{j.render([],T,pe,a)},m=j=>{qr.forEach(Y=>{Y!==j&&d(Y)})};jr&&(Em(a)>Am||Tm(a)!==Mm)&&(jr=null);let y=Ir(o);Lm(a,y);let C=y.enabled?Ey(a):null,W=jr??C,z=jr?"host":"agent";if(W){let j=o.suggestions?.followUps,Y=j?.placement??(j?"auto":"composer"),ge=(Y==="auto"?Re()?"composer":"after-message":Y)==="after-message"?Sm:Oo;m(ge),ge.render(W,T,pe,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")){qr.forEach(d);return}let q=o.suggestions?.starters;if(q){let j=vi(tr(o),a),Y=q.placement??"auto",se=Y==="auto"?j?"welcome":"composer":Y;if(se==="welcome"&&!j){lw(),qr.forEach(d);return}let ge=se==="welcome"?wm:Oo;m(ge),ge.render(q.items??o.suggestionChips,T,pe,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(Oo),Oo.render(o.suggestionChips,T,pe,a,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:l,submitPrompt:Yl})},Hm=()=>{jr&&(jr=null,Rs())},cw=r=>{let a=Array.isArray(r)?[...r]:[];if(!a.length){Hm();return}let d=T?T.getMessages():[];jr=a,xm=!0,Am=Em(d),Mm=Tm(d),Rs(d)},kn=!1,Rt=lv(),Ws=new Map,Vr=new Map,ur=new Map,Kr=null,gr=null;function Gr(){if(!Kr)return;let r=Kr;Kr=null,gr?.destroy(),gr=null,Rt.delete(r),ue.querySelector(`#wrapper-${r}`)?.removeAttribute("data-preserve-runtime"),T&&Un(Pe,T.getMessages(),kt)}let Qr=0,dw=ni()!==null,Pn=zh(),In=0,mr=null,bn=!1,pl=!1,fr=0,Ft=null,Xr=null,Ud=!1,Bs=!1,Yr=null,Ni=!0,ul=!1,_s=null,gl=!1,Jr=()=>{gl=!0,mw()},$d=null,pw=4,Do=24,uw=80,gw=1e3,No=null,Rm=()=>{t.setAttribute("data-persona-scrollbar",Sd()),Sd()!=="on-scroll"&&(No!==null&&clearTimeout(No),No=null,ne.removeAttribute("data-persona-scrollbar-visible"))},mw=()=>{Sd()==="on-scroll"&&(ne.setAttribute("data-persona-scrollbar-visible",""),No!==null&&clearTimeout(No),No=setTimeout(()=>{No=null,hs(ne,Do)&&ne.removeAttribute("data-persona-scrollbar-visible")},gw))};Rm(),ye.push(()=>{No!==null&&clearTimeout(No)});let qd=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};om=()=>je.active,eo();let Wm=o.voiceRecognition?.autoResume??!1,Fo=r=>{w.emit("voice:state",{active:je.active,source:r,timestamp:Date.now()})},oo=()=>{ie(r=>({...r,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},fw=()=>{if(o.voiceRecognition?.enabled===!1)return;let r=Lg(ee.voiceState),a=!!r.active,d=Number(r.timestamp??0);je.manuallyDeactivated=!!r.manuallyDeactivated,a&&Date.now()-d<fT&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?T.toggleVoice().then(()=>{je.active=T.isVoiceActive(),Fo("restore"),T.isVoiceActive()&&ei()}):ec("restore"))},1e3)},hw=()=>T?AC(T.getMessages()).filter(r=>!r.__skipPersist):[],ml=null,Bm=(r,a)=>{typeof console<"u"&&console.error(r,a)},fl=(r,a)=>{let d=()=>{try{let W=r();return!W||typeof W.then!="function"?null:Promise.resolve(W).catch(z=>{Bm(a,z)})}catch(W){return Bm(a,W),null}},m=ml,y=m?m.then(()=>d()??void 0):d();if(!y)return;let C=y.finally(()=>{ml===C&&(ml=null)});ml=C};function Os(r){if(!G?.save)return;let a=r?AC(r):T?hw():[],d=le&&T?.getResumableHandle();d&&(ee={...ee,durableResume:{executionId:d.executionId,after:d.lastEventId}});let m={messages:a,metadata:ee,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId,...Zr?{draft:Zr}:{}};fl(()=>G.save(m),"[AgentWidget] Failed to persist state:")}let Zr,hl=()=>!G?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Fi=Nb({write:()=>{if(!hl())return;let r=Se.getState(),a=Ob({text:r.text,mentionRefs:r.mentionRefs,contentSegments:Dp(),selectedModelId:r.selectedModelId,activeModeIds:r.activeModeIds,quote:r.quote});JSON.stringify(a)!==JSON.stringify(Zr)&&(Zr=a,Os())}});function _m(){hl()&&Fi.schedule()}function zd(){Fi.flush()}function Om(r){if(!hl())return;let a=Db(r,{mentionSourceIds:(o.contextMentions?.sources??[]).map(d=>d.id),modelIds:(o.composer?.models??[]).map(d=>d.id),modes:o.composer?.modes??[]});a&&(Zr=r,pe&&!pe.value&&(pe.value=a.text,pe.dispatchEvent(new Event("input",{bubbles:!0})),fo()),a.selectedModelId&&(Se.setSelectedModelId(a.selectedModelId),cr?.repaint()),el(a.activeModeIds??[]),a.quote&&ho(a.quote),Fi.cancel())}function yl(){Fi.cancel(),Zr&&(Zr=void 0,hl()&&Os())}let Ds=null,Dm=()=>Ke.querySelector("#persona-scroll-container")||ne,Ns=()=>{Ds!==null&&(cancelAnimationFrame(Ds),Ds=null),bn=!1},Nm=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),pl=!1,Ns()},yw=()=>kn&&Vd()&&(Tn()!=="anchor-top"||Fg()),jd=()=>{let r=Pi()||"Jump to latest",a=yw();Ht.toggleAttribute("data-persona-scroll-to-bottom-streaming",a),fr>0?(Or.textContent=String(fr),Or.style.display="",Ht.setAttribute("aria-label",`${r} (${fr} new)`)):(Or.textContent="",Or.style.display="none",Ht.setAttribute("aria-label",a?`${r} (response streaming below)`:r))},Fm=()=>{fr!==0&&(fr=0,jd())},bw=()=>{let r=Ft?.spacerHeight??0;return r<=0?hs(ne,Do):wl(r)-ne.scrollTop-ne.clientHeight<=Do},Vd=()=>lr()?!Pn.isFollowing():!bw(),Kd=()=>!!T&&T.getMessages().length>0,Ut=()=>{if(!VC()||sr()){Ht.parentNode&&Ht.remove(),Ht.style.display="none";return}Ht.parentNode!==ue&&ue.appendChild(Ht),Dr();let a=Yo(ne)>0&&Vd()&&Kd();a?jd():Fm(),Ht.style.display=a?"":"none"},Ui=()=>{Pn.pause()&&(Nm(),Ut())},vn=()=>{Pn.resume(),Fm(),Ut()},hr=(r=!1)=>{lr()&&Kd()&&Pn.isFollowing()&&(!r&&!kn||(mr!==null&&(cancelAnimationFrame(mr),mr=null),pl=!0,mr=requestAnimationFrame(()=>{mr=null,pl=!1,Pn.isFollowing()&&vw(Dm(),r?220:140)})))},Um=(r,a,d,m=()=>!0)=>{let y=r.scrollTop,C=a(),W=C-y;if(Ns(),Math.abs(W)<1){bn=!0,r.scrollTop=C,In=r.scrollTop,bn=!1;return}let z=performance.now();bn=!0;let q=Y=>1-Math.pow(1-Y,3),j=Y=>{if(!m()){Ns();return}let se=a();se!==C&&(C=se,W=C-y);let ge=Y-z,Xe=Math.min(ge/d,1),lt=q(Xe),dt=y+W*lt;r.scrollTop=dt,In=r.scrollTop,Xe<1?Ds=requestAnimationFrame(j):(r.scrollTop=C,In=r.scrollTop,Ds=null,bn=!1)};Ds=requestAnimationFrame(j)},vw=(r,a=500)=>{let d=Yo(r)-r.scrollTop;if(Math.abs(d)<1){In=r.scrollTop;return}if(Math.abs(d)>=uw){Ns(),bn=!0,r.scrollTop=Yo(r),In=r.scrollTop,bn=!1;return}Um(r,()=>Yo(r),a,()=>Pn.isFollowing())},bl=()=>{if(!Kd()){Ut();return}let r=Dm();bn=!0,r.scrollTop=Yo(r),In=r.scrollTop,bn=!1,Ut()},es=r=>{let a=0,d=r;for(;d&&d!==ne;)a+=d.offsetTop,d=d.offsetParent;return a},Cw=()=>{let r=ne.getRootNode();return(typeof r.getSelection=="function"?r.getSelection():null)??ne.ownerDocument.getSelection()},vl=()=>Kh(Cw(),ne),Gd=()=>{if(KC()!=="last-user-turn")return!1;let r=T?.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,es(m)-Ii()),Yo(ne));return bn=!0,ne.scrollTop=y,In=ne.scrollTop,bn=!1,Tn()==="follow"&&!hs(ne,Do)&&Pn.pause(),Ut(),!0},Cl=r=>{let a=Math.max(0,Math.round(r));Nn.style.height=`${a}px`,Nn.style.display=a>0?"":"none",Ft&&(Ft.spacerHeight=Math.max(0,r))},wl=r=>{let a=parseFloat(getComputedStyle(ne).paddingBottom)||0,d=0;for(let y of Array.from(ne.children)){if(y===Nn||y.offsetHeight===0)continue;let C=es(y)+y.offsetHeight;C>d&&(d=C)}let m=ne.scrollHeight-r;return d>0?Math.min(d+a,m):m},ww=()=>{if(!Ft||Ft.spacerHeight<=0)return;let r=wl(Ft.spacerHeight),a=Math.max(0,Math.round(ne.scrollTop)+ne.clientHeight-r+Do);a<Ft.spacerHeight&&(Cl(a),Ut())},ro=()=>{Xr!==null&&(cancelAnimationFrame(Xr),Xr=null),Ns(),Ft=null,Nn.style.height="0px",Nn.style.display="none"},$m=r=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Qd=r=>ne.querySelector(`[data-message-id="${$m(r)}"]`),qm=r=>{Xr!==null&&cancelAnimationFrame(Xr),Xr=requestAnimationFrame(()=>{Xr=null;let a=$m(r),d=ne.querySelector(`[data-message-id="${a}"]`);if(!d)return;let m=es(d),y=Ft?.spacerHeight??0,C=wl(y),{targetScrollTop:W,spacerHeight:z}=tu({anchorOffsetTop:m,topOffset:Ii(),viewportHeight:ne.clientHeight,contentHeight:C,slack:Do});Ft={initialSpacerHeight:z,contentHeightAtAnchor:C,spacerHeight:z},Cl(z),Um(ne,()=>d.isConnected?Math.max(0,es(d)-Ii()):W,220)})},Cn=()=>{if(Tn()!=="anchor-top"||!Ft||!_s)return;let r=Qd(_s);if(!r)return;Ns();let a=Ft.spacerHeight,d=wl(a),{targetScrollTop:m,spacerHeight:y}=tu({anchorOffsetTop:es(r),topOffset:Ii(),viewportHeight:ne.clientHeight,contentHeight:d,slack:Do});Ft={initialSpacerHeight:y,contentHeightAtAnchor:d,spacerHeight:y},Cl(y),bn=!0,ne.scrollTop=m,In=ne.scrollTop,bn=!1,Ut()},Sw=()=>{if(lr()){if(!Pn.isFollowing()||hs(ne,1))return;hr(!kn);return}if(Ft&&Ft.initialSpacerHeight>0){let r=ne.scrollHeight-Ft.spacerHeight,a=Gh({initialSpacerHeight:Ft.initialSpacerHeight,contentHeightAtAnchor:Ft.contentHeightAtAnchor,currentContentHeight:r});a!==Ft.spacerHeight&&Cl(a)}Ut()},xw=r=>{let a=Tn();a==="follow"?(vn(),hr(!0)):a==="anchor-top"&&(Ni=!1,ul=!0,gl=!1,_s=r,qm(r))},Aw=()=>{if(Tn()==="anchor-top"){if(ul){Ni=!1;return}Ni=!0,ro(),vn(),hr(!0)}},Mw=96,Ew=r=>{if(Yr===null)return!0;let a=Qd(Yr),d=Qd(r);if(!a||!d)return!0;let m=es(d)-es(a);return Ii()+m>ne.clientHeight-Mw},Tw=r=>{if(Tn()!=="anchor-top"||!ul||gl||vl())return;let a=Yr===null;for(let d of r){if(!a){d.id===Yr&&(a=!0);continue}if(qh(d)){if(d.id===_s||!Ew(d.id))return;_s=d.id,qm(d.id);return}}},kw=r=>{let a=new Map;r.forEach(d=>{let m=qd.get(d.id);a.set(d.id,{streaming:d.streaming,role:d.role}),!m&&d.role==="assistant"&&(w.emit("assistant:message",d),!Bs&&(Tn()!=="anchor-top"||Fg())&&Vd()&&(fr+=1,jd(),Ut(),Xa(fr===1?"1 new message below.":`${fr} 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}))}),qd.clear(),a.forEach((d,m)=>{qd.set(m,d)})},$i=(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")},Uo=(r,a)=>{let d=document.createElement("div");return d.className="persona-flex",d.id=`wrapper-${r}`,d.setAttribute("data-wrapper-id",r),$i(d,a),d},Pw=(r,a,d)=>{let m=document.createElement("div"),C=(()=>{let H=l.find(_e=>_e.renderLoadingIndicator);if(H?.renderLoadingIndicator)return H.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),W=(H,_e)=>_e==null?!1:typeof _e=="string"?(H.textContent=_e,!0):(H.appendChild(_e),!0),z=new Set,q=new Map,j=new Set,Y=l.some(H=>H.renderAskUserQuestion),se=[],ge=[],Xe=o.enableComponentStreaming!==!1,lt=o.approval!==!1,dt=[],Kt=o.messageActions,Bt=Kt?.showRegenerate===!0&&Kt.enabled!==!1&&at.current?.isStreaming()!==!0?Gy(a):null,Mt=Kt?.showEdit===!0&&Kt.enabled!==!1,tn=Kt?.showQuote===!0&&Kt.enabled!==!1,Je=null,nn=o.features?.reasoningDisplay?.completedVisibility==="removed";if(a.forEach(H=>{if(nn&&H.variant==="reasoning"&&H.reasoning?.status==="complete")return;if(z.add(H.id),q.set(H.id,H.role),Kr===H.id&&gr){let We=Uo(H.id,H.role);We.setAttribute("data-persona-message-edit-stub","true"),We.setAttribute("data-preserve-runtime","true"),m.appendChild(We),Je={messageId:H.id,element:gr.element};return}let _e=Y&&ys(H),De=lt&&H.variant==="approval"&&!!H.approval,fe=!_e&&H.role==="assistant"&&!H.variant&&Xe&&Ig(H);!De&&ur.has(H.id)&&(r.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),ur.delete(H.id)),!fe&&Vr.has(H.id)&&(r.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),Vr.delete(H.id));let pt=ys(H)?`:${H.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${H.agentMetadata?.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",$t={canRegenerate:Bt===H.id,canEdit:Mt&&hu(H),canQuote:tn&&!H.variant&&(H.content?.trim().length??0)>0},on=`${$t.canRegenerate?"r":""}${$t.canEdit?"e":""}${$t.canQuote?"q":""}`,rn=av(H,Qr)+pt+`:${on}`,Et=_e||De||fe?null:cv(Rt,H.id,rn);if(Et){m.appendChild(Et.cloneNode(!0)),ys(H)&&H.toolCall?.id&&H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(j.add(H.toolCall.id),Sc(H,o,Ne.composerOverlay));return}let Ee=null,qt=l.find(We=>!!(H.variant==="reasoning"&&We.renderReasoning||H.variant==="tool"&&We.renderToolCall||!H.variant&&We.renderMessage)),zt=o.layout?.messages;if(ys(H)&&H.agentMetadata?.askUserQuestionAnswered===!0){Ws.delete(H.id),r.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime");return}if(Sa(H)&&Ir(o).enabled)return;if(ys(H)&&o.features?.askUserQuestion?.enabled!==!1){let We=l.find(yt=>typeof yt.renderAskUserQuestion=="function");if(We&&at.current){let yt=Ws.get(H.id),Eo=yt!==rn,so=null;if(Eo){let{payload:Fe,complete:ut}=li(H),Ar=H.id,jt=()=>at.current?.getMessages().find(Rn=>Rn.id===Ar);so=We.renderAskUserQuestion({message:H,payload:Fe,complete:ut,resolve:Rn=>{let gs=jt();gs&&at.current?.resolveAskUserQuestion(gs,Rn)},dismiss:()=>{let Rn=jt();Rn?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(Rn),at.current?.resolveAskUserQuestion(Rn,"(dismissed)"))},config:o})}let Oe=yt!=null;if(Eo&&so===null&&!Oe){H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(j.add(H.toolCall.id),Sc(H,o,Ne.composerOverlay));return}let ve=Uo(H.id,H.role);ve.setAttribute("data-ask-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),m.appendChild(ve),se.push({messageId:H.id,fingerprint:rn,bubble:so});return}else{H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(j.add(H.toolCall.id),Sc(H,o,Ne.composerOverlay));return}}else if(De){let We=F();if(!We){m.appendChild(Uo(H.id,H.role));return}let yt=l.find(ve=>typeof ve.renderApproval=="function")??v,so=ur.get(H.id)!==rn,Oe=null;if(so&&yt?.renderApproval){let ve=H.id,Fe=(ut,Ar)=>{let jt=at.current?.getMessages().find(Rn=>Rn.id===ve);jt?.approval&&(jt.approval.toolType==="webmcp"?at.current?.resolveWebMcpApproval(jt.id,ut):at.current?.resolveApproval(jt.approval,ut,Ar))};Oe=yt.renderApproval({message:H,defaultRenderer:()=>We.createApprovalBubble(H,o),config:o,approve:ut=>Fe("approved",ut),deny:ut=>Fe("denied",ut)})}if(so&&Oe===null)r.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),ur.delete(H.id),Ee=We.createApprovalBubble(H,o);else{let ve=Uo(H.id,H.role);ve.setAttribute("data-approval-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),m.appendChild(ve),dt.push({messageId:H.id,fingerprint:rn,bubble:Oe});return}}else if(qt)if(H.variant==="reasoning"&&H.reasoning&&qt.renderReasoning){if(!po)return;Ee=qt.renderReasoning({message:H,defaultRenderer:()=>pg(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&qt.renderToolCall){if(!On)return;Ee=qt.renderToolCall({message:H,defaultRenderer:()=>gg(H,o),config:o})}else qt.renderMessage&&(Ee=qt.renderMessage({message:H,defaultRenderer:()=>{let We=eg(H,d,zt,o.messageActions,Dt,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:$t});return H.role!=="user"&&L(We,H,o,T),We},config:o}));if(!Ee&&fe){let We=bC(H);if(We){let yt=Vr.get(H.id),Eo=yt!==rn,so=o.wrapComponentDirectiveInBubble!==!1&&Jo.getOptions(We.component)?.bubbleChrome!==!1,Oe=null;if(Eo){let ve=hC(We,{config:o,message:H,transform:d});if(ve&&We.component==="PersonaArtifactInline"){let Fe=ve.hasAttribute("data-artifact-inline")?ve:ve.querySelector("[data-artifact-inline]"),ut=Fe?.getAttribute("data-artifact-inline")??"",Ar=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(ut):ut,jt=ut?r.querySelector(`#wrapper-${H.id}`)?.querySelector(`[data-artifact-inline="${Ar}"]`)??null:null;Fe&&jt&&jt!==Fe&&nr()?.hasLiveInlineArtifactBlock(jt)&&(Fe===ve?ve=jt:Fe.replaceWith(jt))}if(ve)if(so){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-${H.id}`,Fe.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let ut=document.createElement("div");ut.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ut.innerHTML=d({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Fe.appendChild(ut)}Fe.appendChild(ve),Oe=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-${H.id}`,Fe.setAttribute("data-message-id",H.id),Fe.setAttribute("data-persona-component-directive","true"),H.content&&H.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:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Fe.appendChild(ut)}Fe.appendChild(ve),Oe=Fe}}if(Oe||yt!=null){let ve=Uo(H.id,H.role);ve.setAttribute("data-component-directive-stub","true"),ve.setAttribute("data-preserve-runtime","true"),m.appendChild(ve),ge.push({messageId:H.id,fingerprint:rn,bubble:Oe});return}}}if(!Ee)if(H.variant==="reasoning"&&H.reasoning){if(!po)return;Ee=pg(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!On)return;Ee=gg(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;let We=F();if(!We)return;Ee=We.createApprovalBubble(H,o)}else{let We=o.layout?.messages;We?.renderUserMessage&&H.role==="user"?Ee=We.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):We?.renderAssistantMessage&&H.role==="assistant"?Ee=We.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):Ee=eg(H,d,We,o.messageActions,Dt,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:$t}),H.role!=="user"&&Ee&&L(Ee,H,o,T)}let Kn=Uo(H.id,H.role);Kn.appendChild(Ee),dv(Rt,H.id,rn,Kn),m.appendChild(Kn)}),Ne.composerOverlay&&Ne.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(_e=>{let De=_e.getAttribute("data-persona-ask-sheet-for");De&&!j.has(De)&&di(Ne.composerOverlay,De)}),o.features?.toolCallDisplay?.grouped){let H=[],_e=[],De=o.features.toolCallDisplay.groupedMode==="summary";a.forEach(fe=>{if(fe.variant==="tool"&&fe.toolCall&&On){_e.push(fe);return}fe.variant==="reasoning"&&(!po||nn&&fe.reasoning?.status==="complete")||((_e.length>1||De&&_e.length>0)&&H.push(_e),_e=[])}),(_e.length>1||De&&_e.length>0)&&H.push(_e),H.forEach(fe=>{let pt=fe.map(zt=>Array.from(m.children).find(Kn=>Kn instanceof HTMLElement&&Kn.getAttribute("data-wrapper-id")===zt.id)).filter(zt=>!!zt);if(pt.length<(De?1:2))return;let $t=Uo(`tool-group-${fe[0].id}`,"assistant");$t.setAttribute("data-persona-tool-group-row","true");let on=document.createElement("div");on.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",on.setAttribute("data-persona-tool-group","true");let rn=document.createElement("div");rn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",rn.id=`tool-group-summary-${fe[0].id}`;let Et=`Called ${fe.length} ${fe.length===1?"tool":"tools"}`,Ee=o.toolCall?.renderGroupedSummary?.({messages:fe,toolCalls:fe.map(zt=>zt.toolCall).filter(zt=>!!zt),defaultSummary:Et,config:o});W(rn,Ee)||(rn.textContent=Et);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"),on.appendChild(rn),De||on.appendChild(qt),$t.appendChild(on),pt[0].before($t),pt.forEach((zt,Kn)=>{if(De){zt.remove();return}zt.style.setProperty("--persona-message-row-max-width","100%");let We=document.createElement("div");We.className="persona-tool-group-item persona-relative",We.setAttribute("data-persona-tool-group-item","true"),Kn<pt.length-1&&We.setAttribute("data-persona-tool-group-connector","true"),We.appendChild(zt),qt.appendChild(We)})})}pv(Rt,z);let Xo=a.some(H=>H.role==="assistant"&&H.streaming),Ao=a[a.length-1],Mo=Ao?.role==="assistant"&&!Ao.streaming&&Ao.variant!=="approval";if(kn&&a.some(H=>H.role==="user")&&!Xo&&!Mo){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:Ua},_e=l.find(fe=>fe.renderLoadingIndicator),De=null;if(_e?.renderLoadingIndicator&&(De=_e.renderLoadingIndicator(H)),De===null&&o.loadingIndicator?.render&&(De=o.loadingIndicator.render(H)),De===null&&(De=Ua()),De){let fe=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1,$t=o.layout?.messages?.layout??"bubble";fe.className=pt?$a("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(De);let on=Uo("typing-indicator","assistant");on.appendChild(fe),m.appendChild(on)}}if(!kn&&a.length>0){let H=a[a.length-1],_e={config:o,lastMessage:H,messageCount:a.length},De=l.find(pt=>pt.renderIdleIndicator),fe=null;if(De?.renderIdleIndicator&&(fe=De.renderIdleIndicator(_e)),fe===null&&o.loadingIndicator?.renderIdle&&(fe=o.loadingIndicator.renderIdle(_e)),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 on=Uo("idle-indicator","assistant");on.appendChild(pt),m.appendChild(on)}}if(ay(m),Zc(r,m),ru(r),Je){let{messageId:H,element:_e}=Je,De=r.querySelector(`#wrapper-${H}`);De&&_e.parentElement!==De&&($i(De,q.get(H)??"user"),De.replaceChildren(_e))}if(se.length>0)for(let{messageId:H,fingerprint:_e,bubble:De}of se){let fe=r.querySelector(`#wrapper-${H}`);fe&&($i(fe,q.get(H)??"assistant"),De!==null&&(fe.replaceChildren(De),fe.setAttribute("data-bubble-fp",_e),Ws.set(H,_e)))}if(Ws.size>0)for(let H of Ws.keys())z.has(H)||Ws.delete(H);if(ge.length>0)for(let{messageId:H,fingerprint:_e,bubble:De}of ge){let fe=r.querySelector(`#wrapper-${H}`);fe&&($i(fe,q.get(H)??"assistant"),De!==null&&(fe.replaceChildren(De),fe.setAttribute("data-bubble-fp",_e),Vr.set(H,_e)))}if(Vr.size>0)for(let H of Vr.keys())z.has(H)||Vr.delete(H);if(dt.length>0)for(let{messageId:H,fingerprint:_e,bubble:De}of dt){let fe=r.querySelector(`#wrapper-${H}`);fe&&($i(fe,q.get(H)??"assistant"),De!==null&&(fe.replaceChildren(De),fe.setAttribute("data-bubble-fp",_e),ur.set(H,_e)))}if(ur.size>0)for(let H of ur.keys())z.has(H)||ur.delete(H)},Xd=!1,Sl=()=>{Xd||(Xd=!0,Sh().catch(()=>{Xd=!1}))},Un=(r,a,d)=>{a.length>0&&Sl(),Pw(r,a,d),cm()},qi=null,Iw=()=>{if(qi)return;let r=d=>{let m=d.composedPath();m.includes(Ke)||Vt&&m.includes(Vt)||ct(!1,"user")};qi=r,(t.ownerDocument??document).addEventListener("pointerdown",r,!0)},zm=()=>{if(!qi)return;(t.ownerDocument??document).removeEventListener("pointerdown",qi,!0),qi=null};ye.push(()=>zm());let zi=null,Lw=()=>{if(zi)return;let r=d=>{d.key==="Escape"&&(d.isComposing||ct(!1,"user"))};zi=r,(t.ownerDocument??document).addEventListener("keydown",r,!0)},jm=()=>{if(!zi)return;(t.ownerDocument??document).removeEventListener("keydown",zi,!0),zi=null};ye.push(()=>jm());let ji=!1,Vm=new Set,Hw=()=>{let r=o.launcher?.composerBar?.peek?.streamAnimation;return r||o.features?.streamAnimation},Fs=()=>{if(!Re())return;let r=Ne.peekBanner,a=Ne.peekTextNode;if(!r||!a)return;if(be){r.classList.remove("persona-pill-peek--visible");return}let d=T?.getMessages()??[],m;for(let Bt=d.length-1;Bt>=0;Bt--){let Mt=d[Bt];if(Mt.role==="assistant"&&Mt.content){m=Mt;break}}if(!m){r.classList.remove("persona-pill-peek--visible");return}let y=m.content,C=!!m.streaming,W=Hw(),z=yc(W),q=z.type!=="none"?Fd(z.type,W?.plugins):null,j=q?.isAnimating?.(m)===!0,Y=q!==null&&(C||j);Y&&q&&!Vm.has(q.name)&&(ba(q,t),Vm.add(q.name));let se=Y&&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),Y?(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 Xe=Y?bc(y,z.buffer,q,m,C):y;if(Y&&z.placeholder==="skeleton"&&C&&(!Xe||!Xe.trim())){let Bt=document.createElement("div"),Mt=ya();Mt.classList.add("persona-pill-peek__skeleton"),Bt.appendChild(Mt),Zc(a,Bt)}else{let Bt=Math.max(0,Xe.length-100),Mt=Xe.length>100?Xe.slice(-100):Xe,tn=lc(Mt);if(!Y||!q){let Je=Xe.length>100?`\u2026${Mt}`:Mt;a.textContent!==Je&&(a.textContent=Je)}else{let Je=tn;(q.wrap==="char"||q.wrap==="word")&&(Je=ha(tn,q.wrap,`peek-${m.id}`,{skipTags:q.skipTags,startIndex:Bt}));let nn=document.createElement("div");if(nn.innerHTML=Je,q.useCaret&&Mt.length>0){let Xo=vc(),Ao=nn.querySelectorAll(".persona-stream-char, .persona-stream-word"),Mo=Ao[Ao.length-1];Mo?.parentNode?Mo.parentNode.insertBefore(Xo,Mo.nextSibling):nn.appendChild(Xo)}Zc(a,nn),q.onAfterRender?.({container:a,bubble:r,messageId:m.id,message:m,speed:z.speed,duration:z.duration})}}let Kt=kn||ji;r.classList.toggle("persona-pill-peek--visible",Kt)};if(Re()){let r=Ne.peekBanner;if(r){let m=y=>{y.preventDefault(),y.stopPropagation(),ct(!0,"user")};r.addEventListener("pointerdown",m),ye.push(()=>{r.removeEventListener("pointerdown",m)})}let a=()=>{ji||(ji=!0,Fs())},d=()=>{ji&&(ji=!1,Fs())};xe.addEventListener("pointerenter",a),xe.addEventListener("pointerleave",d),ye.push(()=>{xe.removeEventListener("pointerenter",a),xe.removeEventListener("pointerleave",d)}),Vt&&(Vt.addEventListener("pointerenter",a),Vt.addEventListener("pointerleave",d),ye.push(()=>{Vt.removeEventListener("pointerenter",a),Vt.removeEventListener("pointerleave",d)}))}let Rw=r=>{let a=o.launcher?.composerBar??{},d=a.expandedSize??"anchored",m=a.bottomOffset??"16px",y=a.collapsedMaxWidth,C=a.expandedMaxWidth??"880px",W=a.expandedTopOffset??"5vh",z=a.modalMaxWidth??"880px",q=a.modalMaxHeight??"min(90vh, 800px)",j="calc(100vw - 32px)",Y="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} + ${Y})`,se.top=W,se.width=C,se.maxWidth=j}},Vi=()=>{if(be&&Sl(),!Ie())return;if(Re()){let j=(o.launcher?.composerBar??{}).expandedSize??"anchored",Y=be?"expanded":"collapsed";Ke.dataset.state=Y,Ke.dataset.expandedSize=j,Vt&&(Vt.dataset.state=Y,Vt.dataset.expandedSize=j),Ke.style.removeProperty("display"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Rw(be),ue.style.display=be?"flex":"none",Fr(),be?(Iw(),Lw()):(zm(),jm()),Fs();return}let r=Lt(o),a=t.ownerDocument.defaultView??window,d=o.launcher?.mobileBreakpoint??640,m=o.launcher?.mobileFullscreen??!0,y=a.innerWidth<=d,C=m&&y&&Ce,W=Xn(o).reveal;be?(Ke.style.removeProperty("display"),Ke.style.display=r?"flex":"",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-95","persona-opacity-0"),xe.classList.add("persona-scale-100","persona-opacity-100"),xt?(xt.setPanelOpen(!0),xt.element.style.display="none"):ln&&(ln.style.display="none")):(r?r&&(W==="overlay"||W==="push")&&!C?(Ke.style.removeProperty("display"),Ke.style.display="flex",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.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"),xe.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"),xe.classList.remove("persona-scale-100","persona-opacity-100"),xe.classList.add("persona-scale-95","persona-opacity-0")),xt?(xt.setPanelOpen(!1),xt.element.style.display=r?"none":""):ln&&(ln.style.display=r?"none":""))},ct=(r,a="user")=>{if(!Ie()||be===r)return;let d=be;be=r,Vi();let m=(()=>{let C=o.launcher?.sidebarMode??!1,W=t.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640,j=W.innerWidth<=q,Y=Lt(o)&&z&&j,se=Re()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return C||z&&j&&Ce||Y||se})();if(be&&m){if(!vo){let C=t.getRootNode(),W=C instanceof ShadowRoot?C.host:t.closest(".persona-host");W&&(vo=ju(W,o.launcher?.zIndex??sn))}Co||(Co=Vu(t.ownerDocument))}else be||(vo?.(),vo=null,Co?.(),Co=null);be&&(ca(),Gd()||(Tn()==="follow"?hr(!0):bl()));let y={open:be,source:a,timestamp:Date.now()};be&&!d?w.emit("widget:opened",y):!be&&d&&w.emit("widget:closed",y),w.emit("widget:state",{open:be,launcherEnabled:Ce,voiceActive:je.active,streaming:T.isStreaming()})},yr={inputDisabled:!1,sendDisabled:!1},br=()=>yr.inputDisabled,ts=()=>yr.inputDisabled||yr.sendDisabled,Ww=()=>(yr.inputDisabled?yr.inputReason:void 0)??(yr.sendDisabled?yr.sendReason:void 0);function Yd(){if(!Ae)return;if(Se.getState().phase==="streaming"){Ae.disabled=!1;return}let r=Ye?!Ye.isReady():!1;Ae.disabled=ts()||r}function xl(){if(!mo)return;let r=Se.getState(),a=o.sendButton?.visibility==="when-text"&&r.phase!=="streaming"&&r.text.trim().length===0&&r.attachments.length===0;mo.toggleAttribute("data-persona-send-hidden",a)}function Bw(){let r=Ww();if(Re()){let a=Zn??He;r?a.setAttribute("title",r):a.removeAttribute("title"),He.toggleAttribute(Ei,!!r);return}if(r){st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.setAttribute(Ei,""),st.textContent=r;return}if(st.hasAttribute(Ei)&&(st.removeAttribute("role"),st.removeAttribute("aria-live"),st.removeAttribute(Ei),g)){let a=T.getStatus();Ka(st,mn(a),o.statusIndicator??{},a)}}function Jd(){let r=Pu(o.composer?.inputDisabled),a=Pu(o.composer?.sendDisabled);yr={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;pe&&(pe instanceof HTMLTextAreaElement?pe.disabled=m:pe.setAttribute("contenteditable",m?"false":"true"),pe.setAttribute("aria-disabled",m?"true":"false")),vt&&(vt.disabled=m),gt&&(gt.disabled=m);for(let C of It?.affordanceButtons??[])C.querySelectorAll("button").forEach(W=>{W.disabled=m});oe&&(oe.disabled=y),qr.forEach(C=>{C.elements.forEach(W=>{W.toggleAttribute("data-disabled",y),W instanceof HTMLButtonElement||W.setAttribute("aria-disabled",y?"true":"false")}),C.buttons.forEach(W=>{W.disabled=y})}),op.forEach(C=>{C.toggleAttribute("data-disabled",y),C instanceof HTMLButtonElement?C.disabled=y:C.setAttribute("aria-disabled",y?"true":"false"),C.querySelectorAll("button").forEach(W=>{W.disabled=y})}),He.dataset.personaComposerStreaming=d?"true":"false",He.dataset.personaComposerInputDisabled=m?"true":"false",He.dataset.personaComposerSendDisabled=ts()?"true":"false",He.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(),Bw()}let Ki=r=>{Se.setStreaming(r),Dg(r?"stop":"send"),Jd()},ns=()=>{je.active||pe&&pe.focus()};w.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ns(),200)});let os=null,Gi=!1,Zd=!fn.hidden,vr=null,ep=!S,Al=null;ye.push(()=>{Al?.cancel(),Al=null});let _w=r=>{let a=Iv(r);if(a===Ya)return;Ya=a,t.setAttribute("data-persona-conversation-state",a);let d=Ad();Za(),ep&&(Al?.cancel(),Al=kv(He,a==="active"?d:Ad(),a==="active"?"drop":"rise")),Cn()},Km=null,Gm,Qm=null,Us=null,tp=!1,Qi=r=>{let a=tr(o),d=`${a.variant}|${a.dismiss}|${a.anchor??"bottom"}|${a.align??""}|${a.iconPlacement}|${a.kicker??""}|${a.title}|${a.subtitle}`;(d!==Km||a.icon!==Gm)&&(Km=d,Gm=a.icon,sd({host:fn,iconHolder:NC,kicker:FC,title:UC,subtitle:$C,starterSuggestions:Cd},a));let m=a.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${a.message}`;m!==Qm&&(Qm=m,id(Mn,a.message,o));let y=r??(T?T.getMessages():o.initialMessages);_w(y);let C=Gi,W=!C&&vi(a,y),z=W!==Zd;if(Zd=W,Us){vr?.cancel(),vr=null,C!==tp&&(tp=C,C?og(ne,fn,null):ng(ne,fn,Us)),bi(ne,fn,!C);return}if(z&&!W&&!C&&a.dismiss==="on-first-message"&&ep){vr=Tv(fn,j=>{vr===j&&(vr=null),!Zd&&!Us&&(bi(ne,fn,!1),Cn()),j?.cancel()});return}if(vr){if(!W&&!C)return;vr.cancel(),vr=null}let q=!fn.hidden;bi(ne,fn,W),!W&&q&&Cn()},np=[],op=[],rp=!1,Xm=null,Ym,Jm=()=>{op.length=0;let r=np.splice(0,np.length);for(let a of r)try{a()}catch(d){console.warn("[persona] renderWelcome cleanup threw",d)}};ye.push(Jm);let Ow=(r,a)=>{let d=Gu(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=Qu({item:{...d,behavior:d.behavior??m?.behavior??"send"},index:a,surface:"starter",source:"config",variant:m?.variant??"card",streaming:g?T.isStreaming():!1,config:o,plugins:l,chipsConfig:o.suggestionChipsConfig,session:T,getTextarea:()=>pe,eventTarget:fn,submitPrompt:Yl});return op.push(y),y},sp=()=>{if(rp)return;rp=!0;let r=tr(o);Xm=`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`,Ym=r.icon;try{Jm(),og(ne,fn,Us),Us=null,tp=!1;let a=T?T.getMessages():o.initialMessages,d=vi(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:()=>fn,sendMessage:W=>{if(!T||T.isStreaming())return;let z=W.trim();z&&T.sendMessage(z)},requestRender:()=>sp(),renderStarter:W=>Ow(W,m++),storage:u(C.id),onCleanup:W=>{np.push(W)}}),y))break;y&&y!==fn&&(Us=y,ng(ne,fn,y))}finally{rp=!1}Qi()},Dw=()=>{let r=tr(o);`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`===Xm&&r.icon===Ym||sp()},Ml=()=>{Qi(),Ps||(pe.placeholder=Hb(Se.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!T?.isStreaming()&&(Ae.textContent=o.copy?.sendButtonLabel??"Send")),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Nw=!!o.setStoredConversationId,$s=r=>ie(a=>{let d={...a};return delete d[r],d}),El=r=>{let a=ee[r];return typeof a=="string"?a:null},Zm=()=>{let r=ee.durableResume;if(!r||typeof r!="object")return null;let a=r;return typeof a.executionId=="string"&&a.executionId.length>0&&typeof a.after=="string"&&a.after.length>0?{executionId:a.executionId,after:a.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>El("sessionId"),setStoredSessionId:r=>{ie(a=>({...a,sessionId:r}))},clearStoredSessionId:o.clearStoredSessionId??(()=>$s("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>El("conversationId")),setStoredConversationId:o.setStoredConversationId??(r=>{ie(a=>({...a,conversationId:r}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>$s("conversationId"))});let ef=()=>o.clientToken??null,tf=r=>dC(r,Yn(),o.persistState===!1),nf=ef(),$o=nf?tf(nf):null,qo={...$o?{visitorStore:$o}:{},historyBootstrapReady:R,getStoredMessageCursor:()=>El("historyMessageCursor"),setStoredMessageCursor:r=>{if(r===null){$s("historyMessageCursor");return}ie(a=>({...a,historyMessageCursor:r}))},getPendingDisplayProjections:()=>{let r=ee.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){$s("pendingDisplayProjections");return}ie(a=>({...a,pendingDisplayProjections:r}))},getStoredResumableHandle:Zm,setStoredResumableHandle:r=>{if(!r){$s("durableResume");return}ie(a=>({...a,durableResume:r}))},shouldResumeDurableConversation:()=>le&&Zm()!==null,...Nw?{}:{getStoredConversationRevision:()=>El("conversationRevision"),setStoredConversationRevision:r=>{if(r===null){$s("conversationRevision");return}ie(a=>({...a,conversationRevision:r}))}}};if(le){let r=o.onExecutionState,a=t.ownerDocument.defaultView,d=!1,m=()=>d=!0,y=()=>d=!1;a?.addEventListener("pagehide",m),a?.addEventListener("pageshow",y),ye.push(()=>{a?.removeEventListener("pagehide",m),a?.removeEventListener("pageshow",y)}),o={...o,reconnectStream:o.reconnectStream??(C=>T.getClient().reconnectClientTokenStream(C)),onExecutionState:C=>{(C||!d)&&qo.setStoredResumableHandle?.(C?{executionId:C.executionId,after:C.lastEventId}:null),r?.(C)}}}let Fw=()=>{let r=ef();if(r&&$o?.matches(r,Yn(),o.persistState===!1)||!r&&!$o)return;$o?.destroy(),$o=r?tf(r):null;let a={...qo};$o?a.visitorStore=$o:delete a.visitorStore,qo=a,T.setHistoryInternals(qo)},rs=null,Uw=()=>{rs==null&&(rs=setInterval(()=>{let r=Pe.querySelectorAll("[data-tool-elapsed]");if(r.length===0){clearInterval(rs),rs=null;return}let a=Date.now();r.forEach(d=>{let m=Number(d.getAttribute("data-tool-elapsed"));m&&(d.textContent=Ih(a-m))})},100))},ip=(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((W,z)=>ip(W,a[z]));let d=r,m=a,y=Object.keys(d),C=Object.keys(m);return y.length===C.length&&y.every(W=>Object.prototype.hasOwnProperty.call(m,W)&&ip(d[W],m[W]))},of=r=>{let{content:a,rawContent:d,llmContent:m,...y}=r;return y},ap=r=>r.role==="assistant"&&r.streaming===!0&&!r.variant&&!r.toolCall&&!r.tools&&!r.approval&&!r.reasoning&&!r.contentParts&&!r.stopReason&&!Ig(r),$w=(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))&&ap(m)&&ap(y)&&ip(of(m),of(y))},lp=null,qs=null,ss=null,zo=null,cp=null,qw=r=>{if(!le)return Os(r);cp=r,queueMicrotask(()=>{cp===r&&(cp=null,Os(r))})},Tl=r=>{lp=r;let a,d;qs=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),!qs&&ap(C)&&(qs={index:y,id:C.id}),a&&d&&qs)break}Un(Pe,r,kt),nr()?.updateInlineArtifactBlocks(Pe,Fn.artifacts,{suppressTransition:kn}),Uw(),Qi(r),Rs(r),hr(!kn),kw(r),r.length===0&&(ro(),Ni=!0,ul=!1,_s=null,gl=!1),!Ud||Bs?(Ud=!0,Yr=a?.id??null,$d=d?.id??null):a&&a.id!==Yr?(Yr=a.id,xw(a.id)):d&&d.id!==$d&&Aw(),d&&($d=d.id),Tw(r);let m=je.lastUserMessageId;a&&a.id!==m&&(je.lastUserMessageId=a.id,w.emit("user:message",a)),je.lastUserMessageWasVoice=!!a?.viaVoice,qw(r),Fs()},dp=()=>{zo!==null&&(cancelAnimationFrame(zo),zo=null);let r=ss;ss=null,r&&Tl(r)},rf=()=>{zo!==null&&cancelAnimationFrame(zo),zo=null,ss=null},zw=r=>{let a=ss??lp;if(kn&&a&&qs&&$w(a,r,qs)){ss=r,zo===null&&(zo=requestAnimationFrame(()=>{zo=null;let d=ss;ss=null,d&&Tl(d)}));return}if(r.length===0){rf(),Tl(r);return}dp(),Tl(r)};T=new Ic(o,{onMessagesChanged(r){zw(r)},onStatusChanged(r){let a=o.statusIndicator??{};Ka(st,(m=>m==="idle"?a.idleText??_t.idle:m==="connecting"?a.connectingText??_t.connecting:m==="connected"?a.connectedText??_t.connected:m==="error"?a.errorText??_t.error:m==="paused"?a.pausedText??_t.paused:m==="resuming"?a.resumingText??_t.resuming:_t[m])(r),a,r),Ro()},onStreamingChanged(r){r||(T?.getMessages().length===0?rf():dp()),kn=r,Ki(r),Ro(),T&&Un(Pe,T.getMessages(),kt),r||(hr(!0),ww(),Im=!0,T&&Lm(T.getMessages(),Ir(o))),Ut(),Xa(r?"Responding\u2026":"Response complete."),Fs()},onVoiceStatusChanged(r){if(w.emit("voice:status",{status:r,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(r){case"listening":Qo(),ei();break;case"processing":Qo(),VS();break;case"speaking":Qo(),KS();break;default:r==="idle"&&T.isBargeInActive()?(Qo(),ei(),oe?.setAttribute("aria-label","End voice session")):(je.active=!1,Qo(),Fo("system"),oo());break}},onArtifactsState(r){Fn=r,r.artifacts.length===0&&(Is=!1),nr()?.updateInlineArtifactBlocks(Pe,r.artifacts,{suppressTransition:kn}),no(),Os()},onHistoryStateChanged(r){Pt(r)},onHistoryNotice(r){wt(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})}},qo),at.current=T,ye.push(()=>T.cancel()),ye.push(()=>{T.destroy(),$o?.destroy()});let pp=null;if(T.onReadAloudChange((r,a)=>{am=r,lm=a,cm();let d=r??pp;r&&(pp=r);let m=d?T.getMessages().find(y=>y.id===d)??null:null;w.emit("message:read-aloud",{messageId:d,message:m,state:a,timestamp:Date.now()}),a==="idle"&&(pp=null)}),g=!0,Ud=!0,o.voiceRecognition?.provider?.type==="runtype")try{T.setupVoice()}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",r)}let jw=720,Vw=250,Qe=ou(o.features?.history?.copy),Ln=null,up=!1,it=null,kl=null,Pl="conversation",gp=null,an=null,wo=null,Il=T.getHistoryState(),mp=null,Xi=0,fp=null,Ll=null,Hl=null,hp=`persona-history-${Math.random().toString(36).slice(2,8)}`,yp=()=>o.features?.history?.enabled===!0,So=()=>yp()&&!!Ln&&!up,sf=()=>{let r=T.getStatus();return kn||r==="paused"||r==="resuming"},bp=()=>{let r=o.features?.history?.scope;if(r)return r;let a=o.getIdentityProof?"verified-user":"browser",d=Ln?.capabilities.scopes;return!d||d.includes(a)?a:d[0]??a},zs=()=>kl?.scope??bp(),af=()=>T.getClientSession()?.targetId??null,lf=r=>`${r.state}:${"reason"in r?r.reason:""}`,Kw=r=>{let a=lf(r);a!==mp&&(mp=a,w.emit("history:identityStatusChanged",{status:r,timestamp:Date.now()}))},Rl=r=>{r&&(Wo.textContent="",Wo.textContent=r)},cf=null,df=null,Gw=()=>{if(!yp())return null;let r=mC();if(r)return r();let a=o.features?.history?.provider;return a?typeof a!="function"?a:(cf!==a&&(cf=a,df=a()),df):T.isClientTokenMode()?fC({client:T.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:d=>T.bindActivatedSession(d),getClient:()=>T.getClient()}):null},pf=()=>{Ll?.(),Ll=null,Hl?.(),Hl=null,up=!1,Ln=Gw();let r={...qo};Ln?r.historyProvider=Ln:delete r.historyProvider,qo=r,T.setHistoryInternals(qo),Ln&&(Ll=Ln.subscribeAvailability?.(a=>{up=!a,a||wn({restoreFocus:!1}),wr()})??null,Hl=Ln.subscribeIdentityStatus(a=>Kw(a)),mp=lf(Ln.getIdentityStatus()))},vp=()=>{let r=o.features?.history?.presentation??"panel";if(r==="panel"||r==="auto"&&!(!Ce||Lt(o)))return"panel";let a=bo??ue;return(a.getBoundingClientRect().width||a.clientWidth)>=jw?"rail":"panel"},$n=(r,a)=>{a?(r.setAttribute("aria-hidden","true"),r.setAttribute("inert","")):(r.removeAttribute("aria-hidden"),r.removeAttribute("inert"))},Wl="data-persona-history-suppressed",Hn=null,Cr=null,is=null,Yi=null,Cp=null,uf="",gf=()=>Me===Cp?uf:o.layout?.showHeader===!1?"none":"",Qw=()=>de==="panel"&&!!is&&Yi===is.element&&o.layout?.showHeader!==!1&&gf()!=="none",Xw=()=>{for(let r of Array.from(Me.children))r!==Hn&&r.setAttribute(Wl,"")},Yw=()=>{for(let r of Array.from(ue.querySelectorAll(`[${Wl}]`)))r.removeAttribute(Wl)},Jw=()=>{let r=is;if(!r)return;if(Array.from(Me.children).some(m=>m!==Hn&&!m.hasAttribute(Wl))){Cr&&Cr!==Me&&(Cr.style.removeProperty("min-height"),Cr=null);let m=Me.offsetHeight;m>0&&(Me.style.minHeight=`${m}px`,Cr=Me)}Hn||(Hn=k("div","persona-history-header-host")),r.setHeaderPlacement("external");let d=r.getHeaderElement();d.parentNode!==Hn&&Hn.replaceChildren(d),Hn.parentNode!==Me&&Me.appendChild(Hn),Xw()},mf=()=>{Cr&&(Cr.style.removeProperty("min-height"),Cr=null),Hn&&(is?.setHeaderPlacement("inline"),Hn.remove(),Hn=null,Yw())},Bl=null,wp=()=>{if(Bl){if(ne.style.display="none",$n(ne,!0),He.hidden=!0,$n(He,!0),Qw()){Jw(),Me.style.display=gf(),$n(Me,!1);return}mf(),Me.style.display="none",$n(Me,!0)}};Ot=wp;let Zw=r=>{let a=ne.style.display,d=He.hidden,m=He,y=Me,C=Me.style.display;Cp=y,uf=C,Bl=()=>{Bl=null,mf(),Cp=null,ne.style.display=a,$n(ne,!1),m.hidden=d,$n(m,!1),He!==m&&(He.hidden=!1,$n(He,!1)),y.style.display=C,$n(y,!1),Me!==y&&(Me.style.display=o.layout?.showHeader===!1?"none":"",$n(Me,!1))},He.parentNode?.insertBefore(r,He),wp()},js=null,as=null,Ji=null,Vs=null,ff=()=>[Me,Ne.closeButtonWrapper,Ne.clearChatButtonWrapper,ne,He],eS=52,_l=()=>o.features?.history?.rail?.collapsible!==!1,Ks=()=>o.features?.history?.rail?.side==="right"?"right":"left",Sp=200,xp=400,Ap=r=>Math.min(xp,Math.max(Sp,Math.round(r))),tS=()=>o.features?.history?.rail?.resizable===!0,Zi,nS=()=>{if(Zi===void 0&&(Zi=null,o.persistState!==!1))try{let r=Number(window.localStorage.getItem(`${Yn()}rail-width`));r&&(Zi=r)}catch{}return Zi},ea=()=>Ap(nS()??o.features?.history?.rail?.width??260),oS=r=>{if(Zi=r,o.persistState!==!1)try{window.localStorage.setItem(`${Yn()}rail-width`,String(r))}catch{}},Ol=()=>_l()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Wt=!1,hf=r=>{let a=k("img");return a.src=r,a.alt="",a.setAttribute("aria-hidden","true"),a},rS=()=>{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=hf(r.iconUrl):d=r.icon?he(r.icon,20):null),d?d.cloneNode(!0):null}},sS=()=>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=hf(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)}}}})}})??[],iS=r=>{let a=sS();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},ta=null,yf=()=>`${Yn()}rail-collapsed`,Mp=()=>{if(ta===null&&(ta=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let r=window.localStorage.getItem(yf());r&&(ta=r==="1")}catch{}return ta},Ep=r=>{if(ta=r,o.persistState!==!1)try{window.localStorage.setItem(yf(),r?"1":"0")}catch{}},na=()=>de==="rail"&&_l()&&!Ol()&&Mp(),Tp=()=>{},bf=()=>{if(Ol()){Tp();return}Ep(!Mp()),it?.view.setCollapsed(na()),Be(),Cn()},kp=()=>{let r=o.features?.history?.rail?.collapseShortcut;return!r||!Yc(r)?null:{combo:r,hint:Jc(r),aria:Wa(r)}},vf=()=>{p.forEach(a=>a()),p=[];let r=kp();r&&p.push(c.register({id:"history-rail-collapse",combo:r.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ae&&de==="rail"&&_l()||Qs(),run:()=>Ol()?Tp():bf()}));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}`}))};vf();let aS=300,Dl="var(--persona-history-overlay-margin,8px)",qn=null,jo=null,Nl=0,Vo=null,Gs=null,ls=!1,Pp=0,Cf=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Qs=()=>So()&&Ol()&&(de??vp())==="rail",lS=()=>ae&&!Wt,oa=()=>{Gs!==null&&clearTimeout(Gs),Gs=null},cS=()=>{Tg().catch(()=>{})},wf=()=>{oa(),Wt&&(Gs=setTimeout(()=>{Gs=null,!(ls||!Wt)&&(Vo?.contains(document.activeElement)||wn({restoreFocus:!1}))},aS))},dS=(r,a)=>{let d=Vo?.getBoundingClientRect();if(!d)return!1;let m=qn?.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},Ip=r=>{Wt&&(ls=dS(r.clientX,r.clientY),ls?oa():Gs===null&&wf())},Sf=r=>{ae||!Qs()||(Wt=!0,sa({invoker:qn,keyboard:r?.keyboard===!0}).then(()=>{ae?!ls&&document.activeElement!==qn&&wn():Wt=!1}))},xf=()=>{let r=Yi?.querySelector('[data-persona-history-focus="collapse"]');r&&(r.setAttribute("aria-label",Wt?Qe.expandLabel:Qe.collapseLabel),r.setAttribute("aria-expanded",Wt?"false":"true"))},Af=()=>{Ep(!1);let r=it;if(!Wt||!r){sa({invoker:qn});return}let a=document.activeElement===qn;Wt=!1,Fl(),r.element.remove(),Hp(r.element),xf(),a&&$l(),Cn(),wr()},pS=()=>{Ep(!0),wn()};Tp=()=>{!ae||Wt?Af():pS()};let uS=()=>{let r=kp(),a=vs({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":hp,...r?{"aria-keyshortcuts":r.aria}:{}}}),d=a.button;d.addEventListener("mouseenter",()=>{ls=!0,oa(),!(Cf()||Date.now()<Pp)&&Sf()}),d.addEventListener("mouseleave",()=>{ls=!1,Pp=0,wf()}),d.addEventListener("focus",()=>{ae||cS()}),d.addEventListener("click",m=>{So()&&(m.detail!==0&&Cf()&&!ae?Sf():Af())}),qn=d,jo=a.wrapper},ra=()=>{if(jo&&!jo.isConnected&&(jo=null,qn=null),!Qs()){jo?.remove(),jo=null,qn=null;return}qn||uS();let r=jo,a=qn;if(!r||!a)return;let d=Ks()!=="right"?Me.firstChild:null;(d??Me.lastChild)!==r&&Me.insertBefore(r,d),r.style.display=lS()||Nl>0?"none":"",a.setAttribute("aria-label",Qe.expandLabel),a.setAttribute("aria-expanded",ae?"true":"false"),Vo&&Be()},Mf=r=>{if(!Wt)return;let a=r.target;a instanceof Node&&(Vo?.contains(a)||jo?.contains(a)||a instanceof Element&&a.closest('.persona-dropdown-menu,[role="alertdialog"]')||wn({restoreFocus:!1}))};document.addEventListener("pointerdown",Mf,!0),ye.push(()=>{document.removeEventListener("pointerdown",Mf,!0),document.removeEventListener("pointermove",Ip),Xs?.(),oa()});let Lp=null,Xs=null,Ef=16,Tf=r=>{oS(Ap(r)),Be(),Cn()},gS=()=>{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(Sp)),r.setAttribute("aria-valuemax",String(xp)),r.addEventListener("pointerdown",a=>{let d=as;if(!d||a.button!==0)return;a.preventDefault(),Xs?.();let m=a.clientX,y=d.getBoundingClientRect().width||ea(),C=Ks()==="right"?-1:1,W=y,z=t.ownerDocument;d.style.transition="none";let q=Y=>{W=Ap(y+C*(Y.clientX-m)),d.style.flex=`0 0 ${W}px`,r.setAttribute("aria-valuenow",String(W))},j=()=>{Xs=null,z.removeEventListener("pointermove",q),z.removeEventListener("pointerup",j),z.removeEventListener("pointercancel",j),d.style.removeProperty("transition");try{r.releasePointerCapture(a.pointerId)}catch{}Tf(W)};Xs=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=Ks()==="right"?-Ef:Ef,m=ea(),y=a.key==="ArrowRight"?m+d:a.key==="ArrowLeft"?m-d:a.key==="Home"?Sp:a.key==="End"?xp:null;y!==null&&(a.preventDefault(),Tf(y))}),r},mS=(r,a)=>{if(!tS()||na()){Xs?.(),Lp?.remove();return}let d=Lp??gS();Lp=d,d.setAttribute("aria-label",Qe.resizeLabel),d.setAttribute("aria-valuenow",String(ea())),d.nextElementSibling!==a&&r.insertBefore(d,a)};Be=()=>{it?.view.setRailSide(Ks());let r=Ks()==="right",a=Vo;if(a){let z=qn?qn.getBoundingClientRect().bottom-ue.getBoundingClientRect().top:0;a.style.top=`calc(${Math.max(0,Math.round(z))}px + ${Dl})`,a.style.width=`${ea()}px`,a.style.left=r?"":Dl,a.style.right=r?Dl:""}let d=as,m=js,y=Ji;if(!d||!m||!y)return;d.style.flex=`0 0 ${na()?eS:ea()}px`;let C="1px solid var(--persona-divider,#e5e7eb)";d.style.borderRight=r?"":C,d.style.borderLeft=r?C:"";let W=r?y:d;m.firstElementChild!==W&&m.append(W,r?d:y),mS(m,r?d:y)};let kf=r=>{if(Vs&&as){Vs.replaceWith(r),Vs=null,Be();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",ue.insertBefore(a,Me.parentNode===ue?Me:ne);for(let y of ff())y?.parentNode===ue&&d.appendChild(y);a.append(m,d),m.appendChild(r),js=a,as=m,Ji=d,Be()},fS=()=>{if(js)return;let r=k("div","persona-history-rail-placeholder");r.style.cssText="flex:1 1 auto;min-height:0",Vs=r,kf(r),Cn()},Pf=()=>{Vs&&(Fl(),Cn())},hS=r=>{let a=k("div","persona-history-rail-overlay");a.style.cssText=`position:absolute;bottom:${Dl};display:flex;overflow:hidden;z-index:${mc-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))`,ue.style.position="relative",ue.appendChild(a),a.appendChild(r),document.addEventListener("pointermove",Ip),Vo=a,Be(),xf()},Fl=()=>{Bl?.(),Vo&&(ls&&(Pp=Date.now()+150),document.removeEventListener("pointermove",Ip),Vo.remove(),Vo=null);let r=js;if(r){Xs?.();for(let a of ff())a&&r.contains(a)&&ue.insertBefore(a,r);r.remove(),js=null,as=null,Ji=null,Vs=null}},If=r=>{Yi=r,r.id=hp,r.style.flex="1 1 auto",r.style.minHeight="0"},Hp=r=>{If(r),(de!=="rail"||Wt)&&Pf(),de!=="rail"?Zw(r):Wt?hS(r):kf(r)},Ul=()=>{if(ra(),Uf(),!ae||!it)return;let r=vp();if(r===de)return;let a=document.activeElement,d=a instanceof HTMLElement&&(it.element.contains(a)||Hn?.contains(a)===!0)?a:null;Fl(),it.element.remove(),it.view.setHeaderPlacement("inline"),de=r,it.view.setPresentation(r),it.view.setCollapsed(na()),it.requestRender(),it.element.isConnected||Hp(it.element),d?.isConnected?d.focus():$l(),Ut(),Cn(),wr()},Lf=(r,a)=>Hn?.querySelector(a)??r.querySelector(a),$l=()=>{let r=it?.element??Yi;if(!r)return;let a=Lf(r,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(a){a.focus();return}let d=Lf(r,".persona-history-title")??r;d.tabIndex=-1,d.focus()},sa=async r=>{if(!So()||ae)return;let a=Ln;if(!a)return;if(!Wt&&Qs()&&Mp()){ra();return}ql();let d=++Xi;Pl=r?.returnSurface??"conversation",gp=r?.invoker??an;let m=Qs()&&!Wt;m&&(Nl+=1,ra(),fS());let y;try{y=await Tg()}catch{Rl(Qe.openHistoryLabel),m&&(Nl-=1,d===Xi&&(Pf(),ra()));return}if(m&&(Nl-=1),d!==Xi||ae)return;kl={scope:bp()},de=vp(),ae=!0;let C=de==="panel"&&o.layout?.showHeader!==!1&&Me.style.display!=="none"?"external":"inline",W=o.features?.history?.rowAvatar,z=kp(),q=z?{hint:z.hint,aria:z.aria}:null,j={provider:a,context:kl,targetId:af(),presentation:de,collapsible:_l(),collapsed:na(),railSide:Ks(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:rS(),onToggleCollapse:bf,...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:W===!1?!1:typeof W=="string"?W:o.launcher?.iconUrl,activeConversationId:T.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:Y=>Wp(Y,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Y=>cs(Y),attachTooltip:Xt,onStartNew:()=>Bp({focusComposer:!0}),onClose:()=>wn(),onRequestDeleteConversation:Y=>Ff(Y),onRequestClearHistory:()=>SS(),...a.resetDevice?{onRequestResetIdentity:()=>xS()}:{}};it=gC({plugins:l,config:o,getPresentation:()=>de??"panel",getReturnSurface:()=>Pl,close:()=>wn(),createView:({slots:Y,renderDom:se,onModelChange:ge,railSections:Xe})=>(is=y.createHistoryView({...j,railSections:iS(Xe),slots:Y,renderDom:se,onModelChange:ge,onAnnounce:Rl}),is),onElementChanged:(Y,se)=>{if(!se?.isConnected)return Hp(Y);If(Y),se.replaceWith(Y),wp()}}),it.view.setNewConversationRequired(Il.recovery==="new_conversation_required"),r?.focus!==!1&&(de!=="rail"||r?.keyboard===!0)&&$l(),Ut(),Cn(),wr(),w.emit("history:opened",{presentation:de,returnSurface:Pl,timestamp:Date.now()})},ql=()=>{},wn=r=>{if(!ae)return;Xi+=1;let a=Pl,d=gp,m=it,y=r?.restoreFocus!==!1;ae=!1;let C=!1,W=null,z=()=>{if(!C){if(C=!0,ql=()=>{},W!==null&&clearTimeout(W),Wt=!1,oa(),Fl(),m?.dispose(),m?.view.destroy(),m?.element.remove(),it===m&&(it=null,is=null,Yi=null,de=null,kl=null,gp=null),Ut(),Cn(),wr(),y){let j=d??an;j?.isConnected?j.focus():ns()}w.emit("history:closed",{returnSurface:a,timestamp:Date.now()})}},q=m&&m.element===m.view.element?m.view.playExit():null;if(!q){z();return}ql=z,W=setTimeout(z,Vw),q.then(z)},Hf=r=>{if(!(r.key!=="Escape"||!ae||!it)){if(de==="rail"){let a=r.target;if(!(a instanceof Node)||!(it.element.contains(a)||Wt&&jo?.contains(a)===!0))return}r.preventDefault(),r.stopPropagation(),wn()}};ue.addEventListener("keydown",Hf),ye.push(()=>ue.removeEventListener("keydown",Hf));let zl=null,Rf=!1,ia=()=>{if(!ar)return;let r=o.layout?.header?.titleSource==="conversation",a=r&&zl?.trim()||null;ar.textContent=a??o.launcher?.title??"Chat Assistant";let d=ar.closest(".persona-combo-btn");if(!d)return;let m=!r||T.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")},yS=r=>{r!==zl&&(zl=r,ia())},cs=r=>{Rf=r?.starred===!0,yS(r&&r.title.trim()||null),ia()};ia(),ue.addEventListener("persona:title-menu-builtin",r=>{let a=r.detail?.actionId,d=T.getActiveConversationId();d&&(a==="delete"?Ff(d):a==="star"&&T.canUpdateConversations()&&_p(d,{starred:!Rf}).catch(()=>{}))});let jl=0,bS=250,Vl=null,Kl=()=>{Vl&&clearTimeout(Vl),Vl=null};ye.push(Kl);let Wf=()=>{Kl();let r=os;r&&(Gi=!0,r.hidden=!1,Pe.style.display="none",Qi())},Gl=()=>{jl+=1,Kl(),os&&(os.remove(),os=null,Gi=!1,Pe.style.removeProperty("display"),$n(He,!1),Qi())},vS=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Pe.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Rp=(r,a)=>X("div",{className:Wn("persona-conversation-loading-bubble",a&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:r}}),Bf=()=>X("div",{className:"persona-conversation-loading-body"},Rp("58%",!1),Rp("72%",!0),Rp("44%",!1)),_f=r=>{os?.remove(),os=r,r.hidden=!Gi,ne.insertBefore(r,Pe),Kl(),Gi||(Vl=setTimeout(Wf,bS)),$n(He,!0)},CS=()=>{let r={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Bf},a=null,d=l.find(m=>m.renderLoadingIndicator);d?.renderLoadingIndicator&&(a=d.renderLoadingIndicator(r)),a===null&&o.loadingIndicator?.render&&(a=o.loadingIndicator.render(r)),_f(X("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},a??Bf()))},wS=r=>{let a=()=>{Wp(r,{focusComposer:!0}).catch(()=>{})},d=So()?()=>{Gl(),sa()}:void 0,m=(z,q)=>{let j=X("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:z});return j.addEventListener("click",q),j},y=()=>X("div",{className:"persona-conversation-loading-error-body"},X("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),X("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}),W=null;for(let z of l)if(z.renderHistoryOpenError){try{W=z.renderHistoryOpenError(C)}catch(q){console.warn("[persona] renderHistoryOpenError threw",q),W=null}if(W)break}_f(X("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},W??y())),Wf()};w.on("history:closed",()=>{os&&$n(He,!0)});let Wp=async(r,{focusComposer:a=!1}={})=>{let d=zs(),m=!!it;it?.view.setActiveConversationId(r),Gl();let y=jl;CS(),ae&&(de==="panel"||Wt)&&wn({restoreFocus:!1}),Bs=!0;try{await T.openConversation(r,{scope:d})}catch(C){throw y===jl&&wS(r),C}finally{Bs=!1}y===jl&&(Gl(),Rt.clear(),ro(),vn(),Gd()||bl(),vS(),Ko(),m||cs(null),w.emit("history:conversationOpened",{conversationId:r,title:zl,scope:d,timestamp:Date.now()}),a&&ns())},Bp=async({focusComposer:r=!1}={})=>{Gl(),await T.startNewConversation({scope:zs()}),cs(null),Rt.clear(),ro(),vn(),bl(),Ko();let a=T.getActiveConversationId();it?.view.setActiveConversationId(a),w.emit("history:conversationStarted",{conversationId:a,timestamp:Date.now()}),ae&&(de==="panel"||Wt)&&wn({restoreFocus:!1}),r&&ns()},_p=async(r,a)=>{let d=await T.updateConversation(r,{...a,...a.title!==void 0?{title:a.title.trim()}:{}});return it?.view.applyConversationSummary(d),!it&&r===T.getActiveConversationId()&&cs(d),d},Of=async r=>{let a=zs(),d=T.getActiveConversationId()===r;await T.deleteConversation(r,{scope:a}),it?.view.removeConversationSummary(r),d&&(cs(null),Rt.clear(),ro(),vn(),Ko()),w.emit("history:conversationDeleted",{conversationId:r,scope:a,wasActive:d,timestamp:Date.now()})},Df=async r=>{let a=r?.scope??zs(),d=r?.allTargets?null:r?.targetId??af(),m=await T.clearConversationHistory({...d?{targetId:d}:{},scope:a});return cs(null),Rt.clear(),ro(),vn(),Ko(),w.emit("history:cleared",{deleted:m.deleted,scope:a,targetId:d,timestamp:Date.now()}),m},Nf=async()=>{if(!Ln?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let r=!1;try{r=(await T.resetHistoryDevice()).remoteRevocationConfirmed}finally{cs(null),T.clearArtifacts(),Rt.clear(),lp=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),ee={},Le.syncFromMetadata(),G?.clear&&fl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ro(),vn(),Ko(),wn({restoreFocus:!1}),ns(),be||xt?.launcher.element.focus()}return Rl(r?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),w.emit("history:identityReset",{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},Op=()=>bo?xe:ue,Ff=async r=>await yd({host:Op(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Of(r),"deleted"):"cancelled",SS=async()=>{let r=zs()==="verified-user";return await yd({host:Op(),title:Qe.clearHistoryConfirmTitle,description:r?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Df(),"cleared"):"cancelled"},xS=async()=>{if(!await yd({host:Op(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:a}=await Nf();return{outcome:"reset",remoteRevocationConfirmed:a}},zn=k("button","persona-history-earlier");zn.type="button",zn.textContent=Qe.showEarlierMessagesLabel,zn.setAttribute("data-persona-history-earlier",""),Object.assign(zn.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 Ko=()=>{if(!(So()&&!!Il.nextMessageCursor&&!!T.getActiveConversationId())){zn.remove();return}zn.textContent=Qe.showEarlierMessagesLabel,zn.parentNode!==ne&&ne.insertBefore(zn,ne.firstChild)};zn.addEventListener("click",()=>{let r=T.getActiveConversationId(),a=Il.nextMessageCursor;if(!r||!a||zn.disabled)return;zn.disabled=!0;let d=ne.scrollHeight,m=ne.scrollTop;T.loadOlderMessages(r,a,{scope:zs()}).then(()=>{ne.scrollTop=m+(ne.scrollHeight-d),Cn()}).catch(()=>{}).finally(()=>{zn.disabled=!1,Ko()})});let AS=()=>{let r=vs({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(!(!So()||sf())){if(ae){wn();return}sa({invoker:r.button,keyboard:a.detail===0})}}),r},Uf=()=>{if(!So()){wo?.remove(),an=null,wo=null;return}if(wo&&!wo.isConnected&&(an=null,wo=null),!an&&Me){let m=AS();an=m.button,wo=m.wrapper;let y=Ne.clearChatButtonWrapper||Ne.closeButtonWrapper;y?.parentNode&&Me.contains(y)?y.parentNode.insertBefore(wo,y):Me.appendChild(wo)}if(!an||!wo)return;let r=Qs()||ae&&de==="rail";if(wo.style.display=r?"none":"",r){document.activeElement===an&&$l();return}let a=sf();an.disabled=a,an.setAttribute("aria-disabled",a?"true":"false");let d=a?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;an.setAttribute("aria-label",d),(o.features?.history?.presentation??"panel")==="panel"?(an.removeAttribute("aria-expanded"),an.removeAttribute("aria-controls")):(an.setAttribute("aria-expanded",ae?"true":"false"),an.setAttribute("aria-controls",hp))},Ql=!1,MS=()=>{let r=Ne.clearChatButton;if(r){if(So()){Ql||(fp=r.getAttribute("aria-label")??"",Ql=!0),r.setAttribute("aria-label",Qe.newConversationLabel),r.removeAttribute("title");return}Ql&&(Ql=!1,fp&&r.setAttribute("aria-label",fp))}},wr=()=>{Qe=ou(o.features?.history?.copy),Uf(),ra(),MS(),Ko()};Ro=wr,Pt=r=>{Il=r,it?.view.setNewConversationRequired(r.recovery==="new_conversation_required"),Ki(r.sendBlocked||kn),Ko()},wt=r=>{(r.code==="history_continuity_reset"||r.code==="conversation_deleted_recovered")&&(Rt.clear(),ro(),vn()),Rl(r.message),it?.view.refresh()},pf(),wr(),ye.push(()=>{Ll?.(),Hl?.(),Xi+=1,ql(),it?.dispose(),it?.view.destroy(),it=null}),o.clientToken&&T.initClientSession().then(()=>{if(So())return T.reconcileBootConversation({scope:bp()})}).then(()=>{Ko()}).catch(r=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",r)}),(en||o.onSSEEvent)&&T.setSSEEventCallback((r,a)=>{o.onSSEEvent?.(r,a),te(r,a)});let $f=()=>{let r=o.resume??(le?qo.getStoredResumableHandle?.():null);r&&typeof o.reconnectStream=="function"&&T.resumeFromHandle(r)};S?S.then(r=>{if(r){if(r.metadata&&(ee=Lg(r.metadata),Le.syncFromMetadata()),r.messages?.length){Bs=!0;try{T.hydrateMessages(r.messages)}finally{Bs=!1}Sl()}r.artifacts?.length&&T.hydrateArtifacts(r.artifacts,r.selectedArtifactId??null),Om(r.draft)}}).catch(r=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",r)}).finally(()=>{ep=!0,B(),$f()}):(Om(I),$f());let ES=()=>{!Re()||be||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ct(!0,"auto")},TS=(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),ST(y)}}:r:a,Dp=()=>{let a=pe.getInlineMessageFields?.();return a&&a.contentSegments.some(m=>m.kind==="mention")?a.contentSegments:void 0},Go=!1,ds=null,Xl=()=>{pe.value="",pe.style.height="auto",fo(),la()},Np="data-persona-composer-notice",Ys=null;function kS(r){Xa(r),!(Re()||!st)&&(st.hasAttribute(Ei)||(st.setAttribute(Np,""),st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.textContent=r,Ys&&clearTimeout(Ys),Ys=setTimeout(()=>{if(Ys=null,!!st?.hasAttribute(Np)&&(st.removeAttribute(Np),st.removeAttribute("role"),st.removeAttribute("aria-live"),g)){let a=T.getStatus();Ka(st,mn(a),o.statusIndicator??{},a)}},4e3)))}function PS(){let r=Se.getState().pendingSubmission;r&&(Ts(void 0),pe&&(pe.value=r.text,pe.dispatchEvent(new Event("input",{bubbles:!0})),fo()),r.options.selectedModelId&&(Se.setSelectedModelId(r.options.selectedModelId),cr?.repaint()),r.options.activeModeIds?.length&&el(r.options.activeModeIds),r.options.quote&&ho(r.options.quote),pe?.focus())}let IS=r=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",r)},qf=(r={})=>{let a=(r.overrideText??pe?.value??"").trim();return r.resolveInlineCommand&&a?(It?.takeInlineCommand(a)??Promise.resolve(null)).then(d=>zf(r,a,d)):zf(r,a,null)},zf=(r,a,d)=>{if(d?.kind==="action"){Xl(),It?.clear(),Nr();return}let m=d?.kind==="server"?d.mentions:null,y=d?.kind==="prompt"?d.sendText:a,C=r.pending?.contentParts,W=(Ye?.hasAttachments()??!1)||(C?.length??0)>0;if(!zb({text:y,hasAttachments:W,attachmentsReady:Ye?.isReady()??!0,hasMentions:It?.hasMentions()??!1,hasServerMentions:!!m,inputDisabled:br(),sendDisabled:ts()}))return;let z=T.isStreaming()?kd():"block";if(z==="defer-one"&&!r.pending){if(Se.getState().pendingSubmission){kS("One message is already queued. Edit or remove it first.");return}LS({intent:r,sendText:y,serverMentions:m});return}let q={text:y,mentionRefs:[...It?.getMentionRefs()??[],...m?.refs??[]],contentSegments:d?.kind==="prompt"?void 0:Dp(),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(!Ye?.hasAttachments())return;let dt=[...Ye.getContentParts()];return q.text&&dt.push(ko(q.text)),dt};q.contentParts=j();let Y=()=>{Gr(),ES();let dt=It?.collectForSubmit()??null,Kt=TS(dt,m),Bt=j();r.consumeDraft!==!1&&Xl();let Mt={selectedModelId:q.options.selectedModelId,activeModeIds:q.options.activeModeIds},tn=z==="interrupt";tn&&T.cancel(),T.sendMessage(q.text,{contentParts:Bt,mentions:Kt??void 0,contentSegments:q.contentSegments,viaVoice:q.viaVoice,composerOptions:Mt,...q.options.quote&&{quote:q.options.quote},...tn&&{interrupt:!0}}),Ye?.hasAttachments()&&Ye.clearAttachments(),dt&&It?.clear(),Nr();let Je=Se.getState().activeModeIds,nn=Lb(Je,o.composer?.modes);nn.length!==Je.length&&el(nn),Se.getState().quote&&ho(void 0),yl(),Rd.release(),eo()},se=o.composer?.onBeforeSend;if(!se){Y();return}let ge=new AbortController;ds=ge;let Xe=dt=>{if(ds=null,dt.status==="error"){IS(dt.error);return}dt.status==="proceed"&&Y()},lt=jb(se,q,ge.signal);if(!(lt instanceof Promise)){Xe(lt);return}return Se.setPreparing(!0),lt.then(Xe).finally(()=>Se.setPreparing(!1))};function LS(r){let a=Se.getState(),d=Ye?.hasAttachments()??!1,m=d?[...Ye.getContentParts()]:[];d&&r.sendText&&m.push(ko(r.sendText));let y=Du({text:r.sendText,contentParts:m.length?m:void 0,mentionRefs:[...It?.getMentionRefs()??[],...r.serverMentions?.refs??[]],contentSegments:Dp(),options:{...a.selectedModelId&&{selectedModelId:a.selectedModelId},...a.activeModeIds.length>0&&{activeModeIds:[...a.activeModeIds]},...a.quote&&{quote:{...a.quote}}},viaVoice:r.intent.viaVoice});Ts(y),r.intent.consumeDraft!==!1&&Xl(),d&&Ye.clearAttachments(),It?.clear(),Nr(),a.quote&&ho(void 0),yl(),Rd.release(),eo(),Xa("Message queued. It sends when the response finishes.")}function HS(){let r=Se.getState().pendingSubmission;r&&(Ts(void 0),Jl(r.text,{consumeDraft:!1,pending:r}))}function RS(r){if(o.messageActions?.showEdit!==!0)return;let a=T.getMessages().find(d=>d.id===r);!a||!hu(a)||Kr!==r&&(Gr(),Kr=r,gr=_b({messageId:r,initialText:a.content,onSave:d=>WS(r,d),onCancel:()=>Gr()}),Rt.delete(r),Un(Pe,T.getMessages(),kt),gr.focus())}function WS(r,a){let d=gr;if(Kr=null,gr=null,d?.destroy(),Rt.delete(r),!T.resubmitFrom(r,{reason:"edit",replacement:{text:a,mentionRefs:[],options:{}}})){Un(Pe,T.getMessages(),kt);return}Cn()}function BS(r){if(T.isStreaming())return;let a=fu(T.getMessages(),r);a&&(Gr(),T.resubmitFrom(a,{reason:"retry"})&&Cn())}tl={regenerate:BS,edit:RS,quote:r=>{let d=T.getMessages().find(m=>m.id===r)?.content?.trim();d&&(ho({text:d,messageId:r}),pe?.focus())}};let aa=async r=>{if(!Go){Go=!0;try{await qf({resolveInlineCommand:!0,...r})}finally{Go=!1}}};function Yl(r){ts()||(Xl(),Jl(r,{consumeDraft:!1}))}let Jl=(r,a)=>{if(Go)return;Go=!0;let d=()=>{Go=!1};try{let m=qf({...a,overrideText:r});m instanceof Promise?m.finally(d):d()}catch(m){throw d(),m}},_S=r=>{if(r.preventDefault(),T.isStreaming()){T.cancel(),xn?.reset(),Q?.update();return}Go||aa()},OS=()=>o.features?.composerHistory!==!1,Fp={...zu},Up=!1,la=()=>{Fp={...zu}},DS=()=>T.getMessages().filter(r=>r.role==="user").map(r=>r.content??"").filter(r=>r.length>0),NS=r=>{if(!pe)return;Up=!0,pe.value=r,pe.dispatchEvent(new Event("input",{bubbles:!0})),Up=!1;let a=pe.value.length;pe.setSelectionRange(a,a)},FS=r=>{Up||(r.isComposing||It?.handleInput(r.inputType??void 0),la())},US=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Ia(pe)}),$S=r=>{if(pe&&!br()&&!(!r.isComposing&&It?.handleKeydown(r))){if(OS()&&(r.key==="ArrowUp"||r.key==="ArrowDown")&&!r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.isComposing){let a=pe.selectionStart===0&&pe.selectionEnd===0,d=iv({direction:r.key==="ArrowUp"?"up":"down",history:DS(),currentValue:pe.value,atStart:a,state:Fp});if(Fp=d.state,d.handled){r.preventDefault(),d.value!==void 0&&NS(d.value);return}}if(fb(r,US())){if(T.isStreaming()){if(r.preventDefault(),kd()==="block"||Go||ts())return;la(),aa();return}if(Go){r.preventDefault();return}if(ts()){r.preventDefault();return}la(),r.preventDefault(),Ae.click()}}},jf=r=>{if(!(r.key!=="Escape"||r.isComposing)&&r.composedPath().includes(ue)){if(ds){ds.abort(),ds=null,r.preventDefault(),r.stopImmediatePropagation();return}T.isStreaming()&&(T.cancel(),xn?.reset(),Q?.update(),la(),r.preventDefault(),r.stopImmediatePropagation())}},qS=async r=>{if(o.attachments?.enabled!==!0||!Ye||br())return;let a=bT(r.clipboardData);a.length!==0&&(r.preventDefault(),await Ye.handleFiles(a))},jn=null,xo=!1,Js=null,ht=null,$p=()=>o.voiceRecognition?.completionBehavior==="review";function ps(r){oe?.setAttribute("data-state",r),r==="recording"?jS():Vp()}let Vf="--persona-voice-level",qp=.5,Zs=null,zp=-1,Zl=0,Kf=()=>{let r=[],a=En??oe?.parentElement??null;return a&&r.push(a),He&&r.push(He),r},jp=r=>{let a=Math.round(Math.max(0,Math.min(1,r))*100)/100;if(a!==zp){zp=a;for(let d of Kf())d.style.setProperty(Vf,String(a))}},zS=()=>{zp=-1,Zl=0;for(let r of Kf())r.style.removeProperty(Vf)};function jS(){if(Zs!==null)return;if(typeof requestAnimationFrame!="function"){jp(g?T.getVoiceLevel()??qp:qp);return}let r=()=>{Zs=requestAnimationFrame(r);let a=g?T.getVoiceLevel():null;if(a===null){jp(qp);return}Zl+=(a-Zl)*.3,jp(Zl)};Zs=requestAnimationFrame(r)}function Vp(){Zs!==null&&(cancelAnimationFrame(Zs),Zs=null),zS()}let Gf=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ec=(r="user")=>{if(xo||T.isStreaming())return;let a=Gf();if(!a)return;jn=new a;let d=o.voiceRecognition??{},m=d.pauseDuration??2e3;jn.continuous=d.provider?.browser?.continuous??!0,jn.interimResults=!0,jn.lang=d.provider?.browser?.language??"en-US";let y=pe.value;jn.onresult=C=>{let W="",z="";for(let j=0;j<C.results.length;j++){let Y=C.results[j],se=Y[0].transcript;Y.isFinal?W+=se+" ":z=se}let q=y+W+z;pe.value=q,fo(),Js&&clearTimeout(Js),(W||z)&&(Js=window.setTimeout(()=>{if(pe.value.trim()&&jn&&xo){if(Sr(),$p())return;aa({viaVoice:!0})}},m))},jn.onerror=C=>{C.error!=="no-speech"&&Sr()},jn.onend=()=>{if(xo){let C=pe.value.trim();!$p()&&C&&C!==y.trim()&&aa({viaVoice:!0}),Sr()}};try{if(jn.start(),xo=!0,je.active=!0,r!=="system"&&(je.manuallyDeactivated=!1),Fo(r),oo(),eo(),oe){let C=o.voiceRecognition??{};ht={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:C.iconName??"mic",iconSize:parseFloat(C.iconSize??"")||cn};let W=C.recordingBackgroundColor,z=C.recordingIconColor,q=C.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),ps("recording"),oe.style.backgroundColor=W??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let j=oe.querySelector("svg");j&&j.setAttribute("stroke",z)}q&&(oe.style.borderColor=q),oe.setAttribute("aria-label","Stop voice recognition")}}catch{Sr("system")}},Sr=(r="user")=>{if(xo){if(xo=!1,Js&&(clearTimeout(Js),Js=null),jn){try{jn.stop()}catch{}jn=null}if(je.active=!1,Fo(r),oo(),eo(),oe){if(oe.classList.remove("persona-voice-recording"),ps("idle"),ht){oe.style.backgroundColor=ht.backgroundColor,oe.style.color=ht.color,oe.style.borderColor=ht.borderColor;let a=oe.querySelector("svg");a&&a.setAttribute("stroke",ht.color||"currentColor"),ht=null}oe.setAttribute("aria-label","Start voice recognition")}}},Kp=()=>{if(!oe||ht)return;let r=o.voiceRecognition??{};ht={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:r.iconName??"mic",iconSize:parseFloat(r.iconSize??"")||cn}},Gp=(r,a)=>{if(!oe)return;let d=oe.querySelector("svg");d&&d.remove();let m=ht?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||cn),y=he(r,m,a,1.5);y&&oe.appendChild(y)},tc=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ei=()=>{if(!oe)return;Kp();let r=o.voiceRecognition??{},a=r.recordingBackgroundColor,d=r.recordingIconColor,m=r.recordingBorderColor;if(tc(),oe.classList.add("persona-voice-recording"),ps("recording"),oe.style.backgroundColor=a??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=d??"var(--persona-voice-recording-indicator, #ffffff)",d){let y=oe.querySelector("svg");y&&y.setAttribute("stroke",d)}m&&(oe.style.borderColor=m),oe.setAttribute("aria-label","Stop voice recognition")},VS=()=>{if(!oe)return;Kp();let r=o.voiceRecognition??{},a=T.getVoiceInterruptionMode(),d=r.processingIconName??"loader",m=r.processingIconColor??ht?.color??"",y=r.processingBackgroundColor??ht?.backgroundColor??"",C=r.processingBorderColor??ht?.borderColor??"";tc(),oe.classList.add("persona-voice-processing"),ps("processing"),oe.style.backgroundColor=y,oe.style.borderColor=C;let W=m||"currentColor";oe.style.color=W,Gp(d,W),oe.setAttribute("aria-label","Processing voice input"),a==="none"&&(oe.style.cursor="default")},KS=()=>{if(!oe)return;Kp();let r=o.voiceRecognition??{},a=T.getVoiceInterruptionMode(),d=a==="cancel"?"square":a==="barge-in"?"mic":"volume-2",m=r.speakingIconName??d,y=r.speakingIconColor??(a==="barge-in"?r.recordingIconColor??ht?.color??"":ht?.color??""),C=r.speakingBackgroundColor??(a==="barge-in"?r.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":ht?.backgroundColor??""),W=r.speakingBorderColor??(a==="barge-in"?r.recordingBorderColor??"":ht?.borderColor??"");tc(),oe.classList.add("persona-voice-speaking"),ps("speaking"),oe.style.backgroundColor=C,oe.style.borderColor=W;let z=y||"currentColor";oe.style.color=z,Gp(m,z);let q=a==="cancel"?"Stop playback and re-record":a==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",q),a==="none"&&(oe.style.cursor="default"),a==="barge-in"&&oe.classList.add("persona-voice-recording")},Qo=()=>{oe&&(tc(),ps("idle"),ht&&(oe.style.backgroundColor=ht.backgroundColor??"",oe.style.color=ht.color??"",oe.style.borderColor=ht.borderColor??"",Gp(ht.iconName,ht.color||"currentColor"),ht=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},Qp=()=>{if(!br()){if(o.voiceRecognition?.provider?.type==="runtype"){let r=T.getVoiceStatus(),a=T.getVoiceInterruptionMode();if(a==="none"&&(r==="processing"||r==="speaking"))return;if(a==="cancel"&&(r==="processing"||r==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,oo(),Fo("user"),Qo()});return}T.toggleVoice().then(()=>{je.active=T.isVoiceActive(),je.manuallyDeactivated=!T.isVoiceActive(),oo(),Fo("user"),T.isVoiceActive()?ei():Qo()});return}if(xo){let r=pe.value.trim();je.manuallyDeactivated=!0,oo(),Sr("user"),r&&!$p()&&aa()}else je.manuallyDeactivated=!1,oo(),ec("user")}};Pd=Qp,oe&&ye.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),Qo()):Sr("system")});let GS=w.on("assistant:complete",()=>{Se.getState().pendingSubmission&&setTimeout(()=>{T.isStreaming()||HS()},0)});ye.push(GS);let QS=w.on("assistant:complete",()=>{Wm&&(je.active||je.manuallyDeactivated||Wm==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?T.toggleVoice().then(()=>{je.active=T.isVoiceActive(),Fo("auto"),T.isVoiceActive()&&ei()}):ec("auto"))},600))});ye.push(QS);let XS=w.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});ye.push(XS);let Qf=()=>{ct(!be,"user")},xt=null,ln=null;if(Ce&&!Re()){let{instance:r,element:a}=cg({config:o,plugins:l,onToggle:Qf});xt=r,r||(ln=a)}xt?t.appendChild(xt.element):ln&&t.appendChild(ln),Vi(),Rs(),Ml(),sp(),Ki(T.isStreaming()),Gd()||(Tn()==="follow"?hr(!0):bl()),fw(),we&&(!Ce||Re()?setTimeout(()=>ns(),0):be&&setTimeout(()=>ns(),200));let us=null,Xf=()=>{us&&(us.disconnect(),us.observe(He),us.observe(ue))},ca=()=>{if(Re()){Dr(),Vi();return}let r=Lt(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,W=m&&C&&Ce;try{if(W){Fr(),_i=cl();return}let z=!1;mt&&(mt=!1,Fr(),z=!0);let q=cl();if(!z&&q!==_i&&(Fr(),z=!0),_i=q,z&&sl(),!Ce&&!r){xe.style.height="",xe.style.width="";return}if(!a&&!r){let Y=o?.launcher?.width??o?.launcherWidth??er;xe.style.width=Y,xe.style.maxWidth=Y}ll(),bm()}finally{if(Dr(),Za(),Vi(),be&&Ce){let q=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),j=o.launcher?.sidebarMode??!1,Y=o.launcher?.mobileFullscreen??!0,se=Lt(o)&&Y&&q,ge=j||Y&&q&&Ce||se;if(ge&&!Co){let Xe=t.getRootNode(),lt=Xe instanceof ShadowRoot?Xe.host:t.closest(".persona-host");lt&&!vo&&(vo=ju(lt,o.launcher?.zIndex??sn)),Co=Vu(t.ownerDocument)}else ge||(vo?.(),vo=null,Co?.(),Co=null)}}};ca();let nc=t.ownerDocument.defaultView??window;if(nc.addEventListener("resize",ca),ye.push(()=>nc.removeEventListener("resize",ca)),typeof ResizeObserver<"u"){us=new ResizeObserver(()=>{Za()}),Xf(),ye.push(()=>{us?.disconnect(),us=null});let r=new ResizeObserver(()=>{Ul()});r.observe(ue),ye.push(()=>r.disconnect())}nc.addEventListener("resize",Ul),ye.push(()=>nc.removeEventListener("resize",Ul)),In=ne.scrollTop;let Yf=Yo(ne),Jf=()=>{let r=ne.scrollTop,a=Yo(ne),d=a<Yf;if(Yf=a,!lr()){In=r,Ut();return}let{action:m,nextLastScrollTop:y}=jh({following:Pn.isFollowing(),currentScrollTop:r,lastScrollTop:In,nearBottom:hs(ne,Do),userScrollThreshold:pw,isAutoScrolling:bn||pl||d,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(In=y,m==="resume"){vl()||vn();return}m==="pause"&&Ui()};if(ne.addEventListener("scroll",Jf,{passive:!0}),ye.push(()=>ne.removeEventListener("scroll",Jf)),typeof ResizeObserver<"u"){let r=new ResizeObserver(()=>{Sw(),ru(Pe)});r.observe(Pe),r.observe(ne),ye.push(()=>r.disconnect())}let Zf=()=>{lr()&&Pn.isFollowing()&&vl()&&Ui()},eh=ne.ownerDocument;eh.addEventListener("selectionchange",Zf),ye.push(()=>{eh.removeEventListener("selectionchange",Zf)});let YS=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),th=r=>{YS.has(r.key)&&(Jr(),Ng()&&lr()&&Pn.isFollowing()&&Ui())},nh=r=>{r.target?.closest("a, button, [tabindex], input, textarea, select")&&(Jr(),Ng()&&lr()&&Pn.isFollowing()&&Ui())};ne.addEventListener("keydown",th),ne.addEventListener("focusin",nh),ye.push(()=>{ne.removeEventListener("keydown",th),ne.removeEventListener("focusin",nh)});let oh=r=>{if(r.deltaY!==0&&Jr(),!lr())return;let a=Vh({following:Pn.isFollowing(),deltaY:r.deltaY,nearBottom:hs(ne,Do),resumeWhenNearBottom:!0});a==="pause"?Ui():a==="resume"&&!vl()&&vn()};ne.addEventListener("wheel",oh,{passive:!0}),ne.addEventListener("touchmove",Jr,{passive:!0}),ne.addEventListener("pointerdown",Jr,{passive:!0}),ye.push(()=>{ne.removeEventListener("touchmove",Jr),ne.removeEventListener("pointerdown",Jr)}),ye.push(()=>ne.removeEventListener("wheel",oh)),Ht.addEventListener("click",()=>{ro(),ne.scrollTop=ne.scrollHeight,In=ne.scrollTop,vn(),hr(!0),Ut()}),ye.push(()=>Ht.remove()),ye.push(()=>{Nm(),ro()});let rh=()=>{qe&&(zr&&(qe.removeEventListener("click",zr),zr=null),Ie()?(qe.style.display="",zr=()=>{ct(!1,"user")},qe.addEventListener("click",zr)):qe.style.display="none")};rh(),(()=>{let{clearChatButton:r}=Ne;r&&r.addEventListener("click",()=>{if(So()){Bp({focusComposer:!0}).catch(d=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",d)});return}T.clearMessages(),Rt.clear(),vn(),di(Ne.composerOverlay);try{localStorage.removeItem(Mi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mi}`)}catch(d){console.error("[AgentWidget] Failed to clear default localStorage:",d)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Mi)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&&fl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ee={},Le.syncFromMetadata(),Ye?.clearAttachments(),yl(),Ts(void 0),ho(void 0),Gr(),et?.clear(),xn?.reset(),Q?.update()})})();let sh=[["keydown",$S],["input",FS],["input",fo],["input",Nr],["keyup",Nr],["paste",qS],["focus",ZC]],ih=r=>{if(r)for(let[a,d]of sh)nt?.addListener(r,a,d)},JS=r=>{if(r)for(let[a,d]of sh)nt?.removeListener(r,a,d)},ah=()=>{nt&&(nt.addListener(nt.form,"submit",_S),nt.addListener(nt.footer,"click",Nr),ih(pe),oe&&nt.addListener(oe,"click",Qp))};ah();let lh=()=>{It?.onComposerSwap((r,a)=>{JS(a),pe=r,nt&&(nt.input=r),ih(r),Ld(),Jd(),fo()})};lh();let Xp=!1;function ch(){if(!Xp){Xp=!0;try{let r=pe?.value??"",a=He.ownerDocument??document,d=pe?a.activeElement===pe:!1;Vp(),nt?.destroy(),nt=null,It?.destroy(),It=null;let m=null,y=()=>(m=Re()?nd({config:o}):Fa({config:o}),m.footer),C=Qg(y)??y();An.replaceComposer(C),He=An.composer.footer;let W=m!==null&&C===m.footer;Ps=!W,Dg=W?m.setSendButtonMode:()=>{},Gg(He),Yg(He),Jg(),Zg(),em(),lh(),tm(),Hd(),nm(),ah();let z=qr.indexOf(Oo);Oo.destroy(),Oo=Da(ir),z>=0&&(qr[z]=Oo),pe&&(pe.value=r),fo(),Nr(),Ml(),Rs(),Ki(T.isStreaming()),je.active&&ps("recording"),Fr(),Xf(),Dr(),eo(),xl(),d&&pe?.focus()}finally{Xp=!1}}}let da=t.ownerDocument??document;da.addEventListener("keydown",jf,!0);let dh=()=>{zd()},ph=()=>{da.visibilityState==="hidden"&&zd()};typeof window<"u"&&(window.addEventListener("pagehide",dh),da.addEventListener("visibilitychange",ph),ye.push(()=>{window.removeEventListener("pagehide",dh),da.removeEventListener("visibilitychange",ph)}));let uh="persona-attachment-drop-active",pa=0,Yp=()=>{pa=0,ue.classList.remove(uh)},ti=()=>o.attachments?.enabled===!0&&Ye!==null&&!br(),gh=r=>{!bd(r.dataTransfer)||!ti()||(pa++,pa===1&&ue.classList.add(uh))},mh=r=>{!bd(r.dataTransfer)||!ti()||(pa--,pa<=0&&Yp())},fh=r=>{!bd(r.dataTransfer)||!ti()||(r.preventDefault(),r.dataTransfer.dropEffect="copy")},hh=r=>{if(!bd(r.dataTransfer)||!ti())return;r.preventDefault(),r.stopPropagation(),Yp();let a=Array.from(r.dataTransfer.files??[]);a.length!==0&&Ye.handleFiles(a)},xr=!0;ue.addEventListener("dragenter",gh,xr),ue.addEventListener("dragleave",mh,xr),t.addEventListener("dragover",fh,xr),t.addEventListener("drop",hh,xr);let oc=t.ownerDocument,yh=r=>{ti()&&r.preventDefault()},bh=r=>{ti()&&r.preventDefault()};oc.addEventListener("dragover",yh),oc.addEventListener("drop",bh),ye.push(()=>{nt?.destroy(),nt=null,Vp(),yo?.destroy(),yo=null,Bo?.destroy(),Bo=null,dr?.destroy(),dr=null,pr?.destroy(),pr=null,cr=null,Td=null,zd(),Fi.destroy(),Ys&&clearTimeout(Ys),Gr(),ds?.abort(),ds=null,Ye?.destroy(),Ye=null,Se.destroy(),da.removeEventListener("keydown",jf,!0),It?.destroy()}),ye.push(()=>{ue.removeEventListener("dragenter",gh,xr),ue.removeEventListener("dragleave",mh,xr),t.removeEventListener("dragover",fh,xr),t.removeEventListener("drop",hh,xr),oc.removeEventListener("dragover",yh),oc.removeEventListener("drop",bh),Yp()}),ye.push(()=>{T.cancel()}),xt?ye.push(()=>{xt?.destroy()}):ln&&ye.push(()=>{ln?.remove()});let At={update(r){let a=o.toolCall,d=o.messageActions,m=o.layout?.messages,y=o.colorScheme,C=o.loadingIndicator,W=o.iterationDisplay,z=o.features?.showReasoning,q=o.features?.showToolCalls,j=o.features?.toolCallDisplay,Y=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type,ge=o.features?.history?.enabled===!0,Xe=o.features?.history?.provider,lt=o.getIdentityProof,dt=o.clientToken,Kt=o.contextMentions;o=sC({...o,features:i},r),i=o.features,o=Cg(o),s(),Dd(),Ha(t,o),qa(t,o),za(t,o),Be(),no(),o.colorScheme!==y&&vm();let Bt=xg.getForInstance(o.plugins);l.length=0,l.push(...Bt),vf(),Ce=o.launcher?.enabled??!0,Ze=o.launcher?.autoExpand??!1,po=o.features?.showReasoning??!0,On=o.features?.showToolCalls??!0,uo=o.features?.scrollToBottom??{};let Mt=Tn();Dn=o.features?.scrollBehavior??{},Mt!==Tn()&&(ro(),vn()),Rm(),$g(),Ut();let tn=en;if(en=o.features?.showEventStreamToggle??!1,en&&!tn){if(et||(re(),T.setSSEEventCallback((J,Ve)=>{o.onSSEEvent?.(J,Ve),te(J,Ve)})),!tt&&Me){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:"");tt=k("button",Ve),tt.style.width="28px",tt.style.height="28px",tt.style.color=pn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Ge=Zt(wC,"18px","currentColor",1.5);Ge&&tt.appendChild(Ge);let ot=Ne.clearChatButtonWrapper,bt=Ne.closeButtonWrapper,Jt=ot||bt;Jt&&Jt.parentNode===Me?Me.insertBefore(tt,Jt):Me.appendChild(tt),tt.addEventListener("click",()=>{b?ks():Id()})}}else!en&&tn&&(ks(),tt&&(tt.remove(),tt=null),et?.clear(),Ho?.destroy(),et=null,Ho=null,xn?.reset(),xn=null,Jn=null);if(o.launcher?.enabled===!1&&xt&&(xt.destroy(),xt=null),o.launcher?.enabled===!1&&ln&&(ln.remove(),ln=null),o.launcher?.enabled!==!1&&!xt&&!ln){let{instance:J,element:Ve}=cg({config:o,plugins:l,onToggle:Qf});xt=J,J||(ln=Ve),t.appendChild(Ve)}xt&&xt.update(o),ia(),_r&&o.launcher?.subtitle!==void 0&&(_r.textContent=o.launcher.subtitle);let Je=o.layout?.header;if(Je?.layout!==$e&&Me){let J=Je?td(o,Je,{showClose:Ie(),onClose:()=>ct(!1,"user")}):Cs({config:o,showClose:Ie(),onClose:()=>ct(!1,"user")});An.replaceHeader(J),Me=An.header.element,St=An.header.iconHolder,ar=An.header.headerTitle,_r=An.header.headerSubtitle,qe=An.header.closeButton,$e=Je?.layout,ia()}else if(Je){if(St&&(St.style.display=Je.showIcon===!1?"none":""),ar&&(ar.style.display=Je.showTitle===!1?"none":""),_r&&(_r.style.display=Je.showSubtitle===!1?"none":""),qe){let J=Ie()&&Je.showCloseButton!==!1;qe.style.display=J?"":"none"}if(Ne.clearChatButtonWrapper){let J=Je.showClearChat;if(J!==void 0){Ne.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:Ve}=Ne;Ve&&!Ve.classList.contains("persona-absolute")&&(J?Ve.classList.remove("persona-ml-auto"):Ve.classList.add("persona-ml-auto"))}}}let Xo=o.layout?.showHeader!==!1;Me&&(Me.style.display=Xo?"":"none");let Ao=o.layout?.showFooter!==!1;He&&(He.style.display=Ao?"":"none"),Dr(),Ut(),Ce!==ke?Ce?ct(Ze,"auto"):(be=!0,Vi()):Ze!==U&&ct(Ze,"auto"),U=Ze,ke=Ce,ca(),rh();let _e=JSON.stringify(o.toolCall)!==JSON.stringify(a),De=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!==W,on=(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(Y);(_e||De||fe||pt||$t||on)&&T&&(Qr++,Un(Pe,T.getMessages(),kt));let Et=o.features?.streamAnimation?.type;if(Et!==se&&Et&&Et!=="none"){let J=Fd(Et,o.features?.streamAnimation?.plugins);J&&ba(J,t)}let Ee=o.launcher??{},qt=Ee.headerIconHidden??!1,zt=o.layout?.header?.showIcon,Kn=qt||zt===!1,We=Ee.headerIconName,yt=Ee.headerIconSize??"48px";if(St){let J=Me,Ve=J?.querySelector(".persona-flex-col");if(Kn)St.style.display="none",J&&Ve&&!J.contains(Ve)&&J.insertBefore(Ve,J.firstChild);else{if(St.style.display="",St.style.height=yt,St.style.width=yt,J&&Ve&&(J.contains(St)?St.nextSibling!==Ve&&(St.remove(),J.insertBefore(St,Ve)):J.insertBefore(St,Ve)),We){let ot=parseFloat(yt)||24,bt=he(We,ot*.6,"currentColor",1);bt?St.replaceChildren(bt):St.textContent=Ee.agentIconText??"\u{1F4AC}"}else if(Ee.iconUrl){let ot=St.querySelector("img");if(ot)ot.src=Ee.iconUrl,ot.style.height=yt,ot.style.width=yt;else{let bt=document.createElement("img");bt.src=Ee.iconUrl,bt.alt="",bt.className="persona-rounded-xl persona-object-cover",bt.style.height=yt,bt.style.width=yt,St.replaceChildren(bt)}}else{let ot=St.querySelector("svg"),bt=St.querySelector("img");(ot||bt)&&St.replaceChildren(),St.textContent=Ee.agentIconText??"\u{1F4AC}"}let Ge=St.querySelector("img");Ge&&(Ge.style.height=yt,Ge.style.width=yt)}}let Eo=o.layout?.header?.showTitle,so=o.layout?.header?.showSubtitle;if(ar&&(ar.style.display=Eo===!1?"none":""),_r&&(_r.style.display=so===!1?"none":""),qe){let J=Ie()&&o.layout?.header?.showCloseButton!==!1;if(qe.style.display=J?"":"none",!Re()){let Gt=Ee.closeButtonSize??"";qe.style.height=Gt,qe.style.width=Gt,qe.style.minWidth=Gt,qe.style.minHeight=Gt}let Ve=Ee.closeButtonPlacement??"inline",{closeButtonWrapper:Ge}=Ne,ot=Ve==="top-right",bt=Ge?.classList.contains("persona-absolute");if(Ge&&ot!==bt)if(Ge.remove(),ot){Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Gt=Ji??ue;Gt.style.position="relative",Gt.appendChild(Ge)}else{let Gt=Ee.clearChat?.placement??"inline",Qt=Ee.clearChat?.enabled??!0;Ge.className=Qt&&Gt==="inline"?"":"persona-ml-auto",Me&&Me.appendChild(Ge)}if(qe.style.color=Ee.closeButtonColor||pn.actionIconColor,Ee.closeButtonBackgroundColor?(qe.style.backgroundColor=Ee.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),Ee.closeButtonBorderWidth||Ee.closeButtonBorderColor){let Gt=Ee.closeButtonBorderWidth||"0px",Qt=Ee.closeButtonBorderColor||"transparent";qe.style.border=`${Gt} solid ${Qt}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");Ee.closeButtonBorderRadius?(qe.style.borderRadius=Ee.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),Ee.closeButtonPaddingX?(qe.style.paddingLeft=Ee.closeButtonPaddingX,qe.style.paddingRight=Ee.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),Ee.closeButtonPaddingY?(qe.style.paddingTop=Ee.closeButtonPaddingY,qe.style.paddingBottom=Ee.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom=""),ed(qe,Ee.closeButtonIconName??"x",{iconSize:Re()?sg:void 0,iconText:Ee.closeButtonIconText??"\xD7"});let Jt=Ee.closeButtonTooltipText??"Close chat",io=Ee.closeButtonShowTooltip??!0;qe.setAttribute("aria-label",Jt),Ge&&Xt({anchor:qe,trigger:Ge,text:()=>qe?.getAttribute("aria-label")??Jt,enabled:io})}let{clearChatButton:Oe,clearChatButtonWrapper:ve}=Ne;if(Oe){let J=Ee.clearChat??{},Ve=J.enabled??!0,Ge=o.layout?.header?.showClearChat,ot=Ge!==void 0?Ge:Ve,bt=J.placement??"inline";if(ve){ve.style.display=ot?"":"none";let{closeButtonWrapper:Jt}=Ne;!Re()&&Jt&&!Jt.classList.contains("persona-absolute")&&(ot?Jt.classList.remove("persona-ml-auto"):Jt.classList.add("persona-ml-auto"));let io=bt==="top-right",Gt=ve.classList.contains("persona-absolute");if(!Re()&&io!==Gt&&ot){if(ve.remove(),io){ve.className="persona-absolute persona-top-4 persona-z-50",ve.style.right="48px";let To=Ji??ue;To.style.position="relative",To.appendChild(ve)}else{ve.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ve.style.right="";let To=Ne.closeButtonWrapper;Me&&To&&To.parentElement===Me?Me.insertBefore(ve,To):Me&&Me.appendChild(ve)}let Qt=Ne.closeButtonWrapper;Qt&&!Qt.classList.contains("persona-absolute")&&(io?Qt.classList.add("persona-ml-auto"):Qt.classList.remove("persona-ml-auto"))}}if(ot){if(!Re()){let Qt=J.size??"";Oe.style.height=Qt,Oe.style.width=Qt,Oe.style.minWidth=Qt,Oe.style.minHeight=Qt}let Jt=J.iconColor??"";if(Oe.style.color=Jt||pn.actionIconColor,ed(Oe,J.iconName??"refresh-cw",{iconSize:Re()?ig:void 0}),J.backgroundColor?(Oe.style.backgroundColor=J.backgroundColor,Oe.classList.remove("hover:persona-bg-gray-100")):(Oe.style.backgroundColor="",Oe.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let Qt=J.borderWidth||"0px",To=J.borderColor||"transparent";Oe.style.border=`${Qt} solid ${To}`,Oe.classList.remove("persona-border-none")}else Oe.style.border="",Oe.classList.add("persona-border-none");J.borderRadius?(Oe.style.borderRadius=J.borderRadius,Oe.classList.remove("persona-rounded-full")):(Oe.style.borderRadius="",Oe.classList.add("persona-rounded-full")),J.paddingX?(Oe.style.paddingLeft=J.paddingX,Oe.style.paddingRight=J.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),J.paddingY?(Oe.style.paddingTop=J.paddingY,Oe.style.paddingBottom=J.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let io=J.tooltipText??"Clear chat",Gt=J.showTooltip??!0;Oe.setAttribute("aria-label",io),ve&&Xt({anchor:Oe,trigger:ve,text:()=>Oe?.getAttribute("aria-label")??io,enabled:Gt})}}let Fe=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Mg],ut=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ja.message,ja.messageAndClick];Le=Eg({parsers:Fe,handlers:ut,getSessionMetadata:ce,updateSessionMetadata:ie,emit:w.emit,documentRef:typeof document<"u"?document:null}),kt=MC(o,Le,xs),Fw(),T.updateConfig(o),(o.features?.history?.enabled===!0!==ge||o.features?.history?.provider!==Xe||o.getIdentityProof!==lt||o.clientToken!==dt)&&(wn({restoreFocus:!1}),pf()),wr(),Ul(),Un(Pe,T.getMessages(),kt),Rs(),Ml(),Dw(),Ki(T.isStreaming()),Kt!==o.contextMentions&&ch();let Ar=o.voiceRecognition?.enabled===!0,jt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Rn=o.voiceRecognition?.provider?.type==="runtype";if(Ar&&(jt||Rn))if(!oe||!En){let J=gi(o);if(J){oe=J.button,En=J.wrapper;let Ve=mo&&mo.parentElement===Ga?mo:null;Ga?Ga.insertBefore(En,Ve):Zn?.appendChild(En),nt&&(nt.micButton=oe),nt?.addListener(oe,"click",Qp),oe.disabled=T.isStreaming()}}else{let J=o.voiceRecognition??{},Ve=o.sendButton??{},Ge=J.iconName??"mic",ot=J.iconSize,bt=parseFloat(ot??"")||cn;oe.classList.add(Bn),oe.classList.toggle(ao,!ot),oe.style.width=ot??"",oe.style.height=ot??"",oe.style.minWidth=ot??"",oe.style.minHeight=ot??"";let Jt=J.iconColor??Ve.textColor;oe.innerHTML="";let io=he(Ge,bt,Jt||"currentColor",1.5);io?oe.appendChild(io):oe.textContent="\u{1F3A4}";let Gt=J.backgroundColor??Ve.backgroundColor;Gt?oe.style.backgroundColor=Gt:oe.style.backgroundColor="",Jt?oe.style.color=Jt:oe.style.color="var(--persona-text, #111827)",J.borderWidth?(oe.style.borderWidth=J.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),J.borderColor?oe.style.borderColor=J.borderColor:oe.style.borderColor="",J.paddingX?(oe.style.paddingLeft=J.paddingX,oe.style.paddingRight=J.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),J.paddingY?(oe.style.paddingTop=J.paddingY,oe.style.paddingBottom=J.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let Qt=J.tooltipText??"Start voice recognition",To=J.showTooltip??!1;oe.setAttribute("aria-label",Qt),En&&Xt({anchor:oe,trigger:En,text:()=>oe?.getAttribute("aria-label")??Qt,enabled:To}),En.style.display="",oe.disabled=T.isStreaming()}else oe&&En&&(En.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?T.isVoiceActive()&&T.toggleVoice():xo&&Sr());if(o.attachments?.enabled===!0){if(!hn||!vt){let J=o.attachments??{};yn||(yn=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),yn.style.display="none",(pe.parentElement??Zn).insertBefore(yn,pe)),gt||(gt=document.createElement("input"),gt.type="file",gt.accept=(J.allowedTypes??Zo).join(","),gt.multiple=(J.maxFiles??4)>1,gt.style.display="none",gt.setAttribute("aria-label","Attach files"),(pe.parentElement??Zn).insertBefore(gt,pe)),hn=k("div","persona-send-button-wrapper"),vt=k("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Bn} ${ao}`),vt.type="button",vt.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let Ve=J.buttonIconName??"paperclip";vt.style.fontSize="18px",vt.style.lineHeight="1";let Ge=he(Ve,cn,"currentColor",1.5);Ge?vt.appendChild(Ge):vt.textContent="\u{1F4CE}",vt.addEventListener("click",bt=>{bt.preventDefault(),gt?.click()}),hn.appendChild(vt);let ot=J.buttonTooltipText??"Attach file";Xt({anchor:vt,trigger:hn,text:()=>vt?.getAttribute("aria-label")??ot}),wd?wd.append(hn):Zn.appendChild(hn),nt&&(nt.attachmentButton=vt,nt.attachmentInput=gt??void 0,nt.attachmentPreviews=yn??void 0),!Ye&&gt&&yn&&(Ye=Ta.fromConfig(J,qg),Ye.setPreviewsContainer(yn),nt?.addListener(gt,"change",async()=>{Ye&&gt?.files&&(await Ye.handleFileSelect(gt.files),gt.value="")}))}else{hn.style.display="";let J=o.attachments??{};gt&&(gt.accept=(J.allowedTypes??Zo).join(","),gt.multiple=(J.maxFiles??4)>1),Ye&&Ye.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(EC(o.attachments?.dropOverlay)),vt){let J=o.attachments??{},Ve=J.buttonTooltipText??"Attach file";vt.setAttribute("aria-label",Ve),vt.textContent="";let Ge=he(J.buttonIconName??"paperclip",cn,"currentColor",1.5);Ge?vt.appendChild(Ge):vt.textContent="\u{1F4CE}",hn&&Xt({anchor:vt,trigger:hn,text:()=>vt?.getAttribute("aria-label")??Ve})}}else hn&&(hn.style.display="none"),Ye&&Ye.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Ct=o.sendButton??{},Jp=Ct.useIcon??!1,ms=Ct.iconText??"\u2191",rc=Ct.iconName,Ch=Ct.tooltipText??"Send message",tx=Ct.showTooltip??!1,ua=Ct.size,nx=parseFloat(ua??"")||Lu,sc=Ct.backgroundColor,ga=Ct.textColor;if(Jp){if(Ae.style.width=ua??"",Ae.style.height=ua??"",Ae.style.minWidth=ua??"",Ae.style.minHeight=ua??"",Ae.style.fontSize="18px",Ae.style.lineHeight="1",ga?Ae.style.color=ga:Ae.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!T.isStreaming())if(Ae.innerHTML="",rc){let J=parseFloat(Ct.iconSize??"")||Math.round(nx*.5),Ve=ga?.trim()||"currentColor",Ge=Ct.iconStrokeWidth??2,ot=he(rc,J,Ve,Ge),bt=he(Ct.stopIconName??"square",J,Ve,Ge);ot&&bt?Ae.appendChild(Hu(ot,bt)):ot?Ae.appendChild(ot):Ae.textContent=ms}else Ae.textContent=ms;Ae.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Bn}`,sc?(Ae.style.backgroundColor=sc,Ae.classList.remove("persona-bg-persona-primary")):(Ae.style.backgroundColor="",Ae.classList.add("persona-bg-persona-primary"))}else Ae.textContent=o.copy?.sendButtonLabel??"Send",Ae.style.width="",Ae.style.height="",Ae.style.minWidth="",Ae.style.minHeight="",Ae.style.fontSize="",Ae.style.lineHeight="",Ae.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",sc?(Ae.style.backgroundColor=sc,Ae.classList.remove("persona-bg-persona-accent")):Ae.classList.add("persona-bg-persona-accent"),ga?Ae.style.color=ga:Ae.classList.add("persona-text-white");Ct.borderWidth?(Ae.style.borderWidth=Ct.borderWidth,Ae.style.borderStyle="solid"):(Ae.style.borderWidth="",Ae.style.borderStyle=""),Ct.borderColor?Ae.style.borderColor=Ct.borderColor:Ae.style.borderColor="",Ct.paddingX?(Ae.style.paddingLeft=Ct.paddingX,Ae.style.paddingRight=Ct.paddingX):(Ae.style.paddingLeft="",Ae.style.paddingRight=""),Ct.paddingY?(Ae.style.paddingTop=Ct.paddingY,Ae.style.paddingBottom=Ct.paddingY):(Ae.style.paddingTop="",Ae.style.paddingBottom=""),T.isStreaming()||Ae.setAttribute("aria-label",Ch),xl(),mo&&Xt({anchor:Ae,trigger:mo,text:()=>Ae.getAttribute("aria-label")??Ch,enabled:tx}),rm();let wh=jc(Se.getState().activeModeIds,o.composer?.modes);Se.setActiveModeIds(wh),Ms().length>0!==!!Bo&&Hd(),Bo?.render(wh,Ms());for(let J of[...Es.keys()])zc(J,o.composer?.modeGroups)||Es.delete(J);Es.forEach(J=>J.repaint()),cr?.repaint(),yo?.resolve();let ic=Rr(o,Re());if(Nd(),ic){Pe.style.maxWidth=ic,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",Mn.style.maxWidth=ic,Mn.style.marginLeft="auto",Mn.style.marginRight="auto",Mn.style.width="100%";for(let J of[Zn,ir,yn,st])J&&(J.style.maxWidth=ic,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{Pe.style.maxWidth="",Pe.style.marginLeft="",Pe.style.marginRight="",Pe.style.width="",Mn.style.maxWidth="",Mn.style.marginLeft="",Mn.style.marginRight="",Mn.style.width="";for(let J of[Zn,ir,yn,st])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let Mr=o.statusIndicator??{},ox=Mr.visible??!0;if(st.style.display=ox?"":"none",T){let J=T.getStatus();Ka(st,(Ge=>Ge==="idle"?Mr.idleText??_t.idle:Ge==="connecting"?Mr.connectingText??_t.connecting:Ge==="connected"?Mr.connectedText??_t.connected:Ge==="error"?Mr.errorText??_t.error:_t[Ge])(J),Mr,J)}st.classList.remove("persona-text-left","persona-text-center","persona-text-right");let rx=Mr.align==="left"?"persona-text-left":Mr.align==="center"?"persona-text-center":"persona-text-right";st.classList.add(rx),Ld(),Jd(),eo(),Ot()},open(){Ie()&&ct(!0,"api")},close(){Ie()&&ct(!1,"api")},toggle(){Ie()&&ct(!be,"api")},reconnect(){T.reconnectNow()},clearChat(){_o=!1,T.clearMessages(),Rt.clear(),vn();try{localStorage.removeItem(Mi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mi}`)}catch(a){console.error("[AgentWidget] Failed to clear default localStorage:",a)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Mi)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&&fl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ee={},Le.syncFromMetadata(),Ye?.clearAttachments(),yl(),Ts(void 0),ho(void 0),Gr(),et?.clear(),xn?.reset(),Q?.update()},setMessage(r){return!pe||T.isStreaming()||br()?!1:(!be&&Ie()&&ct(!0,"system"),pe.value=r,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(r){if(T.isStreaming()||ts())return!1;let a=r?.trim()||pe.value.trim();return a?(!be&&Ie()&&ct(!0,"system"),pe.value="",pe.style.height="auto",fo(),Jl(a,{consumeDraft:!1}),!0):!1},getComposerState(){return Se.getState()},setQuote(r){let a=r?.text?.trim();a&&ho({...r,text:a})},clearQuote(){ho(void 0)},startVoiceRecognition(){return T.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(T.isVoiceActive()||(!be&&Ie()&&ct(!0,"system"),je.manuallyDeactivated=!1,oo(),T.toggleVoice().then(()=>{je.active=T.isVoiceActive(),Fo("user"),T.isVoiceActive()&&ei()})),!0):xo?!0:Gf()?(!be&&Ie()&&ct(!0,"system"),je.manuallyDeactivated=!1,oo(),ec("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,oo(),Fo("user"),Qo()}),!0):!1:xo?(je.manuallyDeactivated=!0,oo(),Sr("user"),!0):!1},injectMessage(r){return!be&&Ie()&&ct(!0,"system"),T.injectMessage(r)},injectAssistantMessage(r){!be&&Ie()&&ct(!0,"system");let a=T.injectAssistantMessage(r);return lo&&(lo=!1,co&&(clearTimeout(co),co=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),a},injectUserMessage(r){return!be&&Ie()&&ct(!0,"system"),T.injectUserMessage(r)},injectSystemMessage(r){return!be&&Ie()&&ct(!0,"system"),T.injectSystemMessage(r)},injectMessageBatch(r){return!be&&Ie()&&ct(!0,"system"),T.injectMessageBatch(r)},injectComponentDirective(r){return!be&&Ie()&&ct(!0,"system"),T.injectComponentDirective(r)},injectTestMessage(r){!be&&Ie()&&ct(!0,"system"),T.injectTestEvent(r)},async connectStream(r,a){return T.connectStream(r,a)},__pushEventStreamEvent(r){en&&(re(),te(r.type,r.payload))},showEventStream(){en&&Id()},hideEventStream(){b&&ks()},isEventStreamVisible(){return b},listConversations(r){return T.listConversations(r)},getActiveConversationId(){return T.getActiveConversationId()},openConversation(r,a){return Wp(r,{focusComposer:a?.focus===!0})},startNewConversation(r){return Bp({focusComposer:r?.focus===!0})},deleteConversation(r){return Of(r)},renameConversation(r,a){return _p(r,{title:a})},setConversationStarred(r,a){return _p(r,{starred:a})},clearConversationHistory(r){return Df(r)},resetHistoryIdentity(){return Nf()},getHistoryIdentityStatus(){return Ln?Ln.getIdentityStatus():yp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(r){return sa({...r?.returnSurface?{returnSurface:r.returnSurface}:{},...r?.focus!==void 0?{focus:r.focus}:{}})},hideHistory(r){wn(r?.restoreFocus!==void 0?{restoreFocus:r.restoreFocus}:void 0)},isHistoryVisible(){return ae},showArtifacts(){gn(o)&&(_o=!1,Is=!0,no(),ze?.setMobileOpen(!0))},hideArtifacts(){gn(o)&&(_o=!0,no())},upsertArtifact(r){return gn(o)?(Er(o.features?.artifacts,{artifactType:r.artifactType,...r.artifactType==="markdown"&&r.file?{file:r.file}:{},...r.presentation?{presentation:r.presentation}:{}})==="panel"&&(_o=!1,Is=!0),T.upsertArtifact(r)):null},selectArtifact(r){gn(o)&&T.selectArtifact(r)},clearArtifacts(){gn(o)&&T.clearArtifacts()},getArtifacts(){return T?.getArtifacts()??[]},getSelectedArtifactId(){return T?.getSelectedArtifactId()??null},focusInput(){return Ce&&!be&&!Re()||!pe?!1:(pe.focus(),!0)},async resolveApproval(r,a,d){let y=T.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"){T.resolveWebMcpApproval(y.id,a);return}return T.resolveApproval(y.approval,a,d)},setFollowUpSuggestions(r){cw(r)},clearFollowUpSuggestions(){Hm()},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...ee}},updatePersistentMetadata(r){ie(r)},on(r,a){return w.on(r,a)},off(r,a){w.off(r,a)},isOpen(){return Ie()&&be},isVoiceActive(){return je.active},toggleReadAloud(r){T.toggleReadAloud(r)},stopReadAloud(){T.stopSpeaking()},getReadAloudState(r){return T.getReadAloudState(r)},onReadAloudChange(r){return T.onReadAloudChange(r)},getState(){return{open:Ie()&&be,launcherEnabled:Ce,voiceActive:je.active,streaming:T.isStreaming()}},showCSATFeedback(r){!be&&Ie()&&ct(!0,"system");let a=Pe.querySelector(".persona-feedback-container");a&&a.remove();let d=vC({onSubmit:async(m,y)=>{T.isClientTokenMode()&&await T.submitCSATFeedback(m,y),r?.onSubmit?.(m,y)},onDismiss:r?.onDismiss,...r});Pe.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(r){!be&&Ie()&&ct(!0,"system");let a=Pe.querySelector(".persona-feedback-container");a&&a.remove();let d=CC({onSubmit:async(m,y)=>{T.isClientTokenMode()&&await T.submitNPSFeedback(m,y),r?.onSubmit?.(m,y)},onDismiss:r?.onDismiss,...r});Pe.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(r,a){return T.submitCSATFeedback(r,a)},async submitNPSFeedback(r,a){return T.submitNPSFeedback(r,a)},destroy(){dp(),rs!=null&&(clearInterval(rs),rs=null),ye.forEach(r=>r()),Ke.remove(),Vt?.remove(),xt?.destroy(),ln?.remove(),zr&&qe.removeEventListener("click",zr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let r=window.AgentWidgetBrowser,a={controller:At,getMessages:At.getMessages,getStatus:At.getStatus,getMetadata:At.getPersistentMetadata,updateMetadata:At.updatePersistentMetadata,clearHistory:()=>At.clearChat(),setVoiceActive:d=>d?At.startVoiceRecognition():At.stopVoiceRecognition()};window.AgentWidgetBrowser=a,ye.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 Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&At.focusInput()};if(window.addEventListener("persona:focusInput",a),ye.push(()=>{window.removeEventListener("persona:focusInput",a)}),en){let j=se=>{let ge=se.detail;(!ge?.instanceId||ge.instanceId===r)&&At.showEventStream()},Y=se=>{let ge=se.detail;(!ge?.instanceId||ge.instanceId===r)&&At.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",Y),ye.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",Y)})}let d=j=>{let Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&At.showHistory()},m=j=>{let Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&At.hideHistory()};window.addEventListener("persona:showHistory",d),window.addEventListener("persona:hideHistory",m),ye.push(()=>{window.removeEventListener("persona:showHistory",d),window.removeEventListener("persona:hideHistory",m)});let y=j=>{let Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&At.showArtifacts()},C=j=>{let Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&At.hideArtifacts()},W=j=>{let Y=j.detail;Y?.instanceId&&Y.instanceId!==r||Y?.artifact&&At.upsertArtifact(Y.artifact)},z=j=>{let Y=j.detail;Y?.instanceId&&Y.instanceId!==r||typeof Y?.id=="string"&&At.selectArtifact(Y.id)},q=j=>{let Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&At.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",q),ye.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",q)})}let Vn=vT(o.persistState);if(Vn&&Ie()){let r=CT(Vn.storage),a=`${Vn.keyPrefix}widget-open`,d=`${Vn.keyPrefix}widget-voice`,m=`${Vn.keyPrefix}widget-voice-mode`;if(r){let y=Vn.persist?.openState&&r.getItem(a)==="true",C=Vn.persist?.voiceState&&r.getItem(d)==="true",W=Vn.persist?.voiceState&&r.getItem(m)==="true";if(y&&(xt?.setPanelOpen(!0,"auto"),setTimeout(()=>{At.open(),setTimeout(()=>{if(C||W)At.startVoiceRecognition();else if(Vn.persist?.focusInput){let z=t.querySelector("textarea");z&&z.focus()}},100)},0)),Vn.persist?.openState&&(w.on("widget:opened",()=>{r.setItem(a,"true")}),w.on("widget:closed",()=>{r.setItem(a,"false")})),Vn.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")})),Vn.clearOnChatClear){let z=()=>{r.removeItem(a),r.removeItem(d),r.removeItem(m)},q=()=>z();window.addEventListener("persona:clear-chat",q),ye.push(()=>{window.removeEventListener("persona:clear-chat",q)})}}}if(Z&&Ie()&&(xt?.setPanelOpen(!0,"auto"),setTimeout(()=>{At.open()},0)),Fs(),!dw){let r=ac(()=>{T&&(Qr++,Rt.clear(),Un(Pe,T.getMessages(),kt))});ye.push(r)}E=()=>{T&&(Qr++,Rt.clear(),Un(Pe,T.getMessages(),kt))},T.getMessages().length>0&&Sl(),A=()=>{T&&(Qr++,Rt.clear(),Un(Pe,T.getMessages(),kt))};let ZS=Oh(()=>{T&&(Qr++,Rt.clear(),Un(Pe,T.getMessages(),kt))});ye.push(ZS);let ex=hg(()=>{T&&(Qr++,Rt.clear(),Un(Pe,T.getMessages(),kt),nr()?.updateInlineArtifactBlocks(Pe,Fn.artifacts,{suppressTransition:!0}),no())});return ye.push(ex),At};var kC=(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},xT=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},AT=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},MT=(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.")},PC=(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"},Bg=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=""},IC=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Bg(t)},Hg=t=>{t.style.transition=""},Rg=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=""},Wg=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},vd=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},ET=(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))},TT=(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)},kT=t=>{let e=fi(t),n=e.components?.panel,o=(s,i)=>s==null||s===""?i:dn(e,s)??s;return{inset:o(n?.inset,Vc),canvasBackground:o(n?.canvasBackground,Kc)}},LC=(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},PT=(t,e,n,o,s,i,l,c)=>{let p=Xn(i),g=p.reveal==="push",u=c!=null,f=c?.inset??"",v=c?.canvasBackground??"";ET(t,e,n,o,g),TT(t,e,n,o,p.side,g),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,x=i?.launcher?.mobileFullscreen??!0,E=i?.launcher?.mobileBreakpoint??640,M=h!=null?h.innerWidth<=E:!1;if(x&&M&&l){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Rg(e),Hg(o),IC(o),Wg(n),vd(s,o),LC(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??sn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",g&&(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"),IC(o),xT(o,p.maxHeight),LC(o,u&&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",Rg(e),Hg(o),Wg(n),vd(s,o);let P=p.animate?"transform 180ms ease":"none",K=p.side==="right"?"translateX(100%)":"translateX(-100%)",A=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=A,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",Hg(o),Bg(o),vd(s,o);let P=kC(p.width,t.clientWidth),K=Math.max(0,t.clientWidth),A=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=A,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="",Rg(e),Bg(o),Wg(n),vd(s,o);let P=p.reveal==="emerge";P?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let K=l?p.width:"0px",A=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", 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",AT(o,p.maxHeight),o.style.overflow=P||L?"hidden":"visible",o.style.transition=A,P){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let w=u?`calc(${kC(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"}}},IT=(t,e)=>{let n=t.ownerDocument.createElement("div");return PC(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){PC(n,o)},destroy(){n.remove()}}},LT=(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"),g=n.createElement("aside"),u=n.createElement("div"),f=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;c.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",g.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",g.appendChild(u),o.insertBefore(l,t),p.appendChild(t);let v=null,h=()=>{v?.disconnect(),v=null},x=null,E=()=>{x=e?.launcher?.detachedPanel===!0?kT(e):null};E();let M=()=>{PT(l,c,p,g,u,e,f,x)},F=null,P=()=>{F?.(),F=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(F=Gc(()=>{E(),M()}))},K=()=>{h(),Xn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(v=new ResizeObserver(()=>{M()}),v.observe(l)))},A=!1,L=()=>{M(),K(),f&&!A&&l.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,MT(l,Xn(e)))},w=l.ownerDocument.defaultView,_=()=>{L()};return w?.addEventListener("resize",_),Xn(e).reveal==="push"?(c.appendChild(p),c.appendChild(g),l.appendChild(c)):(l.appendChild(p),l.appendChild(g)),L(),P(),{mode:"docked",host:u,shell:l,syncWidgetState(G){let le=G.launcherEnabled?G.open:!0;f!==le&&(f=le,L())},updateConfig(G){e=G,(e?.launcher?.enabled??!0)===!1&&(f=!0),E(),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()}}},HC=(t,e)=>Lt(e)?LT(t,e):IT(t,e);var Va={desktop:{w:1280,h:800},mobile:{w:390,h:844}},RC=.15,WC=1.5,_g="persona-preview-shell-theme",HT={load:()=>null,save:()=>{},clear:()=>{}},RT=["How do I get started?","Pricing & plans","Talk to support"];function Og(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function WT(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 BC(t){let e=WT(t);return`* { box-sizing: border-box; }
127
+ ${at?"background: transparent !important;":""}
128
+ `)}if(!f&&!r){let De="max-height: -moz-available !important; max-height: stretch !important;",gt=a?"":"padding-top: 1.25em !important;",nt=a?"":`z-index: ${o.launcher?.zIndex??an} !important;`;Ve.style.cssText+=De+gt+nt}Ed(),_e()},Fd=()=>{t.style.setProperty("--persona-content-max-width",Rr(o,Re()))},bf=!1,vf=()=>{let r=qu(o,Re());Re()&&o.composer?.placement&&o.debug===!0&&!bf&&(bf=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let a=nr(o);t.setAttribute("data-persona-composer-placement",r),t.setAttribute("data-persona-conversation-state",Ja),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",a.composerGap??Xc),el()},Cf=()=>{if(Re())return;let r=Rt(o),a=o.launcher?.sidebarMode??!1;if(r||a||(o.launcher?.fullHeight??!1)||!be)return;let f=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,C=o.launcher?.mobileBreakpoint??640;if(y&&f.innerWidth<=C)return;let W=f.innerHeight,z=64,q=o.launcher?.heightOffset??0,j=Math.max(200,W-z),Y=Math.min(640,j);Se.style.height=`${Math.max(200,Y-q)}px`};Nd(),Ra(t,o),za(t,o),ja(t,o),Fd(),vf(),Fr=()=>{Nd(),Cf(),Ra(t,o),za(t,o),ja(t,o),Fd(),vf(),ol?t.style.setProperty("--persona-artifact-welded-outer-radius",ol):t.style.removeProperty("--persona-artifact-welded-outer-radius"),Be(),Nt()};let he=[];he.push(()=>{uf=!0}),he.push(()=>{p.forEach(r=>r()),c.destroy()}),he.push(()=>{document.removeEventListener("keydown",mf)}),he.push(()=>{Ri!==null&&clearTimeout(Ri)});let Co=null,wo=null;he.push(()=>{Co?.(),Co=null,wo?.(),wo=null}),_i&&he.push(()=>{_i?.disconnect(),_i=null}),he.push(()=>{Ni?.(),Ni=null,Dd(),bt&&(bt.remove(),bt=null),qe?.element.style.removeProperty("width"),qe?.element.style.removeProperty("maxWidth"),qe?.destroy()}),nn&&he.push(()=>{D=!0,Zn=null,O!==null&&(cancelAnimationFrame(O),O=null),Q?.destroy(),Q=null,Ze?.destroy(),Ze=null,Ho=null});let $r=null,wf=()=>{$r&&($r(),$r=null),o.colorScheme==="auto"&&($r=Qc(()=>{Ra(t,o)}))};wf(),he.push(()=>{$r&&($r(),$r=null)}),he.push(()=>{x=!0,h?.()}),he.push(()=>{P=!0});let Sf=!1;he.push(()=>{Sf=!0});let Ud=(r,a)=>{let d=ha(r,a);return d||!Xh.includes(r)?d:(gv().then(f=>{if(Sf)return;ou(f.wipe),ou(f.glyphCycle);let y=ha(r,a);y&&va(y,t)}).catch(()=>{}),null)},pl=o.features?.streamAnimation;if(pl?.type&&pl.type!=="none"){let r=Ud(pl.type,pl.plugins);r&&va(r,t),he.push(()=>Yh(t))}let Oo=Na(ar),xf=Na(wd),Af=Na(Pi),qr=[Oo,xf,Af];he.push(()=>{qr.forEach(r=>r.destroy())});let zr=null,T,jr=null,Mf=!1,Ef=0,Tf=null,kf=r=>r.reduce((a,d)=>d.role==="user"?a+1:a,0),Pf=r=>{for(let a=r.length-1;a>=0;a--)if(xa(r[a]))return r[a].id??null;return null},If=!1,cw=()=>{If||o.debug!==!0||(If=!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".'))},Lf=!1,Hf=!1,Rf=(r,a)=>{Lf||o.debug!==!0||!a.enabled||a.expose||Mf||Hf&&(T.isStreaming()||r.some(xa)||(Lf=!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.")))},Rs=r=>{if(!T)return;let a=r??T.getMessages(),d=j=>{j.render([],T,pe,a)},f=j=>{qr.forEach(Y=>{Y!==j&&d(Y)})};jr&&(kf(a)>Ef||Pf(a)!==Tf)&&(jr=null);let y=Ir(o);Rf(a,y);let C=y.enabled?Ty(a):null,W=jr??C,z=jr?"host":"agent";if(W){let j=o.suggestions?.followUps,Y=j?.placement??(j?"auto":"composer"),ge=(Y==="auto"?Re()?"composer":"after-message":Y)==="after-message"?Af:Oo;f(ge),ge.render(W,T,pe,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:Jl});return}if(a.some(j=>j.role==="user")){qr.forEach(d);return}let q=o.suggestions?.starters;if(q){let j=Ci(nr(o),a),Y=q.placement??"auto",se=Y==="auto"?j?"welcome":"composer":Y;if(se==="welcome"&&!j){cw(),qr.forEach(d);return}let ge=se==="welcome"?xf:Oo;f(ge),ge.render(q.items??o.suggestionChips,T,pe,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:Jl});return}f(Oo),Oo.render(o.suggestionChips,T,pe,a,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:l,submitPrompt:Jl})},Wf=()=>{jr&&(jr=null,Rs())},dw=r=>{let a=Array.isArray(r)?[...r]:[];if(!a.length){Wf();return}let d=T?T.getMessages():[];jr=a,Mf=!0,Ef=kf(d),Tf=Pf(d),Rs(d)},Pn=!1,Bt=cv(),Ws=new Map,Vr=new Map,gr=new Map,Kr=null,fr=null;function Gr(){if(!Kr)return;let r=Kr;Kr=null,fr?.destroy(),fr=null,Bt.delete(r),ue.querySelector(`#wrapper-${r}`)?.removeAttribute("data-preserve-runtime"),T&&$n(Te,T.getMessages(),It)}let Qr=0,pw=oi()!==null,In=jh(),Ln=0,mr=null,vn=!1,ul=!1,hr=0,$t=null,Xr=null,$d=!1,Bs=!1,Yr=null,Fi=!0,gl=!1,_s=null,fl=!1,Jr=()=>{fl=!0,mw()},qd=null,uw=4,Do=24,gw=80,fw=1e3,No=null,Bf=()=>{t.setAttribute("data-persona-scrollbar",xd()),xd()!=="on-scroll"&&(No!==null&&clearTimeout(No),No=null,ne.removeAttribute("data-persona-scrollbar-visible"))},mw=()=>{xd()==="on-scroll"&&(ne.setAttribute("data-persona-scrollbar-visible",""),No!==null&&clearTimeout(No),No=setTimeout(()=>{No=null,hs(ne,Do)&&ne.removeAttribute("data-persona-scrollbar-visible")},fw))};Bf(),he.push(()=>{No!==null&&clearTimeout(No)});let zd=new Map,ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};rf=()=>ze.active,to();let _f=o.voiceRecognition?.autoResume??!1,Fo=r=>{w.emit("voice:state",{active:ze.active,source:r,timestamp:Date.now()})},ro=()=>{ie(r=>({...r,voiceState:{active:ze.active,timestamp:Date.now(),manuallyDeactivated:ze.manuallyDeactivated}}))},hw=()=>{if(o.voiceRecognition?.enabled===!1)return;let r=Hg(ee.voiceState),a=!!r.active,d=Number(r.timestamp??0);ze.manuallyDeactivated=!!r.manuallyDeactivated,a&&Date.now()-d<hT&&setTimeout(()=>{ze.active||(ze.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?T.toggleVoice().then(()=>{ze.active=T.isVoiceActive(),Fo("restore"),T.isVoiceActive()&&ei()}):tc("restore"))},1e3)},yw=()=>T?MC(T.getMessages()).filter(r=>!r.__skipPersist):[],ml=null,Of=(r,a)=>{typeof console<"u"&&console.error(r,a)},hl=(r,a)=>{let d=()=>{try{let W=r();return!W||typeof W.then!="function"?null:Promise.resolve(W).catch(z=>{Of(a,z)})}catch(W){return Of(a,W),null}},f=ml,y=f?f.then(()=>d()??void 0):d();if(!y)return;let C=y.finally(()=>{ml===C&&(ml=null)});ml=C};function Os(r){if(!G?.save)return;let a=r?MC(r):T?yw():[],d=le&&T?.getResumableHandle();d&&(ee={...ee,durableResume:{executionId:d.executionId,after:d.lastEventId}});let f={messages:a,metadata:ee,artifacts:Un.artifacts,selectedArtifactId:Un.selectedId,...Zr?{draft:Zr}:{}};hl(()=>G.save(f),"[AgentWidget] Failed to persist state:")}let Zr,yl=()=>!G?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Ui=Fb({write:()=>{if(!yl())return;let r=Ce.getState(),a=Db({text:r.text,mentionRefs:r.mentionRefs,contentSegments:Np(),selectedModelId:r.selectedModelId,activeModeIds:r.activeModeIds,quote:r.quote});JSON.stringify(a)!==JSON.stringify(Zr)&&(Zr=a,Os())}});function Df(){yl()&&Ui.schedule()}function jd(){Ui.flush()}function Nf(r){if(!yl())return;let a=Nb(r,{mentionSourceIds:(o.contextMentions?.sources??[]).map(d=>d.id),modelIds:(o.composer?.models??[]).map(d=>d.id),modes:o.composer?.modes??[]});a&&(Zr=r,pe&&!pe.value&&(pe.value=a.text,pe.dispatchEvent(new Event("input",{bubbles:!0})),ho()),a.selectedModelId&&(Ce.setSelectedModelId(a.selectedModelId),dr?.repaint()),tl(a.activeModeIds??[]),a.quote&&yo(a.quote),Ui.cancel())}function bl(){Ui.cancel(),Zr&&(Zr=void 0,yl()&&Os())}let Ds=null,Ff=()=>Ve.querySelector("#persona-scroll-container")||ne,Ns=()=>{Ds!==null&&(cancelAnimationFrame(Ds),Ds=null),vn=!1},Uf=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),ul=!1,Ns()},bw=()=>Pn&&Kd()&&(kn()!=="anchor-top"||Ug()),Vd=()=>{let r=Ii()||"Jump to latest",a=bw();Wt.toggleAttribute("data-persona-scroll-to-bottom-streaming",a),hr>0?(Or.textContent=String(hr),Or.style.display="",Wt.setAttribute("aria-label",`${r} (${hr} new)`)):(Or.textContent="",Or.style.display="none",Wt.setAttribute("aria-label",a?`${r} (response streaming below)`:r))},$f=()=>{hr!==0&&(hr=0,Vd())},vw=()=>{let r=$t?.spacerHeight??0;return r<=0?hs(ne,Do):Sl(r)-ne.scrollTop-ne.clientHeight<=Do},Kd=()=>cr()?!In.isFollowing():!vw(),Gd=()=>!!T&&T.getMessages().length>0,qt=()=>{if(!KC()||ir()){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==ue&&ue.appendChild(Wt),Dr();let a=Jo(ne)>0&&Kd()&&Gd();a?Vd():$f(),Wt.style.display=a?"":"none"},$i=()=>{In.pause()&&(Uf(),qt())},Cn=()=>{In.resume(),$f(),qt()},yr=(r=!1)=>{cr()&&Gd()&&In.isFollowing()&&(!r&&!Pn||(mr!==null&&(cancelAnimationFrame(mr),mr=null),ul=!0,mr=requestAnimationFrame(()=>{mr=null,ul=!1,In.isFollowing()&&Cw(Ff(),r?220:140)})))},qf=(r,a,d,f=()=>!0)=>{let y=r.scrollTop,C=a(),W=C-y;if(Ns(),Math.abs(W)<1){vn=!0,r.scrollTop=C,Ln=r.scrollTop,vn=!1;return}let z=performance.now();vn=!0;let q=Y=>1-Math.pow(1-Y,3),j=Y=>{if(!f()){Ns();return}let se=a();se!==C&&(C=se,W=C-y);let ge=Y-z,Qe=Math.min(ge/d,1),ct=q(Qe),ut=y+W*ct;r.scrollTop=ut,Ln=r.scrollTop,Qe<1?Ds=requestAnimationFrame(j):(r.scrollTop=C,Ln=r.scrollTop,Ds=null,vn=!1)};Ds=requestAnimationFrame(j)},Cw=(r,a=500)=>{let d=Jo(r)-r.scrollTop;if(Math.abs(d)<1){Ln=r.scrollTop;return}if(Math.abs(d)>=gw){Ns(),vn=!0,r.scrollTop=Jo(r),Ln=r.scrollTop,vn=!1;return}qf(r,()=>Jo(r),a,()=>In.isFollowing())},vl=()=>{if(!Gd()){qt();return}let r=Ff();vn=!0,r.scrollTop=Jo(r),Ln=r.scrollTop,vn=!1,qt()},es=r=>{let a=0,d=r;for(;d&&d!==ne;)a+=d.offsetTop,d=d.offsetParent;return a},ww=()=>{let r=ne.getRootNode();return(typeof r.getSelection=="function"?r.getSelection():null)??ne.ownerDocument.getSelection()},Cl=()=>Gh(ww(),ne),Qd=()=>{if(GC()!=="last-user-turn")return!1;let r=T?.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,'\\"'),f=ne.querySelector(`[data-message-id="${d}"]`);if(!f)return!1;let y=Math.min(Math.max(0,es(f)-Li()),Jo(ne));return vn=!0,ne.scrollTop=y,Ln=ne.scrollTop,vn=!1,kn()==="follow"&&!hs(ne,Do)&&In.pause(),qt(),!0},wl=r=>{let a=Math.max(0,Math.round(r));Fn.style.height=`${a}px`,Fn.style.display=a>0?"":"none",$t&&($t.spacerHeight=Math.max(0,r))},Sl=r=>{let a=parseFloat(getComputedStyle(ne).paddingBottom)||0,d=0;for(let y of Array.from(ne.children)){if(y===Fn||y.offsetHeight===0)continue;let C=es(y)+y.offsetHeight;C>d&&(d=C)}let f=ne.scrollHeight-r;return d>0?Math.min(d+a,f):f},Sw=()=>{if(!$t||$t.spacerHeight<=0)return;let r=Sl($t.spacerHeight),a=Math.max(0,Math.round(ne.scrollTop)+ne.clientHeight-r+Do);a<$t.spacerHeight&&(wl(a),qt())},so=()=>{Xr!==null&&(cancelAnimationFrame(Xr),Xr=null),Ns(),$t=null,Fn.style.height="0px",Fn.style.display="none"},zf=r=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Xd=r=>ne.querySelector(`[data-message-id="${zf(r)}"]`),jf=r=>{Xr!==null&&cancelAnimationFrame(Xr),Xr=requestAnimationFrame(()=>{Xr=null;let a=zf(r),d=ne.querySelector(`[data-message-id="${a}"]`);if(!d)return;let f=es(d),y=$t?.spacerHeight??0,C=Sl(y),{targetScrollTop:W,spacerHeight:z}=nu({anchorOffsetTop:f,topOffset:Li(),viewportHeight:ne.clientHeight,contentHeight:C,slack:Do});$t={initialSpacerHeight:z,contentHeightAtAnchor:C,spacerHeight:z},wl(z),qf(ne,()=>d.isConnected?Math.max(0,es(d)-Li()):W,220)})},wn=()=>{if(kn()!=="anchor-top"||!$t||!_s)return;let r=Xd(_s);if(!r)return;Ns();let a=$t.spacerHeight,d=Sl(a),{targetScrollTop:f,spacerHeight:y}=nu({anchorOffsetTop:es(r),topOffset:Li(),viewportHeight:ne.clientHeight,contentHeight:d,slack:Do});$t={initialSpacerHeight:y,contentHeightAtAnchor:d,spacerHeight:y},wl(y),vn=!0,ne.scrollTop=f,Ln=ne.scrollTop,vn=!1,qt()},xw=()=>{if(cr()){if(!In.isFollowing()||hs(ne,1))return;yr(!Pn);return}if($t&&$t.initialSpacerHeight>0){let r=ne.scrollHeight-$t.spacerHeight,a=Qh({initialSpacerHeight:$t.initialSpacerHeight,contentHeightAtAnchor:$t.contentHeightAtAnchor,currentContentHeight:r});a!==$t.spacerHeight&&wl(a)}qt()},Aw=r=>{let a=kn();a==="follow"?(Cn(),yr(!0)):a==="anchor-top"&&(Fi=!1,gl=!0,fl=!1,_s=r,jf(r))},Mw=()=>{if(kn()==="anchor-top"){if(gl){Fi=!1;return}Fi=!0,so(),Cn(),yr(!0)}},Ew=96,Tw=r=>{if(Yr===null)return!0;let a=Xd(Yr),d=Xd(r);if(!a||!d)return!0;let f=es(d)-es(a);return Li()+f>ne.clientHeight-Ew},kw=r=>{if(kn()!=="anchor-top"||!gl||fl||Cl())return;let a=Yr===null;for(let d of r){if(!a){d.id===Yr&&(a=!0);continue}if(zh(d)){if(d.id===_s||!Tw(d.id))return;_s=d.id,jf(d.id);return}}},Pw=r=>{let a=new Map;r.forEach(d=>{let f=zd.get(d.id);a.set(d.id,{streaming:d.streaming,role:d.role}),!f&&d.role==="assistant"&&(w.emit("assistant:message",d),!Bs&&(kn()!=="anchor-top"||Ug())&&Kd()&&(hr+=1,Vd(),qt(),Ya(hr===1?"1 new message below.":`${hr} new messages below.`))),d.role==="assistant"&&f?.streaming&&d.streaming===!1&&w.emit("assistant:complete",d),d.variant==="approval"&&d.approval&&(f?d.approval.status!=="pending"&&w.emit("approval:resolved",{approval:d.approval,decision:d.approval.status}):w.emit("approval:requested",{approval:d.approval,message:d}))}),zd.clear(),a.forEach((d,f)=>{zd.set(f,d)})},qi=(r,a)=>{let d=a==="user"?"user":"assistant",f=o.layout?.messages?.[d],y=f?.width??"content",C=f?.maxWidth??(y==="full"?"100%":void 0);r.classList.add("persona-message-row"),r.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),r.classList.add(`persona-message-row-${a}`,`persona-message-width-${y}`),r.classList.toggle("persona-justify-end",a==="user"),r.setAttribute("data-message-role",a),r.setAttribute("data-message-width",y),C?r.style.setProperty("--persona-message-row-max-width",C):r.style.removeProperty("--persona-message-row-max-width")},Uo=(r,a)=>{let d=document.createElement("div");return d.className="persona-flex",d.id=`wrapper-${r}`,d.setAttribute("data-wrapper-id",r),qi(d,a),d},Iw=(r,a,d)=>{let f=document.createElement("div"),C=(()=>{let L=l.find(ke=>ke.renderLoadingIndicator);if(L?.renderLoadingIndicator)return L.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),W=(L,ke)=>ke==null?!1:typeof ke=="string"?(L.textContent=ke,!0):(L.appendChild(ke),!0),z=new Set,q=new Map,j=new Set,Y=l.some(L=>L.renderAskUserQuestion),se=[],ge=[],Qe=o.enableComponentStreaming!==!1,ct=o.approval!==!1,ut=[],Kt=o.messageActions,Ot=Kt?.showRegenerate===!0&&Kt.enabled!==!1&&lt.current?.isStreaming()!==!0?Qy(a):null,Tt=Kt?.showEdit===!0&&Kt.enabled!==!1,on=Kt?.showQuote===!0&&Kt.enabled!==!1,Ye=null,rn=o.features?.reasoningDisplay?.completedVisibility,Mo=L=>rn==="removed"?!0:rn==="removed-when-short"?Ph(L,o.features?.reasoningDisplay?.shortThinkThreshold):!1,Xo=o.features?.toolCallDisplay?.completedVisibility==="removed";if(a.forEach(L=>{if(L.variant==="reasoning"&&L.reasoning?.status==="complete"&&Mo(L.reasoning)||Xo&&L.variant==="tool"&&L.toolCall?.status==="complete")return;if(z.add(L.id),q.set(L.id,L.role),Kr===L.id&&fr){let _e=Uo(L.id,L.role);_e.setAttribute("data-persona-message-edit-stub","true"),_e.setAttribute("data-preserve-runtime","true"),f.appendChild(_e),Ye={messageId:L.id,element:fr.element};return}let ke=Y&&ys(L),We=ct&&L.variant==="approval"&&!!L.approval,we=!ke&&L.role==="assistant"&&!L.variant&&Qe&&Lg(L);!We&&gr.has(L.id)&&(r.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),gr.delete(L.id)),!we&&Vr.has(L.id)&&(r.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),Vr.delete(L.id));let zt=ys(L)?`:${L.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${L.agentMetadata?.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",sn={canRegenerate:Ot===L.id,canEdit:Tt&&yu(L),canQuote:on&&!L.variant&&(L.content?.trim().length??0)>0},at=`${sn.canRegenerate?"r":""}${sn.canEdit?"e":""}${sn.canQuote?"q":""}`,Ie=lv(L,Qr)+zt+`:${at}`,io=ke||We||we?null:dv(Bt,L.id,Ie);if(io){f.appendChild(io.cloneNode(!0)),ys(L)&&L.toolCall?.id&&L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),xc(L,o,Oe.composerOverlay));return}let St=null,Zt=l.find(_e=>!!(L.variant==="reasoning"&&_e.renderReasoning||L.variant==="tool"&&_e.renderToolCall||!L.variant&&_e.renderMessage)),jt=o.layout?.messages;if(ys(L)&&L.agentMetadata?.askUserQuestionAnswered===!0){Ws.delete(L.id),r.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime");return}if(xa(L)&&Ir(o).enabled)return;if(ys(L)&&o.features?.askUserQuestion?.enabled!==!1){let _e=l.find(Wn=>typeof Wn.renderAskUserQuestion=="function");if(_e&&lt.current){let Wn=Ws.get(L.id),$e=Wn!==Ie,De=null;if($e){let{payload:dt,complete:ft}=ci(L),Yo=L.id,Gt=()=>lt.current?.getMessages().find(Gn=>Gn.id===Yo);De=_e.renderAskUserQuestion({message:L,payload:dt,complete:ft,resolve:Gn=>{let mt=Gt();mt&&lt.current?.resolveAskUserQuestion(mt,Gn)},dismiss:()=>{let Gn=Gt();Gn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(Gn),lt.current?.resolveAskUserQuestion(Gn,"(dismissed)"))},config:o})}let gt=Wn!=null;if($e&&De===null&&!gt){L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),xc(L,o,Oe.composerOverlay));return}let nt=Uo(L.id,L.role);nt.setAttribute("data-ask-plugin-stub","true"),nt.setAttribute("data-preserve-runtime","true"),f.appendChild(nt),se.push({messageId:L.id,fingerprint:Ie,bubble:De});return}else{L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),xc(L,o,Oe.composerOverlay));return}}else if(We){let _e=F();if(!_e){f.appendChild(Uo(L.id,L.role));return}let Wn=l.find(nt=>typeof nt.renderApproval=="function")??v,De=gr.get(L.id)!==Ie,gt=null;if(De&&Wn?.renderApproval){let nt=L.id,dt=(ft,Yo)=>{let Gt=lt.current?.getMessages().find(Gn=>Gn.id===nt);Gt?.approval&&(Gt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(Gt.id,ft):lt.current?.resolveApproval(Gt.approval,ft,Yo))};gt=Wn.renderApproval({message:L,defaultRenderer:()=>_e.createApprovalBubble(L,o),config:o,approve:ft=>dt("approved",ft),deny:ft=>dt("denied",ft)})}if(De&&gt===null)r.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),gr.delete(L.id),St=_e.createApprovalBubble(L,o);else{let nt=Uo(L.id,L.role);nt.setAttribute("data-approval-plugin-stub","true"),nt.setAttribute("data-preserve-runtime","true"),f.appendChild(nt),ut.push({messageId:L.id,fingerprint:Ie,bubble:gt});return}}else if(Zt)if(L.variant==="reasoning"&&L.reasoning&&Zt.renderReasoning){if(!uo)return;St=Zt.renderReasoning({message:L,defaultRenderer:()=>ug(L,o),config:o})}else if(L.variant==="tool"&&L.toolCall&&Zt.renderToolCall){if(!Dn)return;St=Zt.renderToolCall({message:L,defaultRenderer:()=>fg(L,o),config:o})}else Zt.renderMessage&&(St=Zt.renderMessage({message:L,defaultRenderer:()=>{let _e=tg(L,d,jt,o.messageActions,Ft,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:sn});return L.role!=="user"&&H(_e,L,o,T),_e},config:o}));if(!St&&we){let _e=vC(L);if(_e){let Wn=Vr.get(L.id),$e=Wn!==Ie,De=o.wrapComponentDirectiveInBubble!==!1&&Zo.getOptions(_e.component)?.bubbleChrome!==!1,gt=null;if($e){let nt=yC(_e,{config:o,message:L,transform:d});if(nt&&_e.component==="PersonaArtifactInline"){let dt=nt.hasAttribute("data-artifact-inline")?nt:nt.querySelector("[data-artifact-inline]"),ft=dt?.getAttribute("data-artifact-inline")??"",Yo=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(ft):ft,Gt=ft?r.querySelector(`#wrapper-${L.id}`)?.querySelector(`[data-artifact-inline="${Yo}"]`)??null:null;dt&&Gt&&Gt!==dt&&or()?.hasLiveInlineArtifactBlock(Gt)&&(dt===nt?nt=Gt:dt.replaceWith(Gt))}if(nt)if(De){let dt=document.createElement("div");if(dt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),dt.id=`bubble-${L.id}`,dt.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let ft=document.createElement("div");ft.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ft.innerHTML=d({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),dt.appendChild(ft)}dt.appendChild(nt),gt=dt}else{let dt=document.createElement("div");if(dt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",dt.id=`bubble-${L.id}`,dt.setAttribute("data-message-id",L.id),dt.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let ft=document.createElement("div");ft.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ft.innerHTML=d({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),dt.appendChild(ft)}dt.appendChild(nt),gt=dt}}if(gt||Wn!=null){let nt=Uo(L.id,L.role);nt.setAttribute("data-component-directive-stub","true"),nt.setAttribute("data-preserve-runtime","true"),f.appendChild(nt),ge.push({messageId:L.id,fingerprint:Ie,bubble:gt});return}}}if(!St)if(L.variant==="reasoning"&&L.reasoning){if(!uo)return;St=ug(L,o)}else if(L.variant==="tool"&&L.toolCall){if(!Dn)return;St=fg(L,o)}else if(L.variant==="approval"&&L.approval){if(o.approval===!1)return;let _e=F();if(!_e)return;St=_e.createApprovalBubble(L,o)}else{let _e=o.layout?.messages;_e?.renderUserMessage&&L.role==="user"?St=_e.renderUserMessage({message:L,config:o,streaming:!!L.streaming}):_e?.renderAssistantMessage&&L.role==="assistant"?St=_e.renderAssistantMessage({message:L,config:o,streaming:!!L.streaming}):St=tg(L,d,_e,o.messageActions,Ft,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:sn}),L.role!=="user"&&St&&H(St,L,o,T)}let kt=Uo(L.id,L.role);kt.appendChild(St),pv(Bt,L.id,Ie,kt),f.appendChild(kt)}),Oe.composerOverlay&&Oe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let We=ke.getAttribute("data-persona-ask-sheet-for");We&&!j.has(We)&&pi(Oe.composerOverlay,We)}),o.features?.toolCallDisplay?.grouped){let L=[],ke=[],We=o.features.toolCallDisplay.groupedMode==="summary";a.forEach(we=>{if(we.variant==="tool"&&we.toolCall&&Dn){if(Xo&&we.toolCall.status==="complete")return;ke.push(we);return}we.variant==="reasoning"&&(!uo||we.reasoning?.status==="complete"&&Mo(we.reasoning))||((ke.length>1||We&&ke.length>0)&&L.push(ke),ke=[])}),(ke.length>1||We&&ke.length>0)&&L.push(ke),L.forEach(we=>{let zt=we.map(jt=>Array.from(f.children).find(kt=>kt instanceof HTMLElement&&kt.getAttribute("data-wrapper-id")===jt.id)).filter(jt=>!!jt);if(zt.length<(We?1:2))return;let sn=Uo(`tool-group-${we[0].id}`,"assistant");sn.setAttribute("data-persona-tool-group-row","true");let at=document.createElement("div");at.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",at.setAttribute("data-persona-tool-group","true");let Ie=document.createElement("div");Ie.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",Ie.id=`tool-group-summary-${we[0].id}`;let io=`Called ${we.length} ${we.length===1?"tool":"tools"}`,St=o.toolCall?.renderGroupedSummary?.({messages:we,toolCalls:we.map(jt=>jt.toolCall).filter(jt=>!!jt),defaultSummary:io,config:o});W(Ie,St)||(Ie.textContent=io);let Zt=document.createElement("div");Zt.className="persona-tool-group-stack persona-flex persona-flex-col",Zt.id=`tool-group-stack-${we[0].id}`,Zt.setAttribute("data-persona-tool-group-stack","true"),at.appendChild(Ie),We||at.appendChild(Zt),sn.appendChild(at),zt[0].before(sn),zt.forEach((jt,kt)=>{if(We){jt.remove();return}jt.style.setProperty("--persona-message-row-max-width","100%");let _e=document.createElement("div");_e.className="persona-tool-group-item persona-relative",_e.setAttribute("data-persona-tool-group-item","true"),kt<zt.length-1&&_e.setAttribute("data-persona-tool-group-connector","true"),_e.appendChild(jt),Zt.appendChild(_e)})})}uv(Bt,z);let Eo=a.some(L=>L.role==="assistant"&&L.streaming),ni=a[a.length-1],gs=ni?.role==="assistant"&&!ni.streaming&&ni.variant!=="approval";if(Pn&&a.some(L=>L.role==="user")&&!Eo&&!gs){let L={config:o,streaming:!0,location:"standalone",defaultRenderer:$a},ke=l.find(we=>we.renderLoadingIndicator),We=null;if(ke?.renderLoadingIndicator&&(We=ke.renderLoadingIndicator(L)),We===null&&o.loadingIndicator?.render&&(We=o.loadingIndicator.render(L)),We===null&&(We=$a()),We){let we=document.createElement("div"),zt=o.loadingIndicator?.showBubble!==!1,sn=o.layout?.messages?.layout??"bubble";we.className=zt?qa("assistant",sn).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),we.setAttribute("data-typing-indicator","true"),zt&&(we.style.color="var(--persona-message-assistant-text, var(--persona-text))",sn!=="flat"&&(we.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",we.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),we.appendChild(We);let at=Uo("typing-indicator","assistant");at.appendChild(we),f.appendChild(at)}}if(!Pn&&a.length>0){let L=a[a.length-1],ke={config:o,lastMessage:L,messageCount:a.length},We=l.find(zt=>zt.renderIdleIndicator),we=null;if(We?.renderIdleIndicator&&(we=We.renderIdleIndicator(ke)),we===null&&o.loadingIndicator?.renderIdle&&(we=o.loadingIndicator.renderIdle(ke)),we){let zt=document.createElement("div"),sn=o.loadingIndicator?.showBubble!==!1;zt.className=sn?["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(" "),zt.setAttribute("data-idle-indicator","true"),zt.appendChild(we);let at=Uo("idle-indicator","assistant");at.appendChild(zt),f.appendChild(at)}}if(ly(f),ed(r,f),su(r),Ye){let{messageId:L,element:ke}=Ye,We=r.querySelector(`#wrapper-${L}`);We&&ke.parentElement!==We&&(qi(We,q.get(L)??"user"),We.replaceChildren(ke))}if(se.length>0)for(let{messageId:L,fingerprint:ke,bubble:We}of se){let we=r.querySelector(`#wrapper-${L}`);we&&(qi(we,q.get(L)??"assistant"),We!==null&&(we.replaceChildren(We),we.setAttribute("data-bubble-fp",ke),Ws.set(L,ke)))}if(Ws.size>0)for(let L of Ws.keys())z.has(L)||Ws.delete(L);if(ge.length>0)for(let{messageId:L,fingerprint:ke,bubble:We}of ge){let we=r.querySelector(`#wrapper-${L}`);we&&(qi(we,q.get(L)??"assistant"),We!==null&&(we.replaceChildren(We),we.setAttribute("data-bubble-fp",ke),Vr.set(L,ke)))}if(Vr.size>0)for(let L of Vr.keys())z.has(L)||Vr.delete(L);if(ut.length>0)for(let{messageId:L,fingerprint:ke,bubble:We}of ut){let we=r.querySelector(`#wrapper-${L}`);we&&(qi(we,q.get(L)??"assistant"),We!==null&&(we.replaceChildren(We),we.setAttribute("data-bubble-fp",ke),gr.set(L,ke)))}if(gr.size>0)for(let L of gr.keys())z.has(L)||gr.delete(L)},Yd=!1,xl=()=>{Yd||(Yd=!0,Sh().catch(()=>{Yd=!1}))},$n=(r,a,d)=>{a.length>0&&xl(),Iw(r,a,d),pf()},zi=null,Lw=()=>{if(zi)return;let r=d=>{let f=d.composedPath();f.includes(Ve)||Vt&&f.includes(Vt)||pt(!1,"user")};zi=r,(t.ownerDocument??document).addEventListener("pointerdown",r,!0)},Vf=()=>{if(!zi)return;(t.ownerDocument??document).removeEventListener("pointerdown",zi,!0),zi=null};he.push(()=>Vf());let ji=null,Hw=()=>{if(ji)return;let r=d=>{d.key==="Escape"&&(d.isComposing||pt(!1,"user"))};ji=r,(t.ownerDocument??document).addEventListener("keydown",r,!0)},Kf=()=>{if(!ji)return;(t.ownerDocument??document).removeEventListener("keydown",ji,!0),ji=null};he.push(()=>Kf());let Vi=!1,Gf=new Set,Rw=()=>{let r=o.launcher?.composerBar?.peek?.streamAnimation;return r||o.features?.streamAnimation},Fs=()=>{if(!Re())return;let r=Oe.peekBanner,a=Oe.peekTextNode;if(!r||!a)return;if(ye){r.classList.remove("persona-pill-peek--visible");return}let d=T?.getMessages()??[],f;for(let Ot=d.length-1;Ot>=0;Ot--){let Tt=d[Ot];if(Tt.role==="assistant"&&Tt.content){f=Tt;break}}if(!f){r.classList.remove("persona-pill-peek--visible");return}let y=f.content,C=!!f.streaming,W=Rw(),z=bc(W),q=z.type!=="none"?Ud(z.type,W?.plugins):null,j=q?.isAnimating?.(f)===!0,Y=q!==null&&(C||j);Y&&q&&!Gf.has(q.name)&&(va(q,t),Gf.add(q.name));let se=Y&&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),Y?(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 Qe=Y?vc(y,z.buffer,q,f,C):y;if(Y&&z.placeholder==="skeleton"&&C&&(!Qe||!Qe.trim())){let Ot=document.createElement("div"),Tt=ba();Tt.classList.add("persona-pill-peek__skeleton"),Ot.appendChild(Tt),ed(a,Ot)}else{let Ot=Math.max(0,Qe.length-100),Tt=Qe.length>100?Qe.slice(-100):Qe,on=cc(Tt);if(!Y||!q){let Ye=Qe.length>100?`\u2026${Tt}`:Tt;a.textContent!==Ye&&(a.textContent=Ye)}else{let Ye=on;(q.wrap==="char"||q.wrap==="word")&&(Ye=ya(on,q.wrap,`peek-${f.id}`,{skipTags:q.skipTags,startIndex:Ot}));let rn=document.createElement("div");if(rn.innerHTML=Ye,q.useCaret&&Tt.length>0){let Mo=Cc(),Xo=rn.querySelectorAll(".persona-stream-char, .persona-stream-word"),Eo=Xo[Xo.length-1];Eo?.parentNode?Eo.parentNode.insertBefore(Mo,Eo.nextSibling):rn.appendChild(Mo)}ed(a,rn),q.onAfterRender?.({container:a,bubble:r,messageId:f.id,message:f,speed:z.speed,duration:z.duration})}}let Kt=Pn||Vi;r.classList.toggle("persona-pill-peek--visible",Kt)};if(Re()){let r=Oe.peekBanner;if(r){let f=y=>{y.preventDefault(),y.stopPropagation(),pt(!0,"user")};r.addEventListener("pointerdown",f),he.push(()=>{r.removeEventListener("pointerdown",f)})}let a=()=>{Vi||(Vi=!0,Fs())},d=()=>{Vi&&(Vi=!1,Fs())};Se.addEventListener("pointerenter",a),Se.addEventListener("pointerleave",d),he.push(()=>{Se.removeEventListener("pointerenter",a),Se.removeEventListener("pointerleave",d)}),Vt&&(Vt.addEventListener("pointerenter",a),Vt.addEventListener("pointerleave",d),he.push(()=>{Vt.removeEventListener("pointerenter",a),Vt.removeEventListener("pointerleave",d)}))}let Ww=r=>{let a=o.launcher?.composerBar??{},d=a.expandedSize??"anchored",f=a.bottomOffset??"16px",y=a.collapsedMaxWidth,C=a.expandedMaxWidth??"880px",W=a.expandedTopOffset??"5vh",z=a.modalMaxWidth??"880px",q=a.modalMaxHeight??"min(90vh, 800px)",j="calc(100vw - 32px)",Y="var(--persona-pill-area-height, 80px)",se=Ve.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=f,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(${f} + ${Y})`,se.top=W,se.width=C,se.maxWidth=j}},Ki=()=>{if(ye&&xl(),!Pe())return;if(Re()){let j=(o.launcher?.composerBar??{}).expandedSize??"anchored",Y=ye?"expanded":"collapsed";Ve.dataset.state=Y,Ve.dataset.expandedSize=j,Vt&&(Vt.dataset.state=Y,Vt.dataset.expandedSize=j),Ve.style.removeProperty("display"),Ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ww(ye),ue.style.display=ye?"flex":"none",Fr(),ye?(Lw(),Hw()):(Vf(),Kf()),Fs();return}let r=Rt(o),a=t.ownerDocument.defaultView??window,d=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,y=a.innerWidth<=d,C=f&&y&&be,W=Yn(o).reveal;ye?(Ve.style.removeProperty("display"),Ve.style.display=r?"flex":"",Ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0"),Se.classList.add("persona-scale-100","persona-opacity-100"),Mt?(Mt.setPanelOpen(!0),Mt.element.style.display="none"):cn&&(cn.style.display="none")):(r?r&&(W==="overlay"||W==="push")&&!C?(Ve.style.removeProperty("display"),Ve.style.display="flex",Ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ve.style.setProperty("display","none","important"),Ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ve.style.display="",Ve.classList.add("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100"),Se.classList.add("persona-scale-95","persona-opacity-0")),Mt?(Mt.setPanelOpen(!1),Mt.element.style.display=r?"none":""):cn&&(cn.style.display=r?"none":""))},pt=(r,a="user")=>{if(!Pe()||ye===r)return;let d=ye;ye=r,Ki();let f=(()=>{let C=o.launcher?.sidebarMode??!1,W=t.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640,j=W.innerWidth<=q,Y=Rt(o)&&z&&j,se=Re()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return C||z&&j&&be||Y||se})();if(ye&&f){if(!Co){let C=t.getRootNode(),W=C instanceof ShadowRoot?C.host:t.closest(".persona-host");W&&(Co=Vu(W,o.launcher?.zIndex??an))}wo||(wo=Ku(t.ownerDocument))}else ye||(Co?.(),Co=null,wo?.(),wo=null);ye&&(da(),Qd()||(kn()==="follow"?yr(!0):vl()));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:be,voiceActive:ze.active,streaming:T.isStreaming()})},br={inputDisabled:!1,sendDisabled:!1},vr=()=>br.inputDisabled,ts=()=>br.inputDisabled||br.sendDisabled,Bw=()=>(br.inputDisabled?br.inputReason:void 0)??(br.sendDisabled?br.sendReason:void 0);function Jd(){if(!xe)return;if(Ce.getState().phase==="streaming"){xe.disabled=!1;return}let r=Xe?!Xe.isReady():!1;xe.disabled=ts()||r}function Al(){if(!mo)return;let r=Ce.getState(),a=o.sendButton?.visibility==="when-text"&&r.phase!=="streaming"&&r.text.trim().length===0&&r.attachments.length===0;mo.toggleAttribute("data-persona-send-hidden",a)}function _w(){let r=Bw();if(Re()){let a=eo??He;r?a.setAttribute("title",r):a.removeAttribute("title"),He.toggleAttribute(Ti,!!r);return}if(r){st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.setAttribute(Ti,""),st.textContent=r;return}if(st.hasAttribute(Ti)&&(st.removeAttribute("role"),st.removeAttribute("aria-live"),st.removeAttribute(Ti),g)){let a=T.getStatus();Ga(st,mn(a),o.statusIndicator??{},a)}}function Zd(){let r=Iu(o.composer?.inputDisabled),a=Iu(o.composer?.sendDisabled);br={inputDisabled:r.disabled,inputReason:r.reason,sendDisabled:a.disabled,sendReason:a.reason},Ce.setInputDisabled(r.disabled),Ce.setSendDisabled(a.disabled);let d=Ce.getState().phase==="streaming",f=r.disabled,y=d||f;pe&&(pe instanceof HTMLTextAreaElement?pe.disabled=f:pe.setAttribute("contenteditable",f?"false":"true"),pe.setAttribute("aria-disabled",f?"true":"false")),wt&&(wt.disabled=f),ht&&(ht.disabled=f);for(let C of Ht?.affordanceButtons??[])C.querySelectorAll("button").forEach(W=>{W.disabled=f});oe&&(oe.disabled=y),qr.forEach(C=>{C.elements.forEach(W=>{W.toggleAttribute("data-disabled",y),W instanceof HTMLButtonElement||W.setAttribute("aria-disabled",y?"true":"false")}),C.buttons.forEach(W=>{W.disabled=y})}),rp.forEach(C=>{C.toggleAttribute("data-disabled",y),C instanceof HTMLButtonElement?C.disabled=y:C.setAttribute("aria-disabled",y?"true":"false"),C.querySelectorAll("button").forEach(W=>{W.disabled=y})}),He.dataset.personaComposerStreaming=d?"true":"false",He.dataset.personaComposerInputDisabled=f?"true":"false",He.dataset.personaComposerSendDisabled=ts()?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(C=>{(C instanceof HTMLButtonElement||C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement||C instanceof HTMLSelectElement)&&(C.disabled=d)}),Jd(),_w()}let Gi=r=>{Ce.setStreaming(r),Ng(r?"stop":"send"),Zd()},ns=()=>{ze.active||pe&&pe.focus()};w.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ns(),200)});let os=null,Qi=!1,ep=!hn.hidden,Cr=null,tp=!S,Ml=null;he.push(()=>{Ml?.cancel(),Ml=null});let Ow=r=>{let a=Lv(r);if(a===Ja)return;Ja=a,t.setAttribute("data-persona-conversation-state",a);let d=Md();el(),tp&&(Ml?.cancel(),Ml=Pv(He,a==="active"?d:Md(),a==="active"?"drop":"rise")),wn()},Qf=null,Xf,Yf=null,Us=null,np=!1,Xi=r=>{let a=nr(o),d=`${a.variant}|${a.dismiss}|${a.anchor??"bottom"}|${a.align??""}|${a.iconPlacement}|${a.kicker??""}|${a.title}|${a.subtitle}`;(d!==Qf||a.icon!==Xf)&&(Qf=d,Xf=a.icon,id({host:hn,iconHolder:FC,kicker:UC,title:$C,subtitle:qC,starterSuggestions:wd},a));let f=a.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${a.message}`;f!==Yf&&(Yf=f,ad(En,a.message,o));let y=r??(T?T.getMessages():o.initialMessages);Ow(y);let C=Qi,W=!C&&Ci(a,y),z=W!==ep;if(ep=W,Us){Cr?.cancel(),Cr=null,C!==np&&(np=C,C?rg(ne,hn,null):og(ne,hn,Us)),vi(ne,hn,!C);return}if(z&&!W&&!C&&a.dismiss==="on-first-message"&&tp){Cr=kv(hn,j=>{Cr===j&&(Cr=null),!ep&&!Us&&(vi(ne,hn,!1),wn()),j?.cancel()});return}if(Cr){if(!W&&!C)return;Cr.cancel(),Cr=null}let q=!hn.hidden;vi(ne,hn,W),!W&&q&&wn()},op=[],rp=[],sp=!1,Jf=null,Zf,em=()=>{rp.length=0;let r=op.splice(0,op.length);for(let a of r)try{a()}catch(d){console.warn("[persona] renderWelcome cleanup threw",d)}};he.push(em);let Dw=(r,a)=>{let d=Qu(r,a);if(!d)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),k("span");let f=o.suggestions?.starters,y=Xu({item:{...d,behavior:d.behavior??f?.behavior??"send"},index:a,surface:"starter",source:"config",variant:f?.variant??"card",streaming:g?T.isStreaming():!1,config:o,plugins:l,chipsConfig:o.suggestionChipsConfig,session:T,getTextarea:()=>pe,eventTarget:hn,submitPrompt:Jl});return rp.push(y),y},ip=()=>{if(sp)return;sp=!0;let r=nr(o);Jf=`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`,Zf=r.icon;try{em(),rg(ne,hn,Us),Us=null,np=!1;let a=T?T.getMessages():o.initialMessages,d=Ci(r,a),f=0,y=null;for(let C of l)if(C.renderWelcome&&(y=C.renderWelcome({config:r,variant:r.variant,visible:d,defaultRenderer:()=>hn,sendMessage:W=>{if(!T||T.isStreaming())return;let z=W.trim();z&&T.sendMessage(z)},requestRender:()=>ip(),renderStarter:W=>Dw(W,f++),storage:u(C.id),onCleanup:W=>{op.push(W)}}),y))break;y&&y!==hn&&(Us=y,og(ne,hn,y))}finally{sp=!1}Xi()},Nw=()=>{let r=nr(o);`${r.variant}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`===Jf&&r.icon===Zf||ip()},El=()=>{Xi(),Ps||(pe.placeholder=Rb(Ce.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!T?.isStreaming()&&(xe.textContent=o.copy?.sendButtonLabel??"Send")),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Fw=!!o.setStoredConversationId,$s=r=>ie(a=>{let d={...a};return delete d[r],d}),Tl=r=>{let a=ee[r];return typeof a=="string"?a:null},tm=()=>{let r=ee.durableResume;if(!r||typeof r!="object")return null;let a=r;return typeof a.executionId=="string"&&a.executionId.length>0&&typeof a.after=="string"&&a.after.length>0?{executionId:a.executionId,after:a.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Tl("sessionId"),setStoredSessionId:r=>{ie(a=>({...a,sessionId:r}))},clearStoredSessionId:o.clearStoredSessionId??(()=>$s("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Tl("conversationId")),setStoredConversationId:o.setStoredConversationId??(r=>{ie(a=>({...a,conversationId:r}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>$s("conversationId"))});let nm=()=>o.clientToken??null,om=r=>pC(r,Jn(),o.persistState===!1),rm=nm(),$o=rm?om(rm):null,qo={...$o?{visitorStore:$o}:{},historyBootstrapReady:R,getStoredMessageCursor:()=>Tl("historyMessageCursor"),setStoredMessageCursor:r=>{if(r===null){$s("historyMessageCursor");return}ie(a=>({...a,historyMessageCursor:r}))},getPendingDisplayProjections:()=>{let r=ee.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){$s("pendingDisplayProjections");return}ie(a=>({...a,pendingDisplayProjections:r}))},getStoredResumableHandle:tm,setStoredResumableHandle:r=>{if(!r){$s("durableResume");return}ie(a=>({...a,durableResume:r}))},shouldResumeDurableConversation:()=>le&&tm()!==null,...Fw?{}:{getStoredConversationRevision:()=>Tl("conversationRevision"),setStoredConversationRevision:r=>{if(r===null){$s("conversationRevision");return}ie(a=>({...a,conversationRevision:r}))}}};if(le){let r=o.onExecutionState,a=t.ownerDocument.defaultView,d=!1,f=()=>d=!0,y=()=>d=!1;a?.addEventListener("pagehide",f),a?.addEventListener("pageshow",y),he.push(()=>{a?.removeEventListener("pagehide",f),a?.removeEventListener("pageshow",y)}),o={...o,reconnectStream:o.reconnectStream??(C=>T.getClient().reconnectClientTokenStream(C)),onExecutionState:C=>{(C||!d)&&qo.setStoredResumableHandle?.(C?{executionId:C.executionId,after:C.lastEventId}:null),r?.(C)}}}let Uw=()=>{let r=nm();if(r&&$o?.matches(r,Jn(),o.persistState===!1)||!r&&!$o)return;$o?.destroy(),$o=r?om(r):null;let a={...qo};$o?a.visitorStore=$o:delete a.visitorStore,qo=a,T.setHistoryInternals(qo)},rs=null,$w=()=>{rs==null&&(rs=setInterval(()=>{let r=Te.querySelectorAll("[data-tool-elapsed]");if(r.length===0){clearInterval(rs),rs=null;return}let a=Date.now();r.forEach(d=>{let f=Number(d.getAttribute("data-tool-elapsed"));f&&(d.textContent=Lh(a-f))})},100))},ap=(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((W,z)=>ap(W,a[z]));let d=r,f=a,y=Object.keys(d),C=Object.keys(f);return y.length===C.length&&y.every(W=>Object.prototype.hasOwnProperty.call(f,W)&&ap(d[W],f[W]))},sm=r=>{let{content:a,rawContent:d,llmContent:f,...y}=r;return y},lp=r=>r.role==="assistant"&&r.streaming===!0&&!r.variant&&!r.toolCall&&!r.tools&&!r.approval&&!r.reasoning&&!r.contentParts&&!r.stopReason&&!Lg(r),qw=(r,a,d)=>{if(r.length!==a.length)return!1;let f=r[d.index],y=a[d.index];return!f||!y||f.id!==d.id||y.id!==d.id?!1:(!Object.is(f.content,y.content)||!Object.is(f.rawContent,y.rawContent)||!Object.is(f.llmContent,y.llmContent))&&lp(f)&&lp(y)&&ap(sm(f),sm(y))},cp=null,qs=null,ss=null,zo=null,dp=null,zw=r=>{if(!le)return Os(r);dp=r,queueMicrotask(()=>{dp===r&&(dp=null,Os(r))})},kl=r=>{cp=r;let a,d;qs=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),!qs&&lp(C)&&(qs={index:y,id:C.id}),a&&d&&qs)break}$n(Te,r,It),or()?.updateInlineArtifactBlocks(Te,Un.artifacts,{suppressTransition:Pn}),$w(),Xi(r),Rs(r),yr(!Pn),Pw(r),r.length===0&&(so(),Fi=!0,gl=!1,_s=null,fl=!1),!$d||Bs?($d=!0,Yr=a?.id??null,qd=d?.id??null):a&&a.id!==Yr?(Yr=a.id,Aw(a.id)):d&&d.id!==qd&&Mw(),d&&(qd=d.id),kw(r);let f=ze.lastUserMessageId;a&&a.id!==f&&(ze.lastUserMessageId=a.id,w.emit("user:message",a)),ze.lastUserMessageWasVoice=!!a?.viaVoice,zw(r),Fs()},pp=()=>{zo!==null&&(cancelAnimationFrame(zo),zo=null);let r=ss;ss=null,r&&kl(r)},im=()=>{zo!==null&&cancelAnimationFrame(zo),zo=null,ss=null},jw=r=>{let a=ss??cp;if(Pn&&a&&qs&&qw(a,r,qs)){ss=r,zo===null&&(zo=requestAnimationFrame(()=>{zo=null;let d=ss;ss=null,d&&kl(d)}));return}if(r.length===0){im(),kl(r);return}pp(),kl(r)};T=new Lc(o,{onMessagesChanged(r){jw(r)},onStatusChanged(r){let a=o.statusIndicator??{};Ga(st,(f=>f==="idle"?a.idleText??Dt.idle:f==="connecting"?a.connectingText??Dt.connecting:f==="connected"?a.connectedText??Dt.connected:f==="error"?a.errorText??Dt.error:f==="paused"?a.pausedText??Dt.paused:f==="resuming"?a.resumingText??Dt.resuming:Dt[f])(r),a,r),Ro()},onStreamingChanged(r){r||(T?.getMessages().length===0?im():pp()),Pn=r,Gi(r),Ro(),T&&$n(Te,T.getMessages(),It),r||(yr(!0),Sw(),Hf=!0,T&&Rf(T.getMessages(),Ir(o))),qt(),Ya(r?"Responding\u2026":"Response complete."),Fs()},onVoiceStatusChanged(r){if(w.emit("voice:status",{status:r,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(r){case"listening":Qo(),ei();break;case"processing":Qo(),KS();break;case"speaking":Qo(),GS();break;default:r==="idle"&&T.isBargeInActive()?(Qo(),ei(),oe?.setAttribute("aria-label","End voice session")):(ze.active=!1,Qo(),Fo("system"),ro());break}},onArtifactsState(r){Un=r,r.artifacts.length===0&&(Is=!1),or()?.updateInlineArtifactBlocks(Te,r.artifacts,{suppressTransition:Pn}),oo(),Os()},onHistoryStateChanged(r){Lt(r)},onHistoryNotice(r){xt(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})}},qo),lt.current=T,he.push(()=>T.cancel()),he.push(()=>{T.destroy(),$o?.destroy()});let up=null;if(T.onReadAloudChange((r,a)=>{cf=r,df=a,pf();let d=r??up;r&&(up=r);let f=d?T.getMessages().find(y=>y.id===d)??null:null;w.emit("message:read-aloud",{messageId:d,message:f,state:a,timestamp:Date.now()}),a==="idle"&&(up=null)}),g=!0,$d=!0,o.voiceRecognition?.provider?.type==="runtype")try{T.setupVoice()}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",r)}let Vw=720,Kw=250,Ge=ru(o.features?.history?.copy),Hn=null,gp=!1,it=null,Pl=null,Il="conversation",fp=null,ln=null,So=null,Ll=T.getHistoryState(),mp=null,Yi=0,hp=null,Hl=null,Rl=null,yp=`persona-history-${Math.random().toString(36).slice(2,8)}`,bp=()=>o.features?.history?.enabled===!0,xo=()=>bp()&&!!Hn&&!gp,am=()=>{let r=T.getStatus();return Pn||r==="paused"||r==="resuming"},vp=()=>{let r=o.features?.history?.scope;if(r)return r;let a=o.getIdentityProof?"verified-user":"browser",d=Hn?.capabilities.scopes;return!d||d.includes(a)?a:d[0]??a},zs=()=>Pl?.scope??vp(),lm=()=>T.getClientSession()?.targetId??null,cm=r=>`${r.state}:${"reason"in r?r.reason:""}`,Gw=r=>{let a=cm(r);a!==mp&&(mp=a,w.emit("history:identityStatusChanged",{status:r,timestamp:Date.now()}))},Wl=r=>{r&&(Wo.textContent="",Wo.textContent=r)},dm=null,pm=null,Qw=()=>{if(!bp())return null;let r=mC();if(r)return r();let a=o.features?.history?.provider;return a?typeof a!="function"?a:(dm!==a&&(dm=a,pm=a()),pm):T.isClientTokenMode()?hC({client:T.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:d=>T.bindActivatedSession(d),getClient:()=>T.getClient()}):null},um=()=>{Hl?.(),Hl=null,Rl?.(),Rl=null,gp=!1,Hn=Qw();let r={...qo};Hn?r.historyProvider=Hn:delete r.historyProvider,qo=r,T.setHistoryInternals(qo),Hn&&(Hl=Hn.subscribeAvailability?.(a=>{gp=!a,a||Sn({restoreFocus:!1}),Sr()})??null,Rl=Hn.subscribeIdentityStatus(a=>Gw(a)),mp=cm(Hn.getIdentityStatus()))},Cp=()=>{let r=o.features?.history?.presentation??"panel";if(r==="panel"||r==="auto"&&!(!be||Rt(o)))return"panel";let a=vo??ue;return(a.getBoundingClientRect().width||a.clientWidth)>=Vw?"rail":"panel"},qn=(r,a)=>{a?(r.setAttribute("aria-hidden","true"),r.setAttribute("inert","")):(r.removeAttribute("aria-hidden"),r.removeAttribute("inert"))},Bl="data-persona-history-suppressed",Rn=null,wr=null,is=null,Ji=null,wp=null,gm="",fm=()=>Ae===wp?gm:o.layout?.showHeader===!1?"none":"",Xw=()=>de==="panel"&&!!is&&Ji===is.element&&o.layout?.showHeader!==!1&&fm()!=="none",Yw=()=>{for(let r of Array.from(Ae.children))r!==Rn&&r.setAttribute(Bl,"")},Jw=()=>{for(let r of Array.from(ue.querySelectorAll(`[${Bl}]`)))r.removeAttribute(Bl)},Zw=()=>{let r=is;if(!r)return;if(Array.from(Ae.children).some(f=>f!==Rn&&!f.hasAttribute(Bl))){wr&&wr!==Ae&&(wr.style.removeProperty("min-height"),wr=null);let f=Ae.offsetHeight;f>0&&(Ae.style.minHeight=`${f}px`,wr=Ae)}Rn||(Rn=k("div","persona-history-header-host")),r.setHeaderPlacement("external");let d=r.getHeaderElement();d.parentNode!==Rn&&Rn.replaceChildren(d),Rn.parentNode!==Ae&&Ae.appendChild(Rn),Yw()},mm=()=>{wr&&(wr.style.removeProperty("min-height"),wr=null),Rn&&(is?.setHeaderPlacement("inline"),Rn.remove(),Rn=null,Jw())},_l=null,Sp=()=>{if(_l){if(ne.style.display="none",qn(ne,!0),He.hidden=!0,qn(He,!0),Xw()){Zw(),Ae.style.display=fm(),qn(Ae,!1);return}mm(),Ae.style.display="none",qn(Ae,!0)}};Nt=Sp;let eS=r=>{let a=ne.style.display,d=He.hidden,f=He,y=Ae,C=Ae.style.display;wp=y,gm=C,_l=()=>{_l=null,mm(),wp=null,ne.style.display=a,qn(ne,!1),f.hidden=d,qn(f,!1),He!==f&&(He.hidden=!1,qn(He,!1)),y.style.display=C,qn(y,!1),Ae!==y&&(Ae.style.display=o.layout?.showHeader===!1?"none":"",qn(Ae,!1))},He.parentNode?.insertBefore(r,He),Sp()},js=null,as=null,Zi=null,Vs=null,hm=()=>[Ae,Oe.closeButtonWrapper,Oe.clearChatButtonWrapper,ne,He],tS=52,Ol=()=>o.features?.history?.rail?.collapsible!==!1,Ks=()=>o.features?.history?.rail?.side==="right"?"right":"left",xp=200,Ap=400,Mp=r=>Math.min(Ap,Math.max(xp,Math.round(r))),nS=()=>o.features?.history?.rail?.resizable===!0,ea,oS=()=>{if(ea===void 0&&(ea=null,o.persistState!==!1))try{let r=Number(window.localStorage.getItem(`${Jn()}rail-width`));r&&(ea=r)}catch{}return ea},ta=()=>Mp(oS()??o.features?.history?.rail?.width??260),rS=r=>{if(ea=r,o.persistState!==!1)try{window.localStorage.setItem(`${Jn()}rail-width`,String(r))}catch{}},Dl=()=>Ol()&&o.features?.history?.rail?.collapsedBehavior==="overlay",_t=!1,ym=r=>{let a=k("img");return a.src=r,a.alt="",a.setAttribute("aria-hidden","true"),a},sS=()=>{let r=o.features?.history?.rail?.brand;if(!r)return;let a=!1,d;return f=>{if(r.render)try{return r.render({collapsed:f})??null}catch(y){return a||(a=!0,console.warn("[persona] history rail brand threw",y)),null}return d===void 0&&(r.iconUrl?d=ym(r.iconUrl):d=r.icon?me(r.icon,20):null),d?d.cloneNode(!0):null}},iS=()=>o.features?.history?.rail?.sections?.map(r=>{let a=!1,d=f=>{a||(a=!0,console.warn("[persona] history rail section threw",r.id,f))};return{id:r.id,title:r.title,placement:r.placement??"above-conversations",items:r.items.map(f=>{let y;return{id:f.id,label:f.label,badge:f.badge,iconNode:()=>{if(y!==void 0)return y;try{f.renderIcon?y=f.renderIcon()??null:f.iconUrl?y=ym(f.iconUrl):y=f.icon?me(f.icon,20):null}catch(C){d(C),y=null}return y},onSelect:()=>{try{f.onSelect()}catch(C){d(C)}}}})}})??[],aS=r=>{let a=iS();for(let d of r)a.some(f=>f.id===d.id)?console.warn("[persona] duplicate history rail section id",d.id):a.push(d);return a.length?a:void 0},na=null,bm=()=>`${Jn()}rail-collapsed`,Ep=()=>{if(na===null&&(na=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let r=window.localStorage.getItem(bm());r&&(na=r==="1")}catch{}return na},Tp=r=>{if(na=r,o.persistState!==!1)try{window.localStorage.setItem(bm(),r?"1":"0")}catch{}},oa=()=>de==="rail"&&Ol()&&!Dl()&&Ep(),kp=()=>{},vm=()=>{if(Dl()){kp();return}Tp(!Ep()),it?.view.setCollapsed(oa()),Be(),wn()},Pp=()=>{let r=o.features?.history?.rail?.collapseShortcut;return!r||!Jc(r)?null:{combo:r,hint:Zc(r),aria:Ba(r)}},Cm=()=>{p.forEach(a=>a()),p=[];let r=Pp();r&&p.push(c.register({id:"history-rail-collapse",combo:r.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ae&&de==="rail"&&Ol()||Qs(),run:()=>Dl()?kp():vm()}));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}`}))};Cm();let lS=300,Nl="var(--persona-history-overlay-margin,8px)",zn=null,jo=null,Fl=0,Vo=null,Gs=null,ls=!1,Ip=0,wm=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Qs=()=>xo()&&Dl()&&(de??Cp())==="rail",cS=()=>ae&&!_t,ra=()=>{Gs!==null&&clearTimeout(Gs),Gs=null},dS=()=>{kg().catch(()=>{})},Sm=()=>{ra(),_t&&(Gs=setTimeout(()=>{Gs=null,!(ls||!_t)&&(Vo?.contains(document.activeElement)||Sn({restoreFocus:!1}))},lS))},pS=(r,a)=>{let d=Vo?.getBoundingClientRect();if(!d)return!1;let f=zn?.getBoundingClientRect(),y=f?Math.min(f.top,d.top):d.top;return r>=d.left&&r<=d.right&&a>=y&&a<=d.bottom||!!f&&r>=f.left&&r<=f.right&&a>=f.top&&a<=f.bottom},Lp=r=>{_t&&(ls=pS(r.clientX,r.clientY),ls?ra():Gs===null&&Sm())},xm=r=>{ae||!Qs()||(_t=!0,ia({invoker:zn,keyboard:r?.keyboard===!0}).then(()=>{ae?!ls&&document.activeElement!==zn&&Sn():_t=!1}))},Am=()=>{let r=Ji?.querySelector('[data-persona-history-focus="collapse"]');r&&(r.setAttribute("aria-label",_t?Ge.expandLabel:Ge.collapseLabel),r.setAttribute("aria-expanded",_t?"false":"true"))},Mm=()=>{Tp(!1);let r=it;if(!_t||!r){ia({invoker:zn});return}let a=document.activeElement===zn;_t=!1,Ul(),r.element.remove(),Rp(r.element),Am(),a&&ql(),wn(),Sr()},uS=()=>{Tp(!0),Sn()};kp=()=>{!ae||_t?Mm():uS()};let gS=()=>{let r=Pp(),a=vs({ariaLabel:Ge.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":yp,...r?{"aria-keyshortcuts":r.aria}:{}}}),d=a.button;d.addEventListener("mouseenter",()=>{ls=!0,ra(),!(wm()||Date.now()<Ip)&&xm()}),d.addEventListener("mouseleave",()=>{ls=!1,Ip=0,Sm()}),d.addEventListener("focus",()=>{ae||dS()}),d.addEventListener("click",f=>{xo()&&(f.detail!==0&&wm()&&!ae?xm():Mm())}),zn=d,jo=a.wrapper},sa=()=>{if(jo&&!jo.isConnected&&(jo=null,zn=null),!Qs()){jo?.remove(),jo=null,zn=null;return}zn||gS();let r=jo,a=zn;if(!r||!a)return;let d=Ks()!=="right"?Ae.firstChild:null;(d??Ae.lastChild)!==r&&Ae.insertBefore(r,d),r.style.display=cS()||Fl>0?"none":"",a.setAttribute("aria-label",Ge.expandLabel),a.setAttribute("aria-expanded",ae?"true":"false"),Vo&&Be()},Em=r=>{if(!_t)return;let a=r.target;a instanceof Node&&(Vo?.contains(a)||jo?.contains(a)||a instanceof Element&&a.closest('.persona-dropdown-menu,[role="alertdialog"]')||Sn({restoreFocus:!1}))};document.addEventListener("pointerdown",Em,!0),he.push(()=>{document.removeEventListener("pointerdown",Em,!0),document.removeEventListener("pointermove",Lp),Xs?.(),ra()});let Hp=null,Xs=null,Tm=16,km=r=>{rS(Mp(r)),Be(),wn()},fS=()=>{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(xp)),r.setAttribute("aria-valuemax",String(Ap)),r.addEventListener("pointerdown",a=>{let d=as;if(!d||a.button!==0)return;a.preventDefault(),Xs?.();let f=a.clientX,y=d.getBoundingClientRect().width||ta(),C=Ks()==="right"?-1:1,W=y,z=t.ownerDocument;d.style.transition="none";let q=Y=>{W=Mp(y+C*(Y.clientX-f)),d.style.flex=`0 0 ${W}px`,r.setAttribute("aria-valuenow",String(W))},j=()=>{Xs=null,z.removeEventListener("pointermove",q),z.removeEventListener("pointerup",j),z.removeEventListener("pointercancel",j),d.style.removeProperty("transition");try{r.releasePointerCapture(a.pointerId)}catch{}km(W)};Xs=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=Ks()==="right"?-Tm:Tm,f=ta(),y=a.key==="ArrowRight"?f+d:a.key==="ArrowLeft"?f-d:a.key==="Home"?xp:a.key==="End"?Ap:null;y!==null&&(a.preventDefault(),km(y))}),r},mS=(r,a)=>{if(!nS()||oa()){Xs?.(),Hp?.remove();return}let d=Hp??fS();Hp=d,d.setAttribute("aria-label",Ge.resizeLabel),d.setAttribute("aria-valuenow",String(ta())),d.nextElementSibling!==a&&r.insertBefore(d,a)};Be=()=>{it?.view.setRailSide(Ks());let r=Ks()==="right",a=Vo;if(a){let z=zn?zn.getBoundingClientRect().bottom-ue.getBoundingClientRect().top:0;a.style.top=`calc(${Math.max(0,Math.round(z))}px + ${Nl})`,a.style.width=`${ta()}px`,a.style.left=r?"":Nl,a.style.right=r?Nl:""}let d=as,f=js,y=Zi;if(!d||!f||!y)return;d.style.flex=`0 0 ${oa()?tS:ta()}px`;let C="1px solid var(--persona-divider,#e5e7eb)";d.style.borderRight=r?"":C,d.style.borderLeft=r?C:"";let W=r?y:d;f.firstElementChild!==W&&f.append(W,r?d:y),mS(f,r?d:y)};let Pm=r=>{if(Vs&&as){Vs.replaceWith(r),Vs=null,Be();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 f=k("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",ue.insertBefore(a,Ae.parentNode===ue?Ae:ne);for(let y of hm())y?.parentNode===ue&&d.appendChild(y);a.append(f,d),f.appendChild(r),js=a,as=f,Zi=d,Be()},hS=()=>{if(js)return;let r=k("div","persona-history-rail-placeholder");r.style.cssText="flex:1 1 auto;min-height:0",Vs=r,Pm(r),wn()},Im=()=>{Vs&&(Ul(),wn())},yS=r=>{let a=k("div","persona-history-rail-overlay");a.style.cssText=`position:absolute;bottom:${Nl};display:flex;overflow:hidden;z-index:${mc-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))`,ue.style.position="relative",ue.appendChild(a),a.appendChild(r),document.addEventListener("pointermove",Lp),Vo=a,Be(),Am()},Ul=()=>{_l?.(),Vo&&(ls&&(Ip=Date.now()+150),document.removeEventListener("pointermove",Lp),Vo.remove(),Vo=null);let r=js;if(r){Xs?.();for(let a of hm())a&&r.contains(a)&&ue.insertBefore(a,r);r.remove(),js=null,as=null,Zi=null,Vs=null}},Lm=r=>{Ji=r,r.id=yp,r.style.flex="1 1 auto",r.style.minHeight="0"},Rp=r=>{Lm(r),(de!=="rail"||_t)&&Im(),de!=="rail"?eS(r):_t?yS(r):Pm(r)},$l=()=>{if(sa(),$m(),!ae||!it)return;let r=Cp();if(r===de)return;let a=document.activeElement,d=a instanceof HTMLElement&&(it.element.contains(a)||Rn?.contains(a)===!0)?a:null;Ul(),it.element.remove(),it.view.setHeaderPlacement("inline"),de=r,it.view.setPresentation(r),it.view.setCollapsed(oa()),it.requestRender(),it.element.isConnected||Rp(it.element),d?.isConnected?d.focus():ql(),qt(),wn(),Sr()},Hm=(r,a)=>Rn?.querySelector(a)??r.querySelector(a),ql=()=>{let r=it?.element??Ji;if(!r)return;let a=Hm(r,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(a){a.focus();return}let d=Hm(r,".persona-history-title")??r;d.tabIndex=-1,d.focus()},ia=async r=>{if(!xo()||ae)return;let a=Hn;if(!a)return;if(!_t&&Qs()&&Ep()){sa();return}zl();let d=++Yi;Il=r?.returnSurface??"conversation",fp=r?.invoker??ln;let f=Qs()&&!_t;f&&(Fl+=1,sa(),hS());let y;try{y=await kg()}catch{Wl(Ge.openHistoryLabel),f&&(Fl-=1,d===Yi&&(Im(),sa()));return}if(f&&(Fl-=1),d!==Yi||ae)return;Pl={scope:vp()},de=Cp(),ae=!0;let C=de==="panel"&&o.layout?.showHeader!==!1&&Ae.style.display!=="none"?"external":"inline",W=o.features?.history?.rowAvatar,z=Pp(),q=z?{hint:z.hint,aria:z.aria}:null,j={provider:a,context:Pl,targetId:lm(),presentation:de,collapsible:Ol(),collapsed:oa(),railSide:Ks(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:sS(),onToggleCollapse:vm,...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:W===!1?!1:typeof W=="string"?W:o.launcher?.iconUrl,activeConversationId:T.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:Y=>Bp(Y,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Y=>cs(Y),attachTooltip:Yt,onStartNew:()=>_p({focusComposer:!0}),onClose:()=>Sn(),onRequestDeleteConversation:Y=>Um(Y),onRequestClearHistory:()=>xS(),...a.resetDevice?{onRequestResetIdentity:()=>AS()}:{}};it=fC({plugins:l,config:o,getPresentation:()=>de??"panel",getReturnSurface:()=>Il,close:()=>Sn(),createView:({slots:Y,renderDom:se,onModelChange:ge,railSections:Qe})=>(is=y.createHistoryView({...j,railSections:aS(Qe),slots:Y,renderDom:se,onModelChange:ge,onAnnounce:Wl}),is),onElementChanged:(Y,se)=>{if(!se?.isConnected)return Rp(Y);Lm(Y),se.replaceWith(Y),Sp()}}),it.view.setNewConversationRequired(Ll.recovery==="new_conversation_required"),r?.focus!==!1&&(de!=="rail"||r?.keyboard===!0)&&ql(),qt(),wn(),Sr(),w.emit("history:opened",{presentation:de,returnSurface:Il,timestamp:Date.now()})},zl=()=>{},Sn=r=>{if(!ae)return;Yi+=1;let a=Il,d=fp,f=it,y=r?.restoreFocus!==!1;ae=!1;let C=!1,W=null,z=()=>{if(!C){if(C=!0,zl=()=>{},W!==null&&clearTimeout(W),_t=!1,ra(),Ul(),f?.dispose(),f?.view.destroy(),f?.element.remove(),it===f&&(it=null,is=null,Ji=null,de=null,Pl=null,fp=null),qt(),wn(),Sr(),y){let j=d??ln;j?.isConnected?j.focus():ns()}w.emit("history:closed",{returnSurface:a,timestamp:Date.now()})}},q=f&&f.element===f.view.element?f.view.playExit():null;if(!q){z();return}zl=z,W=setTimeout(z,Kw),q.then(z)},Rm=r=>{if(!(r.key!=="Escape"||!ae||!it)){if(de==="rail"){let a=r.target;if(!(a instanceof Node)||!(it.element.contains(a)||_t&&jo?.contains(a)===!0))return}r.preventDefault(),r.stopPropagation(),Sn()}};ue.addEventListener("keydown",Rm),he.push(()=>ue.removeEventListener("keydown",Rm));let jl=null,Wm=!1,aa=()=>{if(!lr)return;let r=o.layout?.header?.titleSource==="conversation",a=r&&jl?.trim()||null;lr.textContent=a??o.launcher?.title??"Chat Assistant";let d=lr.closest(".persona-combo-btn");if(!d)return;let f=!r||T.getActiveConversationId()!==null;d.setAttribute("data-persona-menu-locked",f?"false":"true"),d.setAttribute("aria-haspopup",f?"true":"false"),f||d.setAttribute("aria-expanded","false"),d.style.cursor=f?"pointer":"default";let y=d.querySelector("svg");y&&(y.style.display=f?"":"none")},bS=r=>{r!==jl&&(jl=r,aa())},cs=r=>{Wm=r?.starred===!0,bS(r&&r.title.trim()||null),aa()};aa(),ue.addEventListener("persona:title-menu-builtin",r=>{let a=r.detail?.actionId,d=T.getActiveConversationId();d&&(a==="delete"?Um(d):a==="star"&&T.canUpdateConversations()&&Op(d,{starred:!Wm}).catch(()=>{}))});let Vl=0,vS=250,Kl=null,Gl=()=>{Kl&&clearTimeout(Kl),Kl=null};he.push(Gl);let Bm=()=>{Gl();let r=os;r&&(Qi=!0,r.hidden=!1,Te.style.display="none",Xi())},Ql=()=>{Vl+=1,Gl(),os&&(os.remove(),os=null,Qi=!1,Te.style.removeProperty("display"),qn(He,!1),Xi())},CS=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Te.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Wp=(r,a)=>X("div",{className:Bn("persona-conversation-loading-bubble",a&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:r}}),_m=()=>X("div",{className:"persona-conversation-loading-body"},Wp("58%",!1),Wp("72%",!0),Wp("44%",!1)),Om=r=>{os?.remove(),os=r,r.hidden=!Qi,ne.insertBefore(r,Te),Gl(),Qi||(Kl=setTimeout(Bm,vS)),qn(He,!0)},wS=()=>{let r={config:o,streaming:!1,location:"conversation-open",defaultRenderer:_m},a=null,d=l.find(f=>f.renderLoadingIndicator);d?.renderLoadingIndicator&&(a=d.renderLoadingIndicator(r)),a===null&&o.loadingIndicator?.render&&(a=o.loadingIndicator.render(r)),Om(X("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ge.openConversationLoadingLabel}},a??_m()))},SS=r=>{let a=()=>{Bp(r,{focusComposer:!0}).catch(()=>{})},d=xo()?()=>{Ql(),ia()}:void 0,f=(z,q)=>{let j=X("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:z});return j.addEventListener("click",q),j},y=()=>X("div",{className:"persona-conversation-loading-error-body"},X("p",{className:"persona-conversation-loading-error-title",text:Ge.openConversationErrorTitle}),X("div",{className:"persona-conversation-loading-error-actions"},f(Ge.openConversationRetryLabel,a),d?f(Ge.openConversationBackLabel,d):null)),C=Object.freeze({conversationId:r,config:o,copy:Object.freeze({title:Ge.openConversationErrorTitle,retryLabel:Ge.openConversationRetryLabel,backLabel:Ge.openConversationBackLabel}),retry:a,...d?{back:d}:{},defaultRenderer:y}),W=null;for(let z of l)if(z.renderHistoryOpenError){try{W=z.renderHistoryOpenError(C)}catch(q){console.warn("[persona] renderHistoryOpenError threw",q),W=null}if(W)break}Om(X("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},W??y())),Bm()};w.on("history:closed",()=>{os&&qn(He,!0)});let Bp=async(r,{focusComposer:a=!1}={})=>{let d=zs(),f=!!it;it?.view.setActiveConversationId(r),Ql();let y=Vl;wS(),ae&&(de==="panel"||_t)&&Sn({restoreFocus:!1}),Bs=!0;try{await T.openConversation(r,{scope:d})}catch(C){throw y===Vl&&SS(r),C}finally{Bs=!1}y===Vl&&(Ql(),Bt.clear(),so(),Cn(),Qd()||vl(),CS(),Ko(),f||cs(null),w.emit("history:conversationOpened",{conversationId:r,title:jl,scope:d,timestamp:Date.now()}),a&&ns())},_p=async({focusComposer:r=!1}={})=>{Ql(),await T.startNewConversation({scope:zs()}),cs(null),Bt.clear(),so(),Cn(),vl(),Ko();let a=T.getActiveConversationId();it?.view.setActiveConversationId(a),w.emit("history:conversationStarted",{conversationId:a,timestamp:Date.now()}),ae&&(de==="panel"||_t)&&Sn({restoreFocus:!1}),r&&ns()},Op=async(r,a)=>{let d=await T.updateConversation(r,{...a,...a.title!==void 0?{title:a.title.trim()}:{}});return it?.view.applyConversationSummary(d),!it&&r===T.getActiveConversationId()&&cs(d),d},Dm=async r=>{let a=zs(),d=T.getActiveConversationId()===r;await T.deleteConversation(r,{scope:a}),it?.view.removeConversationSummary(r),d&&(cs(null),Bt.clear(),so(),Cn(),Ko()),w.emit("history:conversationDeleted",{conversationId:r,scope:a,wasActive:d,timestamp:Date.now()})},Nm=async r=>{let a=r?.scope??zs(),d=r?.allTargets?null:r?.targetId??lm(),f=await T.clearConversationHistory({...d?{targetId:d}:{},scope:a});return cs(null),Bt.clear(),so(),Cn(),Ko(),w.emit("history:cleared",{deleted:f.deleted,scope:a,targetId:d,timestamp:Date.now()}),f},Fm=async()=>{if(!Hn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let r=!1;try{r=(await T.resetHistoryDevice()).remoteRevocationConfirmed}finally{cs(null),T.clearArtifacts(),Bt.clear(),cp=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),ee={},Le.syncFromMetadata(),G?.clear&&hl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),so(),Cn(),Ko(),Sn({restoreFocus:!1}),ns(),ye||Mt?.launcher.element.focus()}return Wl(r?Ge.identityResetNotice:Ge.identityResetUnconfirmedNotice),w.emit("history:identityReset",{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},Dp=()=>vo?Se:ue,Um=async r=>await bd({host:Dp(),title:Ge.deleteConversationConfirmTitle,description:Ge.deleteConversationConfirm,confirmLabel:Ge.deleteConversationConfirmLabel,cancelLabel:Ge.confirmCancelLabel})?(await Dm(r),"deleted"):"cancelled",xS=async()=>{let r=zs()==="verified-user";return await bd({host:Dp(),title:Ge.clearHistoryConfirmTitle,description:r?Ge.clearHistoryVerifiedConfirm:Ge.clearHistoryConfirm,confirmLabel:Ge.clearHistoryConfirmLabel,cancelLabel:Ge.confirmCancelLabel})?(await Nm(),"cleared"):"cancelled"},AS=async()=>{if(!await bd({host:Dp(),title:Ge.resetIdentityConfirmTitle,description:Ge.resetIdentityConfirm,confirmLabel:Ge.resetIdentityConfirmLabel,cancelLabel:Ge.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:a}=await Fm();return{outcome:"reset",remoteRevocationConfirmed:a}},jn=k("button","persona-history-earlier");jn.type="button",jn.textContent=Ge.showEarlierMessagesLabel,jn.setAttribute("data-persona-history-earlier",""),Object.assign(jn.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 Ko=()=>{if(!(xo()&&!!Ll.nextMessageCursor&&!!T.getActiveConversationId())){jn.remove();return}jn.textContent=Ge.showEarlierMessagesLabel,jn.parentNode!==ne&&ne.insertBefore(jn,ne.firstChild)};jn.addEventListener("click",()=>{let r=T.getActiveConversationId(),a=Ll.nextMessageCursor;if(!r||!a||jn.disabled)return;jn.disabled=!0;let d=ne.scrollHeight,f=ne.scrollTop;T.loadOlderMessages(r,a,{scope:zs()}).then(()=>{ne.scrollTop=f+(ne.scrollHeight-d),wn()}).catch(()=>{}).finally(()=>{jn.disabled=!1,Ko()})});let MS=()=>{let r=vs({ariaLabel:Ge.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(!(!xo()||am())){if(ae){Sn();return}ia({invoker:r.button,keyboard:a.detail===0})}}),r},$m=()=>{if(!xo()){So?.remove(),ln=null,So=null;return}if(So&&!So.isConnected&&(ln=null,So=null),!ln&&Ae){let f=MS();ln=f.button,So=f.wrapper;let y=Oe.clearChatButtonWrapper||Oe.closeButtonWrapper;y?.parentNode&&Ae.contains(y)?y.parentNode.insertBefore(So,y):Ae.appendChild(So)}if(!ln||!So)return;let r=Qs()||ae&&de==="rail";if(So.style.display=r?"none":"",r){document.activeElement===ln&&ql();return}let a=am();ln.disabled=a,ln.setAttribute("aria-disabled",a?"true":"false");let d=a?Ge.openHistoryBusyLabel:Ge.openHistoryLabel;ln.setAttribute("aria-label",d),(o.features?.history?.presentation??"panel")==="panel"?(ln.removeAttribute("aria-expanded"),ln.removeAttribute("aria-controls")):(ln.setAttribute("aria-expanded",ae?"true":"false"),ln.setAttribute("aria-controls",yp))},Xl=!1,ES=()=>{let r=Oe.clearChatButton;if(r){if(xo()){Xl||(hp=r.getAttribute("aria-label")??"",Xl=!0),r.setAttribute("aria-label",Ge.newConversationLabel),r.removeAttribute("title");return}Xl&&(Xl=!1,hp&&r.setAttribute("aria-label",hp))}},Sr=()=>{Ge=ru(o.features?.history?.copy),$m(),sa(),ES(),Ko()};Ro=Sr,Lt=r=>{Ll=r,it?.view.setNewConversationRequired(r.recovery==="new_conversation_required"),Gi(r.sendBlocked||Pn),Ko()},xt=r=>{(r.code==="history_continuity_reset"||r.code==="conversation_deleted_recovered")&&(Bt.clear(),so(),Cn()),Wl(r.message),it?.view.refresh()},um(),Sr(),he.push(()=>{Hl?.(),Rl?.(),Yi+=1,zl(),it?.dispose(),it?.view.destroy(),it=null}),o.clientToken&&T.initClientSession().then(()=>{if(xo())return T.reconcileBootConversation({scope:vp()})}).then(()=>{Ko()}).catch(r=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",r)}),(nn||o.onSSEEvent)&&T.setSSEEventCallback((r,a)=>{o.onSSEEvent?.(r,a),te(r,a)});let qm=()=>{let r=o.resume??(le?qo.getStoredResumableHandle?.():null);r&&typeof o.reconnectStream=="function"&&T.resumeFromHandle(r)};S?S.then(r=>{if(r){if(r.metadata&&(ee=Hg(r.metadata),Le.syncFromMetadata()),r.messages?.length){Bs=!0;try{T.hydrateMessages(r.messages)}finally{Bs=!1}xl()}r.artifacts?.length&&T.hydrateArtifacts(r.artifacts,r.selectedArtifactId??null),Nf(r.draft)}}).catch(r=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",r)}).finally(()=>{tp=!0,B(),qm()}):(Nf(I),qm());let TS=()=>{!Re()||ye||!(o.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},kS=(r,a)=>r?a?{refs:[...r.refs,...a.refs],finalize:async()=>{let[d,f]=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),f.status==="fulfilled"?y.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),xT(y)}}:r:a,Np=()=>{let a=pe.getInlineMessageFields?.();return a&&a.contentSegments.some(f=>f.kind==="mention")?a.contentSegments:void 0},Go=!1,ds=null,Yl=()=>{pe.value="",pe.style.height="auto",ho(),ca()},Fp="data-persona-composer-notice",Ys=null;function PS(r){Ya(r),!(Re()||!st)&&(st.hasAttribute(Ti)||(st.setAttribute(Fp,""),st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.textContent=r,Ys&&clearTimeout(Ys),Ys=setTimeout(()=>{if(Ys=null,!!st?.hasAttribute(Fp)&&(st.removeAttribute(Fp),st.removeAttribute("role"),st.removeAttribute("aria-live"),g)){let a=T.getStatus();Ga(st,mn(a),o.statusIndicator??{},a)}},4e3)))}function IS(){let r=Ce.getState().pendingSubmission;r&&(Ts(void 0),pe&&(pe.value=r.text,pe.dispatchEvent(new Event("input",{bubbles:!0})),ho()),r.options.selectedModelId&&(Ce.setSelectedModelId(r.options.selectedModelId),dr?.repaint()),r.options.activeModeIds?.length&&tl(r.options.activeModeIds),r.options.quote&&yo(r.options.quote),pe?.focus())}let LS=r=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",r)},zm=(r={})=>{let a=(r.overrideText??pe?.value??"").trim();return r.resolveInlineCommand&&a?(Ht?.takeInlineCommand(a)??Promise.resolve(null)).then(d=>jm(r,a,d)):jm(r,a,null)},jm=(r,a,d)=>{if(d?.kind==="action"){Yl(),Ht?.clear(),Nr();return}let f=d?.kind==="server"?d.mentions:null,y=d?.kind==="prompt"?d.sendText:a,C=r.pending?.contentParts,W=(Xe?.hasAttachments()??!1)||(C?.length??0)>0;if(!jb({text:y,hasAttachments:W,attachmentsReady:Xe?.isReady()??!0,hasMentions:Ht?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:vr(),sendDisabled:ts()}))return;let z=T.isStreaming()?Pd():"block";if(z==="defer-one"&&!r.pending){if(Ce.getState().pendingSubmission){PS("One message is already queued. Edit or remove it first.");return}HS({intent:r,sendText:y,serverMentions:f});return}let q={text:y,mentionRefs:[...Ht?.getMentionRefs()??[],...f?.refs??[]],contentSegments:d?.kind==="prompt"?void 0:Np(),options:{...Ce.getState().selectedModelId&&{selectedModelId:Ce.getState().selectedModelId},...Ce.getState().activeModeIds.length>0&&{activeModeIds:[...Ce.getState().activeModeIds]},...Ce.getState().quote&&{quote:{...Ce.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 ut=[...Xe.getContentParts()];return q.text&&ut.push(ko(q.text)),ut};q.contentParts=j();let Y=()=>{Gr(),TS();let ut=Ht?.collectForSubmit()??null,Kt=kS(ut,f),Ot=j();r.consumeDraft!==!1&&Yl();let Tt={selectedModelId:q.options.selectedModelId,activeModeIds:q.options.activeModeIds},on=z==="interrupt";on&&T.cancel(),T.sendMessage(q.text,{contentParts:Ot,mentions:Kt??void 0,contentSegments:q.contentSegments,viaVoice:q.viaVoice,composerOptions:Tt,...q.options.quote&&{quote:q.options.quote},...on&&{interrupt:!0}}),Xe?.hasAttachments()&&Xe.clearAttachments(),ut&&Ht?.clear(),Nr();let Ye=Ce.getState().activeModeIds,rn=Hb(Ye,o.composer?.modes);rn.length!==Ye.length&&tl(rn),Ce.getState().quote&&yo(void 0),bl(),Wd.release(),to()},se=o.composer?.onBeforeSend;if(!se){Y();return}let ge=new AbortController;ds=ge;let Qe=ut=>{if(ds=null,ut.status==="error"){LS(ut.error);return}ut.status==="proceed"&&Y()},ct=Vb(se,q,ge.signal);if(!(ct instanceof Promise)){Qe(ct);return}return Ce.setPreparing(!0),ct.then(Qe).finally(()=>Ce.setPreparing(!1))};function HS(r){let a=Ce.getState(),d=Xe?.hasAttachments()??!1,f=d?[...Xe.getContentParts()]:[];d&&r.sendText&&f.push(ko(r.sendText));let y=Nu({text:r.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Ht?.getMentionRefs()??[],...r.serverMentions?.refs??[]],contentSegments:Np(),options:{...a.selectedModelId&&{selectedModelId:a.selectedModelId},...a.activeModeIds.length>0&&{activeModeIds:[...a.activeModeIds]},...a.quote&&{quote:{...a.quote}}},viaVoice:r.intent.viaVoice});Ts(y),r.intent.consumeDraft!==!1&&Yl(),d&&Xe.clearAttachments(),Ht?.clear(),Nr(),a.quote&&yo(void 0),bl(),Wd.release(),to(),Ya("Message queued. It sends when the response finishes.")}function RS(){let r=Ce.getState().pendingSubmission;r&&(Ts(void 0),Zl(r.text,{consumeDraft:!1,pending:r}))}function WS(r){if(o.messageActions?.showEdit!==!0)return;let a=T.getMessages().find(d=>d.id===r);!a||!yu(a)||Kr!==r&&(Gr(),Kr=r,fr=Ob({messageId:r,initialText:a.content,onSave:d=>BS(r,d),onCancel:()=>Gr()}),Bt.delete(r),$n(Te,T.getMessages(),It),fr.focus())}function BS(r,a){let d=fr;if(Kr=null,fr=null,d?.destroy(),Bt.delete(r),!T.resubmitFrom(r,{reason:"edit",replacement:{text:a,mentionRefs:[],options:{}}})){$n(Te,T.getMessages(),It);return}wn()}function _S(r){if(T.isStreaming())return;let a=hu(T.getMessages(),r);a&&(Gr(),T.resubmitFrom(a,{reason:"retry"})&&wn())}nl={regenerate:_S,edit:WS,quote:r=>{let d=T.getMessages().find(f=>f.id===r)?.content?.trim();d&&(yo({text:d,messageId:r}),pe?.focus())}};let la=async r=>{if(!Go){Go=!0;try{await zm({resolveInlineCommand:!0,...r})}finally{Go=!1}}};function Jl(r){ts()||(Yl(),Zl(r,{consumeDraft:!1}))}let Zl=(r,a)=>{if(Go)return;Go=!0;let d=()=>{Go=!1};try{let f=zm({...a,overrideText:r});f instanceof Promise?f.finally(d):d()}catch(f){throw d(),f}},OS=r=>{if(r.preventDefault(),T.isStreaming()){T.cancel(),An?.reset(),Q?.update();return}Go||la()},DS=()=>o.features?.composerHistory!==!1,Up={...ju},$p=!1,ca=()=>{Up={...ju}},NS=()=>T.getMessages().filter(r=>r.role==="user").map(r=>r.content??"").filter(r=>r.length>0),FS=r=>{if(!pe)return;$p=!0,pe.value=r,pe.dispatchEvent(new Event("input",{bubbles:!0})),$p=!1;let a=pe.value.length;pe.setSelectionRange(a,a)},US=r=>{$p||(r.isComposing||Ht?.handleInput(r.inputType??void 0),ca())},$S=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:La(pe)}),qS=r=>{if(pe&&!vr()&&!(!r.isComposing&&Ht?.handleKeydown(r))){if(DS()&&(r.key==="ArrowUp"||r.key==="ArrowDown")&&!r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.isComposing){let a=pe.selectionStart===0&&pe.selectionEnd===0,d=av({direction:r.key==="ArrowUp"?"up":"down",history:NS(),currentValue:pe.value,atStart:a,state:Up});if(Up=d.state,d.handled){r.preventDefault(),d.value!==void 0&&FS(d.value);return}}if(hb(r,$S())){if(T.isStreaming()){if(r.preventDefault(),Pd()==="block"||Go||ts())return;ca(),la();return}if(Go){r.preventDefault();return}if(ts()){r.preventDefault();return}ca(),r.preventDefault(),xe.click()}}},Vm=r=>{if(!(r.key!=="Escape"||r.isComposing)&&r.composedPath().includes(ue)){if(ds){ds.abort(),ds=null,r.preventDefault(),r.stopImmediatePropagation();return}T.isStreaming()&&(T.cancel(),An?.reset(),Q?.update(),ca(),r.preventDefault(),r.stopImmediatePropagation())}},zS=async r=>{if(o.attachments?.enabled!==!0||!Xe||vr())return;let a=vT(r.clipboardData);a.length!==0&&(r.preventDefault(),await Xe.handleFiles(a))},Vn=null,Ao=!1,Js=null,vt=null,qp=()=>o.voiceRecognition?.completionBehavior==="review";function ps(r){oe?.setAttribute("data-state",r),r==="recording"?VS():Kp()}let Km="--persona-voice-level",zp=.5,Zs=null,jp=-1,ec=0,Gm=()=>{let r=[],a=Tn??oe?.parentElement??null;return a&&r.push(a),He&&r.push(He),r},Vp=r=>{let a=Math.round(Math.max(0,Math.min(1,r))*100)/100;if(a!==jp){jp=a;for(let d of Gm())d.style.setProperty(Km,String(a))}},jS=()=>{jp=-1,ec=0;for(let r of Gm())r.style.removeProperty(Km)};function VS(){if(Zs!==null)return;if(typeof requestAnimationFrame!="function"){Vp(g?T.getVoiceLevel()??zp:zp);return}let r=()=>{Zs=requestAnimationFrame(r);let a=g?T.getVoiceLevel():null;if(a===null){Vp(zp);return}ec+=(a-ec)*.3,Vp(ec)};Zs=requestAnimationFrame(r)}function Kp(){Zs!==null&&(cancelAnimationFrame(Zs),Zs=null),jS()}let Qm=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,tc=(r="user")=>{if(Ao||T.isStreaming())return;let a=Qm();if(!a)return;Vn=new a;let d=o.voiceRecognition??{},f=d.pauseDuration??2e3;Vn.continuous=d.provider?.browser?.continuous??!0,Vn.interimResults=!0,Vn.lang=d.provider?.browser?.language??"en-US";let y=pe.value;Vn.onresult=C=>{let W="",z="";for(let j=0;j<C.results.length;j++){let Y=C.results[j],se=Y[0].transcript;Y.isFinal?W+=se+" ":z=se}let q=y+W+z;pe.value=q,ho(),Js&&clearTimeout(Js),(W||z)&&(Js=window.setTimeout(()=>{if(pe.value.trim()&&Vn&&Ao){if(xr(),qp())return;la({viaVoice:!0})}},f))},Vn.onerror=C=>{C.error!=="no-speech"&&xr()},Vn.onend=()=>{if(Ao){let C=pe.value.trim();!qp()&&C&&C!==y.trim()&&la({viaVoice:!0}),xr()}};try{if(Vn.start(),Ao=!0,ze.active=!0,r!=="system"&&(ze.manuallyDeactivated=!1),Fo(r),ro(),to(),oe){let C=o.voiceRecognition??{};vt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:C.iconName??"mic",iconSize:parseFloat(C.iconSize??"")||dn};let W=C.recordingBackgroundColor,z=C.recordingIconColor,q=C.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),ps("recording"),oe.style.backgroundColor=W??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let j=oe.querySelector("svg");j&&j.setAttribute("stroke",z)}q&&(oe.style.borderColor=q),oe.setAttribute("aria-label","Stop voice recognition")}}catch{xr("system")}},xr=(r="user")=>{if(Ao){if(Ao=!1,Js&&(clearTimeout(Js),Js=null),Vn){try{Vn.stop()}catch{}Vn=null}if(ze.active=!1,Fo(r),ro(),to(),oe){if(oe.classList.remove("persona-voice-recording"),ps("idle"),vt){oe.style.backgroundColor=vt.backgroundColor,oe.style.color=vt.color,oe.style.borderColor=vt.borderColor;let a=oe.querySelector("svg");a&&a.setAttribute("stroke",vt.color||"currentColor"),vt=null}oe.setAttribute("aria-label","Start voice recognition")}}},Gp=()=>{if(!oe||vt)return;let r=o.voiceRecognition??{};vt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:r.iconName??"mic",iconSize:parseFloat(r.iconSize??"")||dn}},Qp=(r,a)=>{if(!oe)return;let d=oe.querySelector("svg");d&&d.remove();let f=vt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||dn),y=me(r,f,a,1.5);y&&oe.appendChild(y)},nc=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ei=()=>{if(!oe)return;Gp();let r=o.voiceRecognition??{},a=r.recordingBackgroundColor,d=r.recordingIconColor,f=r.recordingBorderColor;if(nc(),oe.classList.add("persona-voice-recording"),ps("recording"),oe.style.backgroundColor=a??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=d??"var(--persona-voice-recording-indicator, #ffffff)",d){let y=oe.querySelector("svg");y&&y.setAttribute("stroke",d)}f&&(oe.style.borderColor=f),oe.setAttribute("aria-label","Stop voice recognition")},KS=()=>{if(!oe)return;Gp();let r=o.voiceRecognition??{},a=T.getVoiceInterruptionMode(),d=r.processingIconName??"loader",f=r.processingIconColor??vt?.color??"",y=r.processingBackgroundColor??vt?.backgroundColor??"",C=r.processingBorderColor??vt?.borderColor??"";nc(),oe.classList.add("persona-voice-processing"),ps("processing"),oe.style.backgroundColor=y,oe.style.borderColor=C;let W=f||"currentColor";oe.style.color=W,Qp(d,W),oe.setAttribute("aria-label","Processing voice input"),a==="none"&&(oe.style.cursor="default")},GS=()=>{if(!oe)return;Gp();let r=o.voiceRecognition??{},a=T.getVoiceInterruptionMode(),d=a==="cancel"?"square":a==="barge-in"?"mic":"volume-2",f=r.speakingIconName??d,y=r.speakingIconColor??(a==="barge-in"?r.recordingIconColor??vt?.color??"":vt?.color??""),C=r.speakingBackgroundColor??(a==="barge-in"?r.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),W=r.speakingBorderColor??(a==="barge-in"?r.recordingBorderColor??"":vt?.borderColor??"");nc(),oe.classList.add("persona-voice-speaking"),ps("speaking"),oe.style.backgroundColor=C,oe.style.borderColor=W;let z=y||"currentColor";oe.style.color=z,Qp(f,z);let q=a==="cancel"?"Stop playback and re-record":a==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",q),a==="none"&&(oe.style.cursor="default"),a==="barge-in"&&oe.classList.add("persona-voice-recording")},Qo=()=>{oe&&(nc(),ps("idle"),vt&&(oe.style.backgroundColor=vt.backgroundColor??"",oe.style.color=vt.color??"",oe.style.borderColor=vt.borderColor??"",Qp(vt.iconName,vt.color||"currentColor"),vt=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},Xp=()=>{if(!vr()){if(o.voiceRecognition?.provider?.type==="runtype"){let r=T.getVoiceStatus(),a=T.getVoiceInterruptionMode();if(a==="none"&&(r==="processing"||r==="speaking"))return;if(a==="cancel"&&(r==="processing"||r==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,ro(),Fo("user"),Qo()});return}T.toggleVoice().then(()=>{ze.active=T.isVoiceActive(),ze.manuallyDeactivated=!T.isVoiceActive(),ro(),Fo("user"),T.isVoiceActive()?ei():Qo()});return}if(Ao){let r=pe.value.trim();ze.manuallyDeactivated=!0,ro(),xr("user"),r&&!qp()&&la()}else ze.manuallyDeactivated=!1,ro(),tc("user")}};Id=Xp,oe&&he.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),Qo()):xr("system")});let QS=w.on("assistant:complete",()=>{Ce.getState().pendingSubmission&&setTimeout(()=>{T.isStreaming()||RS()},0)});he.push(QS);let XS=w.on("assistant:complete",()=>{_f&&(ze.active||ze.manuallyDeactivated||_f==="assistant"&&!ze.lastUserMessageWasVoice||setTimeout(()=>{!ze.active&&!ze.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?T.toggleVoice().then(()=>{ze.active=T.isVoiceActive(),Fo("auto"),T.isVoiceActive()&&ei()}):tc("auto"))},600))});he.push(XS);let YS=w.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});he.push(YS);let Xm=()=>{pt(!ye,"user")},Mt=null,cn=null;if(be&&!Re()){let{instance:r,element:a}=dg({config:o,plugins:l,onToggle:Xm});Mt=r,r||(cn=a)}Mt?t.appendChild(Mt.element):cn&&t.appendChild(cn),Ki(),Rs(),El(),ip(),Gi(T.isStreaming()),Qd()||(kn()==="follow"?yr(!0):vl()),hw(),ve&&(!be||Re()?setTimeout(()=>ns(),0):ye&&setTimeout(()=>ns(),200));let us=null,Ym=()=>{us&&(us.disconnect(),us.observe(He),us.observe(ue))},da=()=>{if(Re()){Dr(),Ki();return}let r=Rt(o),a=o.launcher?.sidebarMode??!1,d=t.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640,C=d.innerWidth<=y,W=f&&C&&be;try{if(W){Fr(),Oi=dl();return}let z=!1;yt&&(yt=!1,Fr(),z=!0);let q=dl();if(!z&&q!==Oi&&(Fr(),z=!0),Oi=q,z&&il(),!be&&!r){Se.style.height="",Se.style.width="";return}if(!a&&!r){let Y=o?.launcher?.width??o?.launcherWidth??tr;Se.style.width=Y,Se.style.maxWidth=Y}cl(),Cf()}finally{if(Dr(),el(),Ki(),ye&&be){let q=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),j=o.launcher?.sidebarMode??!1,Y=o.launcher?.mobileFullscreen??!0,se=Rt(o)&&Y&&q,ge=j||Y&&q&&be||se;if(ge&&!wo){let Qe=t.getRootNode(),ct=Qe instanceof ShadowRoot?Qe.host:t.closest(".persona-host");ct&&!Co&&(Co=Vu(ct,o.launcher?.zIndex??an)),wo=Ku(t.ownerDocument)}else ge||(Co?.(),Co=null,wo?.(),wo=null)}}};da();let oc=t.ownerDocument.defaultView??window;if(oc.addEventListener("resize",da),he.push(()=>oc.removeEventListener("resize",da)),typeof ResizeObserver<"u"){us=new ResizeObserver(()=>{el()}),Ym(),he.push(()=>{us?.disconnect(),us=null});let r=new ResizeObserver(()=>{$l()});r.observe(ue),he.push(()=>r.disconnect())}oc.addEventListener("resize",$l),he.push(()=>oc.removeEventListener("resize",$l)),Ln=ne.scrollTop;let Jm=Jo(ne),Zm=()=>{let r=ne.scrollTop,a=Jo(ne),d=a<Jm;if(Jm=a,!cr()){Ln=r,qt();return}let{action:f,nextLastScrollTop:y}=Vh({following:In.isFollowing(),currentScrollTop:r,lastScrollTop:Ln,nearBottom:hs(ne,Do),userScrollThreshold:uw,isAutoScrolling:vn||ul||d,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Ln=y,f==="resume"){Cl()||Cn();return}f==="pause"&&$i()};if(ne.addEventListener("scroll",Zm,{passive:!0}),he.push(()=>ne.removeEventListener("scroll",Zm)),typeof ResizeObserver<"u"){let r=new ResizeObserver(()=>{xw(),su(Te)});r.observe(Te),r.observe(ne),he.push(()=>r.disconnect())}let eh=()=>{cr()&&In.isFollowing()&&Cl()&&$i()},th=ne.ownerDocument;th.addEventListener("selectionchange",eh),he.push(()=>{th.removeEventListener("selectionchange",eh)});let JS=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),nh=r=>{JS.has(r.key)&&(Jr(),Fg()&&cr()&&In.isFollowing()&&$i())},oh=r=>{r.target?.closest("a, button, [tabindex], input, textarea, select")&&(Jr(),Fg()&&cr()&&In.isFollowing()&&$i())};ne.addEventListener("keydown",nh),ne.addEventListener("focusin",oh),he.push(()=>{ne.removeEventListener("keydown",nh),ne.removeEventListener("focusin",oh)});let rh=r=>{if(r.deltaY!==0&&Jr(),!cr())return;let a=Kh({following:In.isFollowing(),deltaY:r.deltaY,nearBottom:hs(ne,Do),resumeWhenNearBottom:!0});a==="pause"?$i():a==="resume"&&!Cl()&&Cn()};ne.addEventListener("wheel",rh,{passive:!0}),ne.addEventListener("touchmove",Jr,{passive:!0}),ne.addEventListener("pointerdown",Jr,{passive:!0}),he.push(()=>{ne.removeEventListener("touchmove",Jr),ne.removeEventListener("pointerdown",Jr)}),he.push(()=>ne.removeEventListener("wheel",rh)),Wt.addEventListener("click",()=>{so(),ne.scrollTop=ne.scrollHeight,Ln=ne.scrollTop,Cn(),yr(!0),qt()}),he.push(()=>Wt.remove()),he.push(()=>{Uf(),so()});let sh=()=>{Ue&&(zr&&(Ue.removeEventListener("click",zr),zr=null),Pe()?(Ue.style.display="",zr=()=>{pt(!1,"user")},Ue.addEventListener("click",zr)):Ue.style.display="none")};sh(),(()=>{let{clearChatButton:r}=Oe;r&&r.addEventListener("click",()=>{if(xo()){_p({focusComposer:!0}).catch(d=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",d)});return}T.clearMessages(),Bt.clear(),Cn(),pi(Oe.composerOverlay);try{localStorage.removeItem(Ei),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ei}`)}catch(d){console.error("[AgentWidget] Failed to clear default localStorage:",d)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ei)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&&hl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ee={},Le.syncFromMetadata(),Xe?.clearAttachments(),bl(),Ts(void 0),yo(void 0),Gr(),Ze?.clear(),An?.reset(),Q?.update()})})();let ih=[["keydown",qS],["input",US],["input",ho],["input",Nr],["keyup",Nr],["paste",zS],["focus",ew]],ah=r=>{if(r)for(let[a,d]of ih)tt?.addListener(r,a,d)},ZS=r=>{if(r)for(let[a,d]of ih)tt?.removeListener(r,a,d)},lh=()=>{tt&&(tt.addListener(tt.form,"submit",OS),tt.addListener(tt.footer,"click",Nr),ah(pe),oe&&tt.addListener(oe,"click",Xp))};lh();let ch=()=>{Ht?.onComposerSwap((r,a)=>{ZS(a),pe=r,tt&&(tt.input=r),ah(r),Hd(),Zd(),ho()})};ch();let Yp=!1;function dh(){if(!Yp){Yp=!0;try{let r=pe?.value??"",a=He.ownerDocument??document,d=pe?a.activeElement===pe:!1;Kp(),tt?.destroy(),tt=null,Ht?.destroy(),Ht=null;let f=null,y=()=>(f=Re()?od({config:o}):Ua({config:o}),f.footer),C=Xg(y)??y();Mn.replaceComposer(C),He=Mn.composer.footer;let W=f!==null&&C===f.footer;Ps=!W,Ng=W?f.setSendButtonMode:()=>{},Qg(He),Jg(He),Zg(),ef(),tf(),ch(),nf(),Rd(),of(),lh();let z=qr.indexOf(Oo);Oo.destroy(),Oo=Na(ar),z>=0&&(qr[z]=Oo),pe&&(pe.value=r),ho(),Nr(),El(),Rs(),Gi(T.isStreaming()),ze.active&&ps("recording"),Fr(),Ym(),Dr(),to(),Al(),d&&pe?.focus()}finally{Yp=!1}}}let pa=t.ownerDocument??document;pa.addEventListener("keydown",Vm,!0);let ph=()=>{jd()},uh=()=>{pa.visibilityState==="hidden"&&jd()};typeof window<"u"&&(window.addEventListener("pagehide",ph),pa.addEventListener("visibilitychange",uh),he.push(()=>{window.removeEventListener("pagehide",ph),pa.removeEventListener("visibilitychange",uh)}));let gh="persona-attachment-drop-active",ua=0,Jp=()=>{ua=0,ue.classList.remove(gh)},ti=()=>o.attachments?.enabled===!0&&Xe!==null&&!vr(),fh=r=>{!vd(r.dataTransfer)||!ti()||(ua++,ua===1&&ue.classList.add(gh))},mh=r=>{!vd(r.dataTransfer)||!ti()||(ua--,ua<=0&&Jp())},hh=r=>{!vd(r.dataTransfer)||!ti()||(r.preventDefault(),r.dataTransfer.dropEffect="copy")},yh=r=>{if(!vd(r.dataTransfer)||!ti())return;r.preventDefault(),r.stopPropagation(),Jp();let a=Array.from(r.dataTransfer.files??[]);a.length!==0&&Xe.handleFiles(a)},Ar=!0;ue.addEventListener("dragenter",fh,Ar),ue.addEventListener("dragleave",mh,Ar),t.addEventListener("dragover",hh,Ar),t.addEventListener("drop",yh,Ar);let rc=t.ownerDocument,bh=r=>{ti()&&r.preventDefault()},vh=r=>{ti()&&r.preventDefault()};rc.addEventListener("dragover",bh),rc.addEventListener("drop",vh),he.push(()=>{tt?.destroy(),tt=null,Kp(),bo?.destroy(),bo=null,Bo?.destroy(),Bo=null,pr?.destroy(),pr=null,ur?.destroy(),ur=null,dr=null,kd=null,jd(),Ui.destroy(),Ys&&clearTimeout(Ys),Gr(),ds?.abort(),ds=null,Xe?.destroy(),Xe=null,Ce.destroy(),pa.removeEventListener("keydown",Vm,!0),Ht?.destroy()}),he.push(()=>{ue.removeEventListener("dragenter",fh,Ar),ue.removeEventListener("dragleave",mh,Ar),t.removeEventListener("dragover",hh,Ar),t.removeEventListener("drop",yh,Ar),rc.removeEventListener("dragover",bh),rc.removeEventListener("drop",vh),Jp()}),he.push(()=>{T.cancel()}),Mt?he.push(()=>{Mt?.destroy()}):cn&&he.push(()=>{cn?.remove()});let Et={update(r){let a=o.toolCall,d=o.messageActions,f=o.layout?.messages,y=o.colorScheme,C=o.loadingIndicator,W=o.iterationDisplay,z=o.features?.showReasoning,q=o.features?.showToolCalls,j=o.features?.toolCallDisplay,Y=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type,ge=o.features?.history?.enabled===!0,Qe=o.features?.history?.provider,ct=o.getIdentityProof,ut=o.clientToken,Kt=o.contextMentions;o=iC({...o,features:i},r),i=o.features,o=wg(o),s(),Nd(),Ra(t,o),za(t,o),ja(t,o),Be(),oo(),o.colorScheme!==y&&wf();let Ot=Ag.getForInstance(o.plugins);l.length=0,l.push(...Ot),Cm(),be=o.launcher?.enabled??!0,Je=o.launcher?.autoExpand??!1,uo=o.features?.showReasoning??!0,Dn=o.features?.showToolCalls??!0,go=o.features?.scrollToBottom??{};let Tt=kn();Nn=o.features?.scrollBehavior??{},Tt!==kn()&&(so(),Cn()),Bf(),qg(),qt();let on=nn;if(nn=o.features?.showEventStreamToggle??!1,nn&&!on){if(Ze||(re(),T.setSSEEventCallback((J,je)=>{o.onSSEEvent?.(J,je),te(J,je)})),!et&&Ae){let J=o.features?.eventStream?.classNames,je="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J?.toggleButton?" "+J.toggleButton:"");et=k("button",je),et.style.width="28px",et.style.height="28px",et.style.color=un.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let Ke=tn(SC,"18px","currentColor",1.5);Ke&&et.appendChild(Ke);let ot=Oe.clearChatButtonWrapper,Ct=Oe.closeButtonWrapper,en=ot||Ct;en&&en.parentNode===Ae?Ae.insertBefore(et,en):Ae.appendChild(et),et.addEventListener("click",()=>{b?ks():Ld()})}}else!nn&&on&&(ks(),et&&(et.remove(),et=null),Ze?.clear(),Ho?.destroy(),Ze=null,Ho=null,An?.reset(),An=null,Zn=null);if(o.launcher?.enabled===!1&&Mt&&(Mt.destroy(),Mt=null),o.launcher?.enabled===!1&&cn&&(cn.remove(),cn=null),o.launcher?.enabled!==!1&&!Mt&&!cn){let{instance:J,element:je}=dg({config:o,plugins:l,onToggle:Xm});Mt=J,J||(cn=je),t.appendChild(je)}Mt&&Mt.update(o),aa(),_r&&o.launcher?.subtitle!==void 0&&(_r.textContent=o.launcher.subtitle);let Ye=o.layout?.header;if(Ye?.layout!==Fe&&Ae){let J=Ye?nd(o,Ye,{showClose:Pe(),onClose:()=>pt(!1,"user")}):Cs({config:o,showClose:Pe(),onClose:()=>pt(!1,"user")});Mn.replaceHeader(J),Ae=Mn.header.element,At=Mn.header.iconHolder,lr=Mn.header.headerTitle,_r=Mn.header.headerSubtitle,Ue=Mn.header.closeButton,Fe=Ye?.layout,aa()}else if(Ye){if(At&&(At.style.display=Ye.showIcon===!1?"none":""),lr&&(lr.style.display=Ye.showTitle===!1?"none":""),_r&&(_r.style.display=Ye.showSubtitle===!1?"none":""),Ue){let J=Pe()&&Ye.showCloseButton!==!1;Ue.style.display=J?"":"none"}if(Oe.clearChatButtonWrapper){let J=Ye.showClearChat;if(J!==void 0){Oe.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:je}=Oe;je&&!je.classList.contains("persona-absolute")&&(J?je.classList.remove("persona-ml-auto"):je.classList.add("persona-ml-auto"))}}}let Mo=o.layout?.showHeader!==!1;Ae&&(Ae.style.display=Mo?"":"none");let Xo=o.layout?.showFooter!==!1;He&&(He.style.display=Xo?"":"none"),Dr(),qt(),be!==Ee?be?pt(Je,"auto"):(ye=!0,Ki()):Je!==U&&pt(Je,"auto"),U=Je,Ee=be,da(),sh();let gs=JSON.stringify(o.toolCall)!==JSON.stringify(a),L=JSON.stringify(o.messageActions)!==JSON.stringify(d),ke=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),We=o.loadingIndicator?.render!==C?.render||o.loadingIndicator?.renderIdle!==C?.renderIdle||o.loadingIndicator?.showBubble!==C?.showBubble,we=o.iterationDisplay!==W,zt=(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(Y);(gs||L||ke||We||we||zt)&&T&&(Qr++,$n(Te,T.getMessages(),It));let at=o.features?.streamAnimation?.type;if(at!==se&&at&&at!=="none"){let J=Ud(at,o.features?.streamAnimation?.plugins);J&&va(J,t)}let Ie=o.launcher??{},io=Ie.headerIconHidden??!1,St=o.layout?.header?.showIcon,Zt=io||St===!1,jt=Ie.headerIconName,kt=Ie.headerIconSize??"48px";if(At){let J=Ae,je=J?.querySelector(".persona-flex-col");if(Zt)At.style.display="none",J&&je&&!J.contains(je)&&J.insertBefore(je,J.firstChild);else{if(At.style.display="",At.style.height=kt,At.style.width=kt,J&&je&&(J.contains(At)?At.nextSibling!==je&&(At.remove(),J.insertBefore(At,je)):J.insertBefore(At,je)),jt){let ot=parseFloat(kt)||24,Ct=me(jt,ot*.6,"currentColor",1);Ct?At.replaceChildren(Ct):At.textContent=Ie.agentIconText??"\u{1F4AC}"}else if(Ie.iconUrl){let ot=At.querySelector("img");if(ot)ot.src=Ie.iconUrl,ot.style.height=kt,ot.style.width=kt;else{let Ct=document.createElement("img");Ct.src=Ie.iconUrl,Ct.alt="",Ct.className="persona-rounded-xl persona-object-cover",Ct.style.height=kt,Ct.style.width=kt,At.replaceChildren(Ct)}}else{let ot=At.querySelector("svg"),Ct=At.querySelector("img");(ot||Ct)&&At.replaceChildren(),At.textContent=Ie.agentIconText??"\u{1F4AC}"}let Ke=At.querySelector("img");Ke&&(Ke.style.height=kt,Ke.style.width=kt)}}let _e=o.layout?.header?.showTitle,Wn=o.layout?.header?.showSubtitle;if(lr&&(lr.style.display=_e===!1?"none":""),_r&&(_r.style.display=Wn===!1?"none":""),Ue){let J=Pe()&&o.layout?.header?.showCloseButton!==!1;if(Ue.style.display=J?"":"none",!Re()){let Qt=Ie.closeButtonSize??"";Ue.style.height=Qt,Ue.style.width=Qt,Ue.style.minWidth=Qt,Ue.style.minHeight=Qt}let je=Ie.closeButtonPlacement??"inline",{closeButtonWrapper:Ke}=Oe,ot=je==="top-right",Ct=Ke?.classList.contains("persona-absolute");if(Ke&&ot!==Ct)if(Ke.remove(),ot){Ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Qt=Zi??ue;Qt.style.position="relative",Qt.appendChild(Ke)}else{let Qt=Ie.clearChat?.placement??"inline",Xt=Ie.clearChat?.enabled??!0;Ke.className=Xt&&Qt==="inline"?"":"persona-ml-auto",Ae&&Ae.appendChild(Ke)}if(Ue.style.color=Ie.closeButtonColor||un.actionIconColor,Ie.closeButtonBackgroundColor?(Ue.style.backgroundColor=Ie.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),Ie.closeButtonBorderWidth||Ie.closeButtonBorderColor){let Qt=Ie.closeButtonBorderWidth||"0px",Xt=Ie.closeButtonBorderColor||"transparent";Ue.style.border=`${Qt} solid ${Xt}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");Ie.closeButtonBorderRadius?(Ue.style.borderRadius=Ie.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),Ie.closeButtonPaddingX?(Ue.style.paddingLeft=Ie.closeButtonPaddingX,Ue.style.paddingRight=Ie.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Ie.closeButtonPaddingY?(Ue.style.paddingTop=Ie.closeButtonPaddingY,Ue.style.paddingBottom=Ie.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom=""),td(Ue,Ie.closeButtonIconName??"x",{iconSize:Re()?ig:void 0,iconText:Ie.closeButtonIconText??"\xD7"});let en=Ie.closeButtonTooltipText??"Close chat",ao=Ie.closeButtonShowTooltip??!0;Ue.setAttribute("aria-label",en),Ke&&Yt({anchor:Ue,trigger:Ke,text:()=>Ue?.getAttribute("aria-label")??en,enabled:ao})}let{clearChatButton:$e,clearChatButtonWrapper:De}=Oe;if($e){let J=Ie.clearChat??{},je=J.enabled??!0,Ke=o.layout?.header?.showClearChat,ot=Ke!==void 0?Ke:je,Ct=J.placement??"inline";if(De){De.style.display=ot?"":"none";let{closeButtonWrapper:en}=Oe;!Re()&&en&&!en.classList.contains("persona-absolute")&&(ot?en.classList.remove("persona-ml-auto"):en.classList.add("persona-ml-auto"));let ao=Ct==="top-right",Qt=De.classList.contains("persona-absolute");if(!Re()&&ao!==Qt&&ot){if(De.remove(),ao){De.className="persona-absolute persona-top-4 persona-z-50",De.style.right="48px";let To=Zi??ue;To.style.position="relative",To.appendChild(De)}else{De.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",De.style.right="";let To=Oe.closeButtonWrapper;Ae&&To&&To.parentElement===Ae?Ae.insertBefore(De,To):Ae&&Ae.appendChild(De)}let Xt=Oe.closeButtonWrapper;Xt&&!Xt.classList.contains("persona-absolute")&&(ao?Xt.classList.add("persona-ml-auto"):Xt.classList.remove("persona-ml-auto"))}}if(ot){if(!Re()){let Xt=J.size??"";$e.style.height=Xt,$e.style.width=Xt,$e.style.minWidth=Xt,$e.style.minHeight=Xt}let en=J.iconColor??"";if($e.style.color=en||un.actionIconColor,td($e,J.iconName??"refresh-cw",{iconSize:Re()?ag:void 0}),J.backgroundColor?($e.style.backgroundColor=J.backgroundColor,$e.classList.remove("hover:persona-bg-gray-100")):($e.style.backgroundColor="",$e.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let Xt=J.borderWidth||"0px",To=J.borderColor||"transparent";$e.style.border=`${Xt} solid ${To}`,$e.classList.remove("persona-border-none")}else $e.style.border="",$e.classList.add("persona-border-none");J.borderRadius?($e.style.borderRadius=J.borderRadius,$e.classList.remove("persona-rounded-full")):($e.style.borderRadius="",$e.classList.add("persona-rounded-full")),J.paddingX?($e.style.paddingLeft=J.paddingX,$e.style.paddingRight=J.paddingX):($e.style.paddingLeft="",$e.style.paddingRight=""),J.paddingY?($e.style.paddingTop=J.paddingY,$e.style.paddingBottom=J.paddingY):($e.style.paddingTop="",$e.style.paddingBottom="");let ao=J.tooltipText??"Clear chat",Qt=J.showTooltip??!0;$e.setAttribute("aria-label",ao),De&&Yt({anchor:$e,trigger:De,text:()=>$e?.getAttribute("aria-label")??ao,enabled:Qt})}}let gt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Eg],nt=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Va.message,Va.messageAndClick];Le=Tg({parsers:gt,handlers:nt,getSessionMetadata:ce,updateSessionMetadata:ie,emit:w.emit,documentRef:typeof document<"u"?document:null}),It=EC(o,Le,xs),Uw(),T.updateConfig(o),(o.features?.history?.enabled===!0!==ge||o.features?.history?.provider!==Qe||o.getIdentityProof!==ct||o.clientToken!==ut)&&(Sn({restoreFocus:!1}),um()),Sr(),$l(),$n(Te,T.getMessages(),It),Rs(),El(),Nw(),Gi(T.isStreaming()),Kt!==o.contextMentions&&dh();let dt=o.voiceRecognition?.enabled===!0,ft=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Yo=o.voiceRecognition?.provider?.type==="runtype";if(dt&&(ft||Yo))if(!oe||!Tn){let J=fi(o);if(J){oe=J.button,Tn=J.wrapper;let je=mo&&mo.parentElement===Qa?mo:null;Qa?Qa.insertBefore(Tn,je):eo?.appendChild(Tn),tt&&(tt.micButton=oe),tt?.addListener(oe,"click",Xp),oe.disabled=T.isStreaming()}}else{let J=o.voiceRecognition??{},je=o.sendButton??{},Ke=J.iconName??"mic",ot=J.iconSize,Ct=parseFloat(ot??"")||dn;oe.classList.add(_n),oe.classList.toggle(lo,!ot),oe.style.width=ot??"",oe.style.height=ot??"",oe.style.minWidth=ot??"",oe.style.minHeight=ot??"";let en=J.iconColor??je.textColor;oe.innerHTML="";let ao=me(Ke,Ct,en||"currentColor",1.5);ao?oe.appendChild(ao):oe.textContent="\u{1F3A4}";let Qt=J.backgroundColor??je.backgroundColor;Qt?oe.style.backgroundColor=Qt:oe.style.backgroundColor="",en?oe.style.color=en:oe.style.color="var(--persona-text, #111827)",J.borderWidth?(oe.style.borderWidth=J.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),J.borderColor?oe.style.borderColor=J.borderColor:oe.style.borderColor="",J.paddingX?(oe.style.paddingLeft=J.paddingX,oe.style.paddingRight=J.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),J.paddingY?(oe.style.paddingTop=J.paddingY,oe.style.paddingBottom=J.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let Xt=J.tooltipText??"Start voice recognition",To=J.showTooltip??!1;oe.setAttribute("aria-label",Xt),Tn&&Yt({anchor:oe,trigger:Tn,text:()=>oe?.getAttribute("aria-label")??Xt,enabled:To}),Tn.style.display="",oe.disabled=T.isStreaming()}else oe&&Tn&&(Tn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?T.isVoiceActive()&&T.toggleVoice():Ao&&xr());if(o.attachments?.enabled===!0){if(!yn||!wt){let J=o.attachments??{};bn||(bn=k("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),bn.style.display="none",(pe.parentElement??eo).insertBefore(bn,pe)),ht||(ht=document.createElement("input"),ht.type="file",ht.accept=(J.allowedTypes??er).join(","),ht.multiple=(J.maxFiles??4)>1,ht.style.display="none",ht.setAttribute("aria-label","Attach files"),(pe.parentElement??eo).insertBefore(ht,pe)),yn=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 ${_n} ${lo}`),wt.type="button",wt.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let je=J.buttonIconName??"paperclip";wt.style.fontSize="18px",wt.style.lineHeight="1";let Ke=me(je,dn,"currentColor",1.5);Ke?wt.appendChild(Ke):wt.textContent="\u{1F4CE}",wt.addEventListener("click",Ct=>{Ct.preventDefault(),ht?.click()}),yn.appendChild(wt);let ot=J.buttonTooltipText??"Attach file";Yt({anchor:wt,trigger:yn,text:()=>wt?.getAttribute("aria-label")??ot}),Sd?Sd.append(yn):eo.appendChild(yn),tt&&(tt.attachmentButton=wt,tt.attachmentInput=ht??void 0,tt.attachmentPreviews=bn??void 0),!Xe&&ht&&bn&&(Xe=ka.fromConfig(J,zg),Xe.setPreviewsContainer(bn),tt?.addListener(ht,"change",async()=>{Xe&&ht?.files&&(await Xe.handleFileSelect(ht.files),ht.value="")}))}else{yn.style.display="";let J=o.attachments??{};ht&&(ht.accept=(J.allowedTypes??er).join(","),ht.multiple=(J.maxFiles??4)>1),Xe&&Xe.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(TC(o.attachments?.dropOverlay)),wt){let J=o.attachments??{},je=J.buttonTooltipText??"Attach file";wt.setAttribute("aria-label",je),wt.textContent="";let Ke=me(J.buttonIconName??"paperclip",dn,"currentColor",1.5);Ke?wt.appendChild(Ke):wt.textContent="\u{1F4CE}",yn&&Yt({anchor:wt,trigger:yn,text:()=>wt?.getAttribute("aria-label")??je})}}else yn&&(yn.style.display="none"),Xe&&Xe.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let mt=o.sendButton??{},Zp=mt.useIcon??!1,fs=mt.iconText??"\u2191",sc=mt.iconName,Ch=mt.tooltipText??"Send message",nx=mt.showTooltip??!1,ga=mt.size,ox=parseFloat(ga??"")||Hu,ic=mt.backgroundColor,fa=mt.textColor;if(Zp){if(xe.style.width=ga??"",xe.style.height=ga??"",xe.style.minWidth=ga??"",xe.style.minHeight=ga??"",xe.style.fontSize="18px",xe.style.lineHeight="1",fa?xe.style.color=fa:xe.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!T.isStreaming())if(xe.innerHTML="",sc){let J=parseFloat(mt.iconSize??"")||Math.round(ox*.5),je=fa?.trim()||"currentColor",Ke=mt.iconStrokeWidth??2,ot=me(sc,J,je,Ke),Ct=me(mt.stopIconName??"square",J,je,Ke);ot&&Ct?xe.appendChild(Ru(ot,Ct)):ot?xe.appendChild(ot):xe.textContent=fs}else xe.textContent=fs;xe.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${_n}`,ic?(xe.style.backgroundColor=ic,xe.classList.remove("persona-bg-persona-primary")):(xe.style.backgroundColor="",xe.classList.add("persona-bg-persona-primary"))}else xe.textContent=o.copy?.sendButtonLabel??"Send",xe.style.width="",xe.style.height="",xe.style.minWidth="",xe.style.minHeight="",xe.style.fontSize="",xe.style.lineHeight="",xe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",ic?(xe.style.backgroundColor=ic,xe.classList.remove("persona-bg-persona-accent")):xe.classList.add("persona-bg-persona-accent"),fa?xe.style.color=fa:xe.classList.add("persona-text-white");mt.borderWidth?(xe.style.borderWidth=mt.borderWidth,xe.style.borderStyle="solid"):(xe.style.borderWidth="",xe.style.borderStyle=""),mt.borderColor?xe.style.borderColor=mt.borderColor:xe.style.borderColor="",mt.paddingX?(xe.style.paddingLeft=mt.paddingX,xe.style.paddingRight=mt.paddingX):(xe.style.paddingLeft="",xe.style.paddingRight=""),mt.paddingY?(xe.style.paddingTop=mt.paddingY,xe.style.paddingBottom=mt.paddingY):(xe.style.paddingTop="",xe.style.paddingBottom=""),T.isStreaming()||xe.setAttribute("aria-label",Ch),Al(),mo&&Yt({anchor:xe,trigger:mo,text:()=>xe.getAttribute("aria-label")??Ch,enabled:nx}),sf();let wh=Vc(Ce.getState().activeModeIds,o.composer?.modes);Ce.setActiveModeIds(wh),Ms().length>0!==!!Bo&&Rd(),Bo?.render(wh,Ms());for(let J of[...Es.keys()])jc(J,o.composer?.modeGroups)||Es.delete(J);Es.forEach(J=>J.repaint()),dr?.repaint(),bo?.resolve();let ac=Rr(o,Re());if(Fd(),ac){Te.style.maxWidth=ac,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",En.style.maxWidth=ac,En.style.marginLeft="auto",En.style.marginRight="auto",En.style.width="100%";for(let J of[eo,ar,bn,st])J&&(J.style.maxWidth=ac,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{Te.style.maxWidth="",Te.style.marginLeft="",Te.style.marginRight="",Te.style.width="",En.style.maxWidth="",En.style.marginLeft="",En.style.marginRight="",En.style.width="";for(let J of[eo,ar,bn,st])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let Mr=o.statusIndicator??{},rx=Mr.visible??!0;if(st.style.display=rx?"":"none",T){let J=T.getStatus();Ga(st,(Ke=>Ke==="idle"?Mr.idleText??Dt.idle:Ke==="connecting"?Mr.connectingText??Dt.connecting:Ke==="connected"?Mr.connectedText??Dt.connected:Ke==="error"?Mr.errorText??Dt.error:Dt[Ke])(J),Mr,J)}st.classList.remove("persona-text-left","persona-text-center","persona-text-right");let sx=Mr.align==="left"?"persona-text-left":Mr.align==="center"?"persona-text-center":"persona-text-right";st.classList.add(sx),Hd(),Zd(),to(),Nt()},open(){Pe()&&pt(!0,"api")},close(){Pe()&&pt(!1,"api")},toggle(){Pe()&&pt(!ye,"api")},reconnect(){T.reconnectNow()},clearChat(){_o=!1,T.clearMessages(),Bt.clear(),Cn();try{localStorage.removeItem(Ei),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ei}`)}catch(a){console.error("[AgentWidget] Failed to clear default localStorage:",a)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ei)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&&hl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ee={},Le.syncFromMetadata(),Xe?.clearAttachments(),bl(),Ts(void 0),yo(void 0),Gr(),Ze?.clear(),An?.reset(),Q?.update()},setMessage(r){return!pe||T.isStreaming()||vr()?!1:(!ye&&Pe()&&pt(!0,"system"),pe.value=r,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(r){if(T.isStreaming()||ts())return!1;let a=r?.trim()||pe.value.trim();return a?(!ye&&Pe()&&pt(!0,"system"),pe.value="",pe.style.height="auto",ho(),Zl(a,{consumeDraft:!1}),!0):!1},getComposerState(){return Ce.getState()},setQuote(r){let a=r?.text?.trim();a&&yo({...r,text:a})},clearQuote(){yo(void 0)},startVoiceRecognition(){return T.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(T.isVoiceActive()||(!ye&&Pe()&&pt(!0,"system"),ze.manuallyDeactivated=!1,ro(),T.toggleVoice().then(()=>{ze.active=T.isVoiceActive(),Fo("user"),T.isVoiceActive()&&ei()})),!0):Ao?!0:Qm()?(!ye&&Pe()&&pt(!0,"system"),ze.manuallyDeactivated=!1,ro(),tc("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,ro(),Fo("user"),Qo()}),!0):!1:Ao?(ze.manuallyDeactivated=!0,ro(),xr("user"),!0):!1},injectMessage(r){return!ye&&Pe()&&pt(!0,"system"),T.injectMessage(r)},injectAssistantMessage(r){!ye&&Pe()&&pt(!0,"system");let a=T.injectAssistantMessage(r);return co&&(co=!1,po&&(clearTimeout(po),po=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),a},injectUserMessage(r){return!ye&&Pe()&&pt(!0,"system"),T.injectUserMessage(r)},injectSystemMessage(r){return!ye&&Pe()&&pt(!0,"system"),T.injectSystemMessage(r)},injectMessageBatch(r){return!ye&&Pe()&&pt(!0,"system"),T.injectMessageBatch(r)},injectComponentDirective(r){return!ye&&Pe()&&pt(!0,"system"),T.injectComponentDirective(r)},injectTestMessage(r){!ye&&Pe()&&pt(!0,"system"),T.injectTestEvent(r)},async connectStream(r,a){return T.connectStream(r,a)},__pushEventStreamEvent(r){nn&&(re(),te(r.type,r.payload))},showEventStream(){nn&&Ld()},hideEventStream(){b&&ks()},isEventStreamVisible(){return b},listConversations(r){return T.listConversations(r)},getActiveConversationId(){return T.getActiveConversationId()},openConversation(r,a){return Bp(r,{focusComposer:a?.focus===!0})},startNewConversation(r){return _p({focusComposer:r?.focus===!0})},deleteConversation(r){return Dm(r)},renameConversation(r,a){return Op(r,{title:a})},setConversationStarred(r,a){return Op(r,{starred:a})},clearConversationHistory(r){return Nm(r)},resetHistoryIdentity(){return Fm()},getHistoryIdentityStatus(){return Hn?Hn.getIdentityStatus():bp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(r){return ia({...r?.returnSurface?{returnSurface:r.returnSurface}:{},...r?.focus!==void 0?{focus:r.focus}:{}})},hideHistory(r){Sn(r?.restoreFocus!==void 0?{restoreFocus:r.restoreFocus}:void 0)},isHistoryVisible(){return ae},showArtifacts(){fn(o)&&(_o=!1,Is=!0,oo(),qe?.setMobileOpen(!0))},hideArtifacts(){fn(o)&&(_o=!0,oo())},upsertArtifact(r){return fn(o)?(Er(o.features?.artifacts,{artifactType:r.artifactType,...r.artifactType==="markdown"&&r.file?{file:r.file}:{},...r.presentation?{presentation:r.presentation}:{}})==="panel"&&(_o=!1,Is=!0),T.upsertArtifact(r)):null},selectArtifact(r){fn(o)&&T.selectArtifact(r)},clearArtifacts(){fn(o)&&T.clearArtifacts()},getArtifacts(){return T?.getArtifacts()??[]},getSelectedArtifactId(){return T?.getSelectedArtifactId()??null},focusInput(){return be&&!ye&&!Re()||!pe?!1:(pe.focus(),!0)},async resolveApproval(r,a,d){let y=T.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"){T.resolveWebMcpApproval(y.id,a);return}return T.resolveApproval(y.approval,a,d)},setFollowUpSuggestions(r){dw(r)},clearFollowUpSuggestions(){Wf()},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...ee}},updatePersistentMetadata(r){ie(r)},on(r,a){return w.on(r,a)},off(r,a){w.off(r,a)},isOpen(){return Pe()&&ye},isVoiceActive(){return ze.active},toggleReadAloud(r){T.toggleReadAloud(r)},stopReadAloud(){T.stopSpeaking()},getReadAloudState(r){return T.getReadAloudState(r)},onReadAloudChange(r){return T.onReadAloudChange(r)},getState(){return{open:Pe()&&ye,launcherEnabled:be,voiceActive:ze.active,streaming:T.isStreaming()}},showCSATFeedback(r){!ye&&Pe()&&pt(!0,"system");let a=Te.querySelector(".persona-feedback-container");a&&a.remove();let d=CC({onSubmit:async(f,y)=>{T.isClientTokenMode()&&await T.submitCSATFeedback(f,y),r?.onSubmit?.(f,y)},onDismiss:r?.onDismiss,...r});Te.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(r){!ye&&Pe()&&pt(!0,"system");let a=Te.querySelector(".persona-feedback-container");a&&a.remove();let d=wC({onSubmit:async(f,y)=>{T.isClientTokenMode()&&await T.submitNPSFeedback(f,y),r?.onSubmit?.(f,y)},onDismiss:r?.onDismiss,...r});Te.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(r,a){return T.submitCSATFeedback(r,a)},async submitNPSFeedback(r,a){return T.submitNPSFeedback(r,a)},destroy(){pp(),rs!=null&&(clearInterval(rs),rs=null),he.forEach(r=>r()),Ve.remove(),Vt?.remove(),Mt?.destroy(),cn?.remove(),zr&&Ue.removeEventListener("click",zr)}};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,he.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 Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&Et.focusInput()};if(window.addEventListener("persona:focusInput",a),he.push(()=>{window.removeEventListener("persona:focusInput",a)}),nn){let j=se=>{let ge=se.detail;(!ge?.instanceId||ge.instanceId===r)&&Et.showEventStream()},Y=se=>{let ge=se.detail;(!ge?.instanceId||ge.instanceId===r)&&Et.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",Y),he.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",Y)})}let d=j=>{let Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&Et.showHistory()},f=j=>{let Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&Et.hideHistory()};window.addEventListener("persona:showHistory",d),window.addEventListener("persona:hideHistory",f),he.push(()=>{window.removeEventListener("persona:showHistory",d),window.removeEventListener("persona:hideHistory",f)});let y=j=>{let Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&Et.showArtifacts()},C=j=>{let Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&Et.hideArtifacts()},W=j=>{let Y=j.detail;Y?.instanceId&&Y.instanceId!==r||Y?.artifact&&Et.upsertArtifact(Y.artifact)},z=j=>{let Y=j.detail;Y?.instanceId&&Y.instanceId!==r||typeof Y?.id=="string"&&Et.selectArtifact(Y.id)},q=j=>{let Y=j.detail;(!Y?.instanceId||Y.instanceId===r)&&Et.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",q),he.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",q)})}let Kn=CT(o.persistState);if(Kn&&Pe()){let r=wT(Kn.storage),a=`${Kn.keyPrefix}widget-open`,d=`${Kn.keyPrefix}widget-voice`,f=`${Kn.keyPrefix}widget-voice-mode`;if(r){let y=Kn.persist?.openState&&r.getItem(a)==="true",C=Kn.persist?.voiceState&&r.getItem(d)==="true",W=Kn.persist?.voiceState&&r.getItem(f)==="true";if(y&&(Mt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Et.open(),setTimeout(()=>{if(C||W)Et.startVoiceRecognition();else if(Kn.persist?.focusInput){let z=t.querySelector("textarea");z&&z.focus()}},100)},0)),Kn.persist?.openState&&(w.on("widget:opened",()=>{r.setItem(a,"true")}),w.on("widget:closed",()=>{r.setItem(a,"false")})),Kn.persist?.voiceState&&(w.on("voice:state",z=>{r.setItem(d,z.active?"true":"false")}),w.on("user:message",z=>{r.setItem(f,z.viaVoice?"true":"false")})),Kn.clearOnChatClear){let z=()=>{r.removeItem(a),r.removeItem(d),r.removeItem(f)},q=()=>z();window.addEventListener("persona:clear-chat",q),he.push(()=>{window.removeEventListener("persona:clear-chat",q)})}}}if(Z&&Pe()&&(Mt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Et.open()},0)),Fs(),!pw){let r=lc(()=>{T&&(Qr++,Bt.clear(),$n(Te,T.getMessages(),It))});he.push(r)}E=()=>{T&&(Qr++,Bt.clear(),$n(Te,T.getMessages(),It))},T.getMessages().length>0&&xl(),A=()=>{T&&(Qr++,Bt.clear(),$n(Te,T.getMessages(),It))};let ex=Dh(()=>{T&&(Qr++,Bt.clear(),$n(Te,T.getMessages(),It))});he.push(ex);let tx=yg(()=>{T&&(Qr++,Bt.clear(),$n(Te,T.getMessages(),It),or()?.updateInlineArtifactBlocks(Te,Un.artifacts,{suppressTransition:!0}),oo())});return he.push(tx),Et};var PC=(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},AT=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},MT=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},ET=(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.")},IC=(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"},_g=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=""},LC=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",_g(t)},Rg=t=>{t.style.transition=""},Wg=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Bg=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Cd=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},TT=(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))},kT=(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)},PT=t=>{let e=hi(t),n=e.components?.panel,o=(s,i)=>s==null||s===""?i:pn(e,s)??s;return{inset:o(n?.inset,Kc),canvasBackground:o(n?.canvasBackground,Gc)}},HC=(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},IT=(t,e,n,o,s,i,l,c)=>{let p=Yn(i),g=p.reveal==="push",u=c!=null,m=c?.inset??"",v=c?.canvasBackground??"";TT(t,e,n,o,g),kT(t,e,n,o,p.side,g),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,x=i?.launcher?.mobileFullscreen??!0,E=i?.launcher?.mobileBreakpoint??640,M=h!=null?h.innerWidth<=E:!1;if(x&&M&&l){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Wg(e),Rg(o),LC(o),Bg(n),Cd(s,o),HC(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",g&&(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"),LC(o),AT(o,p.maxHeight),HC(o,u&&l,m,v),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Wg(e),Rg(o),Bg(n),Cd(s,o);let P=p.animate?"transform 180ms ease":"none",K=p.side==="right"?"translateX(100%)":"translateX(-100%)",A=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=A,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",Rg(o),_g(o),Cd(s,o);let P=PC(p.width,t.clientWidth),K=Math.max(0,t.clientWidth),A=p.animate?"margin-left 180ms ease":"none",H=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=A,e.style.marginLeft=`${H}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${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="",Wg(e),_g(o),Bg(n),Cd(s,o);let P=p.reveal==="emerge";P?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let K=l?p.width:"0px",A=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",H=!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",MT(o,p.maxHeight),o.style.overflow=P||H?"hidden":"visible",o.style.transition=A,P){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let w=u?`calc(${PC(p.width,t.clientWidth)}px - (2 * ${m}))`:p.width;s.style.width=w,s.style.minWidth=w,s.style.maxWidth=w,s.style.boxSizing="border-box"}}},LT=(t,e)=>{let n=t.ownerDocument.createElement("div");return IC(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){IC(n,o)},destroy(){n.remove()}}},HT=(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"),g=n.createElement("aside"),u=n.createElement("div"),m=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;c.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",g.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",g.appendChild(u),o.insertBefore(l,t),p.appendChild(t);let v=null,h=()=>{v?.disconnect(),v=null},x=null,E=()=>{x=e?.launcher?.detachedPanel===!0?PT(e):null};E();let M=()=>{IT(l,c,p,g,u,e,m,x)},F=null,P=()=>{F?.(),F=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(F=Qc(()=>{E(),M()}))},K=()=>{h(),Yn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(v=new ResizeObserver(()=>{M()}),v.observe(l)))},A=!1,H=()=>{M(),K(),m&&!A&&l.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,ET(l,Yn(e)))},w=l.ownerDocument.defaultView,_=()=>{H()};return w?.addEventListener("resize",_),Yn(e).reveal==="push"?(c.appendChild(p),c.appendChild(g),l.appendChild(c)):(l.appendChild(p),l.appendChild(g)),H(),P(),{mode:"docked",host:u,shell:l,syncWidgetState(G){let le=G.launcherEnabled?G.open:!0;m!==le&&(m=le,H())},updateConfig(G){e=G,(e?.launcher?.enabled??!0)===!1&&(m=!0),E(),H(),P()},destroy(){w?.removeEventListener("resize",_),F?.(),F=null,h(),o.isConnected&&(i&&i.parentNode===o?o.insertBefore(t,i):o.appendChild(t)),l.remove()}}},RC=(t,e)=>Rt(e)?HT(t,e):LT(t,e);var Ka={desktop:{w:1280,h:800},mobile:{w:390,h:844}},WC=.15,BC=1.5,Og="persona-preview-shell-theme",RT={load:()=>null,save:()=>{},clear:()=>{}},WT=["How do I get started?","Pricing & plans","Talk to support"];function Dg(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function BT(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 _C(t){let e=BT(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 Su=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 _C(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(_g);o||(o=n.createElement("style"),o.id=_g,n.head.appendChild(o)),o.textContent=BC(e)}var BT=`
152
+ .preview-workspace-card.short { height: 96px; }`}function OC(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Og);o||(o=n.createElement("style"),o.id=Og,n.head.appendChild(o)),o.textContent=_C(e)}var _T=`
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 Su=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>`,_T=`
171
+ </div>`,OT=`
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 Su=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 OC(t,e,n,o){let s=`
185
- ${BT}
184
+ </div>`;function DC(t,e,n,o){let s=`
185
+ ${_T}
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 Su=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
- ${_T}
197
+ ${OT}
198
198
  </div>
199
199
  </div>
200
200
  </div>`;return`<!DOCTYPE html>
@@ -202,16 +202,16 @@ _Details: ${n.message}_`:o}var Su=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="${Og(o)}">
206
- <style id="${_g}">${BC(e)}</style>
205
+ <link rel="stylesheet" href="${Dg(o)}">
206
+ <style id="${Og}">${_C(e)}</style>
207
207
  </head>
208
208
  <body>
209
209
  ${n?i:s}
210
210
  </body>
211
- </html>`}var OT=()=>[{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()}],DT=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function NT(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"&&DT(e)?[...OT(),...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 FT(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},s={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:RT:t.suggestionChips,initialMessages:NT(e,t,n),storageAdapter:HT};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 UT(t,e){let n=t.theme?mi(t.theme,{validate:!1}):mi();return{...rt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Ti(t,e){let n=t.scene??"conversation";return FT(UT(t,e),n,t.appendedMessages??[])}function DC(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Ti(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Ti(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:Ti(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Ti(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Ti(t,n),shellMode:n}]}function $T(t,e){let n={...e},o=[],s=[],i=null,l=!1,c=1,p=1,g=0;function u(){return n.device??"desktop"}function f(){return n.zoom??c}function v(){let P=getComputedStyle(t),K=parseFloat(P.paddingLeft)+parseFloat(P.paddingRight),A=parseFloat(P.paddingTop)+parseFloat(P.paddingBottom),L=40,w=(n.compareMode??"off")!=="off",_=(t.clientWidth-K-L)/(w?2:1),G=t.clientHeight-A-L;if(_<=0||G<=0)return 1;let le=Va[u()]??Va.desktop;return Math.min(_/le.w,G/le.h,1)}function h(){c=v();let P=Math.max(RC,Math.min(WC,f()));p=P;let K=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let A of K){let L=A.dataset.device??"desktop",w=Va[L]??Va.desktop;A.style.width=`${w.w*P}px`,A.style.height=`${w.h*P}px`,L==="mobile"&&(A.style.borderRadius=`${32*P}px`);let _=A.querySelector("iframe");_&&(_.style.width=`${w.w}px`,_.style.height=`${w.h}px`,_.style.transformOrigin="top left",_.style.transition="none",_.style.transform=`scale(${P})`)}n.onScaleChange?.(P)}function x(){n.onBeforeDestroy?.();for(let P of o)P.destroy();for(let P of s)P();o=[],s=[]}function E(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function M(){if(l)return;x();let P=++g,K=DC(n),A=u(),L=(n.compareMode??"off")!=="off",w=(n.scene??"conversation")==="minimized",_=n.widgetCssPath??"/widget-dist/widget.css",G=n.buildSrcdoc??OC,le=A==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",ee=V=>`<div class="${le}" data-mount-id="${V.mountId}" data-device="${A}" data-shell-mode="${V.shellMode}">
212
- ${L?`<div class="preview-frame-meta"><span class="preview-frame-label">${Og(V.label)}</span></div>`:""}
211
+ </html>`}var DT=()=>[{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()}],NT=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function FT(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"&&NT(e)?[...DT(),...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 UT(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},s={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:WT:t.suggestionChips,initialMessages:FT(e,t,n),storageAdapter:RT};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 $T(t,e){let n=t.theme?mi(t.theme,{validate:!1}):mi();return{...rt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function ki(t,e){let n=t.scene??"conversation";return UT($T(t,e),n,t.appendedMessages??[])}function NC(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:ki(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:ki(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:ki(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:ki(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:ki(t,n),shellMode:n}]}function qT(t,e){let n={...e},o=[],s=[],i=null,l=!1,c=1,p=1,g=0;function u(){return n.device??"desktop"}function m(){return n.zoom??c}function v(){let P=getComputedStyle(t),K=parseFloat(P.paddingLeft)+parseFloat(P.paddingRight),A=parseFloat(P.paddingTop)+parseFloat(P.paddingBottom),H=40,w=(n.compareMode??"off")!=="off",_=(t.clientWidth-K-H)/(w?2:1),G=t.clientHeight-A-H;if(_<=0||G<=0)return 1;let le=Ka[u()]??Ka.desktop;return Math.min(_/le.w,G/le.h,1)}function h(){c=v();let P=Math.max(WC,Math.min(BC,m()));p=P;let K=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let A of K){let H=A.dataset.device??"desktop",w=Ka[H]??Ka.desktop;A.style.width=`${w.w*P}px`,A.style.height=`${w.h*P}px`,H==="mobile"&&(A.style.borderRadius=`${32*P}px`);let _=A.querySelector("iframe");_&&(_.style.width=`${w.w}px`,_.style.height=`${w.h}px`,_.style.transformOrigin="top left",_.style.transition="none",_.style.transform=`scale(${P})`)}n.onScaleChange?.(P)}function x(){n.onBeforeDestroy?.();for(let P of o)P.destroy();for(let P of s)P();o=[],s=[]}function E(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function M(){if(l)return;x();let P=++g,K=NC(n),A=u(),H=(n.compareMode??"off")!=="off",w=(n.scene??"conversation")==="minimized",_=n.widgetCssPath??"/widget-dist/widget.css",G=n.buildSrcdoc??DC,le=A==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",ee=V=>`<div class="${le}" data-mount-id="${V.mountId}" data-device="${A}" data-shell-mode="${V.shellMode}">
212
+ ${H?`<div class="preview-frame-meta"><span class="preview-frame-label">${Dg(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">${ee(V)}</div>`).join("")}</div>`:`<div class="preview-single">${ee(K[0])}</div>`;n.morphContainer?n.morphContainer(t,S):t.innerHTML=S,h();let B=E(),R=0,I=B.length,Z=()=>{if(l||P!==g)return;for(let ce of B){let ie=ce.dataset.mountId;if(!ie||!ce.contentDocument)continue;let me=K.find(we=>we.mountId===ie);if(!me)continue;let Te=()=>{},Le=Lt(me.config),Ce=Le?(()=>{let we=ce.contentDocument?.getElementById(`preview-content-${ie}`);if(!we)return null;let U=HC(we,me.config),ke=ce.contentDocument.createElement("div");ke.id=ie,ke.style.height="100%",ke.style.display="flex",ke.style.flexDirection="column",ke.style.flex="1",ke.style.minHeight="0",U.host.appendChild(ke);let $e=()=>U.syncWidgetState(Ze.getState()),mt=Te;return Te=()=>{U.destroy(),mt()},ke.__syncDock=$e,ke.__hostLayout=U,ke})():ce.contentDocument.getElementById(ie);if(!Ce)continue;let Ze=TC(Ce,me.config);if(o.push(Ze),Le&&Ce.__syncDock){let we=Ce.__syncDock,U=Ze.on("widget:opened",we),ke=Ze.on("widget:closed",we),$e=Te;Te=()=>{U(),ke(),$e()},we()}s.push(Te),w&&Ze.close()}let V=n.scene??"conversation";if(V==="messages")for(let ce of o)ce.showHistory({focus:!1});if(V==="artifact"||n.config?.features?.artifacts?.enabled)for(let ce of o)ce.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
214
+ </div>`,S=H?`<div class="preview-compare-grid">${K.map(V=>`<div class="preview-compare-cell">${ee(V)}</div>`).join("")}</div>`:`<div class="preview-single">${ee(K[0])}</div>`;n.morphContainer?n.morphContainer(t,S):t.innerHTML=S,h();let B=E(),R=0,I=B.length,Z=()=>{if(l||P!==g)return;for(let ce of B){let ie=ce.dataset.mountId;if(!ie||!ce.contentDocument)continue;let fe=K.find(ve=>ve.mountId===ie);if(!fe)continue;let Me=()=>{},Le=Rt(fe.config),be=Le?(()=>{let ve=ce.contentDocument?.getElementById(`preview-content-${ie}`);if(!ve)return null;let U=RC(ve,fe.config),Ee=ce.contentDocument.createElement("div");Ee.id=ie,Ee.style.height="100%",Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1",Ee.style.minHeight="0",U.host.appendChild(Ee);let Fe=()=>U.syncWidgetState(Je.getState()),yt=Me;return Me=()=>{U.destroy(),yt()},Ee.__syncDock=Fe,Ee.__hostLayout=U,Ee})():ce.contentDocument.getElementById(ie);if(!be)continue;let Je=kC(be,fe.config);if(o.push(Je),Le&&be.__syncDock){let ve=be.__syncDock,U=Je.on("widget:opened",ve),Ee=Je.on("widget:closed",ve),Fe=Me;Me=()=>{U(),Ee(),Fe()},ve()}s.push(Me),w&&Je.close()}let V=n.scene??"conversation";if(V==="messages")for(let ce of o)ce.showHistory({focus:!1});if(V==="artifact"||n.config?.features?.artifacts?.enabled)for(let ce of o)ce.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:B,controllers:[...o]})};for(let V of B){let ce=V.dataset.mountId;if(!ce)continue;let ie=K.find(me=>me.mountId===ce);ie&&(V.addEventListener("load",()=>{R++,R>=I&&Z()},{once:!0}),V.srcdoc=G(ce,ie.shellMode,Lt(ie.config),_))}I===0&&Z()}function F(){if(l)return;let P=DC(n);if(o.length!==P.length){M();return}if(P.some(A=>{let L=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${A.mountId}"]`);return!L||L.dataset.shellMode!==A.shellMode})){M();return}o.forEach((A,L)=>{A.update(P[L].config),(n.scene??"conversation")==="minimized"&&A.close()});for(let A of P){let L=t.querySelector(`iframe[data-mount-id="${A.mountId}"]`);L&&_C(L,A.shellMode)}n.onAfterUpdate?.({iframes:E(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(i=new ResizeObserver(()=>{l||h()}),i.observe(t)),M(),{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?M():F()},destroy(){l||(l=!0,x(),i?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){l||(n={...n,zoom:void 0},h())},getIframes(){return E()},getScale(){return p},setZoom(P){l||(n={...n,zoom:P},h())}}}export{$T as createThemePreview};
222
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:B,controllers:[...o]})};for(let V of B){let ce=V.dataset.mountId;if(!ce)continue;let ie=K.find(fe=>fe.mountId===ce);ie&&(V.addEventListener("load",()=>{R++,R>=I&&Z()},{once:!0}),V.srcdoc=G(ce,ie.shellMode,Rt(ie.config),_))}I===0&&Z()}function F(){if(l)return;let P=NC(n);if(o.length!==P.length){M();return}if(P.some(A=>{let H=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${A.mountId}"]`);return!H||H.dataset.shellMode!==A.shellMode})){M();return}o.forEach((A,H)=>{A.update(P[H].config),(n.scene??"conversation")==="minimized"&&A.close()});for(let A of P){let H=t.querySelector(`iframe[data-mount-id="${A.mountId}"]`);H&&OC(H,A.shellMode)}n.onAfterUpdate?.({iframes:E(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(i=new ResizeObserver(()=>{l||h()}),i.observe(t)),M(),{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?M():F()},destroy(){l||(l=!0,x(),i?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){l||(n={...n,zoom:void 0},h())},getIframes(){return E()},getScale(){return p},setZoom(P){l||(n={...n,zoom:P},h())}}}export{qT as createThemePreview};