@runtypelabs/persona 4.26.1 → 4.28.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 (61) hide show
  1. package/dist/approval-ui.d.cts +18 -0
  2. package/dist/approval-ui.d.ts +18 -0
  3. package/dist/artifacts-ui.d.cts +18 -0
  4. package/dist/artifacts-ui.d.ts +18 -0
  5. package/dist/chunk-AALCT54S.js +1 -0
  6. package/dist/{client-history-GOZWBDA5.js → client-history-LV3KHEFA.js} +1 -1
  7. package/dist/client-history.js +1 -1
  8. package/dist/client-stream-N22JHTLE.js +4 -0
  9. package/dist/client-stream.js +3 -3
  10. package/dist/codegen.cjs +1 -1
  11. package/dist/codegen.js +1 -1
  12. package/dist/context-mentions.d.cts +18 -0
  13. package/dist/context-mentions.d.ts +18 -0
  14. package/dist/event-stream-view.d.cts +18 -0
  15. package/dist/event-stream-view.d.ts +18 -0
  16. package/dist/forms-ui.d.cts +26 -0
  17. package/dist/forms-ui.d.ts +26 -0
  18. package/dist/index.cjs +57 -57
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +34 -0
  21. package/dist/index.d.ts +34 -0
  22. package/dist/index.global.js +1 -1
  23. package/dist/index.global.js.map +1 -1
  24. package/dist/index.js +58 -58
  25. package/dist/index.js.map +1 -1
  26. package/dist/session-reconnect.d.cts +18 -0
  27. package/dist/session-reconnect.d.ts +18 -0
  28. package/dist/smart-dom-reader.d.cts +18 -0
  29. package/dist/smart-dom-reader.d.ts +18 -0
  30. package/dist/theme-editor-preview.cjs +66 -66
  31. package/dist/theme-editor-preview.d.cts +18 -0
  32. package/dist/theme-editor-preview.d.ts +18 -0
  33. package/dist/theme-editor-preview.js +31 -31
  34. package/dist/theme-editor.d.cts +18 -0
  35. package/dist/theme-editor.d.ts +18 -0
  36. package/dist/voice-runtime-LVUMPUDS.js +17 -0
  37. package/dist/voice-runtime.cjs +7 -7
  38. package/dist/voice-runtime.d.cts +33 -0
  39. package/dist/voice-runtime.d.ts +33 -0
  40. package/dist/voice-runtime.js +7 -7
  41. package/package.json +1 -1
  42. package/src/client-stream.ts +10 -3
  43. package/src/client.interrupt.test.ts +18 -0
  44. package/src/client.test.ts +20 -0
  45. package/src/client.ts +7 -0
  46. package/src/session.ts +16 -3
  47. package/src/session.voice.test.ts +199 -3
  48. package/src/types.ts +24 -0
  49. package/src/ui.composer-defer-one.test.ts +17 -0
  50. package/src/ui.ts +49 -12
  51. package/src/voice/__fixtures__/voice-wire/server/session_end-provider-error.json +6 -0
  52. package/src/voice/__fixtures__/voice-wire/server/session_end-unknown-reason.json +4 -0
  53. package/src/voice/__fixtures__/voice-wire/server/session_end.json +5 -0
  54. package/src/voice/runtype-voice-provider.ts +205 -21
  55. package/src/voice/voice-clause-buffer.test.ts +143 -0
  56. package/src/voice/voice-clause-buffer.ts +187 -0
  57. package/src/voice/voice-delegation.ts +111 -13
  58. package/src/voice/voice.test.ts +433 -2
  59. package/dist/chunk-GKPCIQPB.js +0 -1
  60. package/dist/client-stream-42FOI3EC.js +0 -4
  61. package/dist/voice-runtime-XLU6YK2N.js +0 -17
@@ -1,17 +1,17 @@
1
- import{a as Om,b as qa,d as is,e as _m,f as ja,g as Fm,h as Wf,i as Bf,m as Df,n as ms,o as go}from"./chunk-QRKGQPU7.js";import{a as el}from"./chunk-4HPTPUC6.js";import{b as gi,c as Td,e as xf,f as Af,g as Mf}from"./chunk-J4J3Y2P2.js";import{A as uf,B as gf,C as mf,D as Pd,E as Uo,F as Mr,G as ff,H as qn,I as tl,J as nl,K as hf,L as ol,M as gs,N as rl,O as sl,P as il,Q as yf,R as wf,S as Sf,T as Id,a as Sr,b as Em,c as Tm,d as km,e as Pm,f as Lm,g as xr,h as Im,i as Hm,j as Rm,k as $a,l as $o,m as rs,n as za,o as Ar,p as Wm,q as Ua,r as ui,s as vd,t as af,u as lf,v as cf,w as vn,x as df,y as pf,z as kd}from"./chunk-T7QM7YMF.js";import{a as je,c as Bm,d as Dm,e as se}from"./chunk-ZC66NAIR.js";import{a as Za,c as nf,d as zo,f as us,g as Ed,i as of,j as rf,k as sf}from"./chunk-S6PBWE75.js";import{a as cl,b as Hf,c as Rd,d as mi,e as dl,f as fi,g as pl,h as hi,i as Rf,j as yi}from"./chunk-CPVD5P5B.js";import{a as Ef,b as Tf,c as uo,d as Er,e as kf,f as Pf,g as Lf,h as Hd,i as If}from"./chunk-VK6JOIYJ.js";import{a as Ga,b as zm,c as as,d as wd,e as Md}from"./chunk-K6HKIP5K.js";import{c as cs,d as Jm,j as Zm,k as xd}from"./chunk-K7NA7G7J.js";import{a as gt,b as Dt,d as tf}from"./chunk-2ANTRKTV.js";import{a as Ad,d as Ja,e as ef,f as ds}from"./chunk-TR2H475E.js";import{b as Nm,c as Ka,d as Vm,e as Cd,f as $m,g as ls,h as Um,i as qm,j as jm,k as Km,l as Ya,m as Qa,n as Sd,o as Xa,q as Gm,r as Ym,s as Qm,t as Xm}from"./chunk-NQLDCJAP.js";import{a as ps}from"./chunk-GKPCIQPB.js";import{a as bf,b as al,c as Ld,d as vf}from"./chunk-HGUCGM3K.js";import{b as ll}from"./chunk-Q735PSZL.js";import{a as yt}from"./chunk-7NQ4ZTHF.js";import{a as P,c as Y,d as ss}from"./chunk-76IELU7F.js";import{a as Cf}from"./chunk-UPO4GUFC.js";import{Circle as EC,Clock as TC}from"lucide";import{ChevronDown as CC,ChevronUp as wC}from"lucide";var SC=["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"],xC="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",AC="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",MC=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ul=(t,e)=>{let n=P("div",["persona-message-bubble",t,...SC].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},gl=t=>{let e=P("button",t.expandable?xC:AC);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},Wd=(t,e,n)=>{t.innerHTML="";let o=yt(e?wC:CC,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},fs=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=P("div","persona-flex persona-items-center");Wd(o,n.expanded,n.iconColor);let s=P("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},ml=t=>{let e=P("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?.();MC(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},fl=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&Wd(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"},hl=(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 u=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");u&&Wd(u,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};function yl(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return{...t,features:{...t?.features,[n]:{...e==="tool"?$o:rs,...t?.future?.v5Defaults===!0?za.features?.[n]:{},...t?.features?.[n]}}}}function qo(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return t?.features?.[n]?.variant??(t?.future?.v5Defaults?"row":"card")}function bi(t){let e=Math.max(0,Math.floor((t??0)/1e3));return e<1?"a moment":e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function mo(t,e,n,o){if(qo(n,o)!=="row")return t;t.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,t.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(t.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let s=t.querySelector(":scope > button");if(!s)return t;s.className="persona-activity-header";let i=o==="tool"?e.toolCall:e.reasoning,l=i?.status!=="complete",c=e.approval?.status??e.toolCall?.approvalStatus,u=c==="denied"?"denied":c==="pending"?"awaiting-approval":e.toolCall?.success===!1?"error":l?i?.status==="pending"?"pending":"running":"done";t.dataset.activityState=u;let p=P("span","persona-activity-icon");p.dataset.activityIcon=u;let g={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},y=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,h=y?se(y,16,"currentColor",2):u==="pending"?yt(EC,16,"currentColor",2):u==="awaiting-approval"?yt(TC,16,"currentColor",2):se(g[u],16,"currentColor",2);h&&p.appendChild(h),s.querySelector(".persona-reasoning-header-icon")?.remove();let C=o==="tool"?"toolCallDisplay":"reasoningDisplay",E=n.features?.[C]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((E==="always"||E==="active"&&u!=="done")&&s.prepend(p),o==="tool"&&i){let k=P("span","persona-activity-duration");l&&i.startedAt&&k.setAttribute("data-tool-elapsed",String(i.startedAt));let R=(o==="tool"?e.toolCall?.duration:void 0)??i.durationMs??(i.completedAt!==void 0&&i.startedAt!==void 0?i.completedAt-i.startedAt:void 0);k.textContent=R===void 0?"":bi(R),s.appendChild(k)}s.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),s.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let L=t.querySelector(":scope > .persona-border-t");return L?.classList.add("persona-activity-body"),L&&(L.id=`activity-details-${e.id}`,s.setAttribute("aria-controls",L.id)),t}function Of(t){let e=new Set,n=new Set,o=new Set,s=new Map,i=l=>{clearTimeout(s.get(l)),s.delete(l)};return{observe(l,c,u,p={}){let g=c==="tool"?l.toolCall:l.reasoning;if(!(!g||n.has(l.id))&&(!e.has(l.id)&&g.status!=="complete"&&g.chunks?.some(Boolean)&&(e.add(l.id),p.autoExpand!==!1&&u.add(l.id)),e.has(l.id)&&g.status==="complete"&&!o.has(l.id))){if(o.add(l.id),p.autoCollapseDelay===!1)return;s.set(l.id,setTimeout(()=>{s.delete(l.id),u.delete(l.id),t(l.id,c)},p.autoCollapseDelay??1e3))}},manual(l){n.add(l),i(l)},prune(l){for(let c of new Set([...e,...n,...o]))l.has(c)||(i(c),e.delete(c),n.delete(c),o.delete(c))},clear(){for(let l of s.keys())i(l);e.clear(),n.clear(),o.clear()}}}function _f(t,e,n,o){let s=P("div","");s.id=`bubble-${t.id}`,s.dataset.messageId=t.id;let i=P("button","");i.type="button",i.dataset.expandHeader="true",i.dataset.bubbleType="tool",i.setAttribute("aria-expanded",String(n));let l=P("div","");typeof o=="string"?l.textContent=o:l.appendChild(o),fs(i,l,{expandable:!0,expanded:n,iconColor:e.toolCall?.toggleTextColor||e.toolCall?.headerTextColor||"currentColor",metaGap:!0});let c=P("div","persona-border-t");return c.id=`activity-details-${t.id}`,c.style.display=n?"":"none",i.setAttribute("aria-controls",c.id),s.append(i,c),mo(s,t,{...e,features:{...e.features,toolCallDisplay:{...e.features?.toolCallDisplay,variant:"row"}}},"tool"),s.dataset.personaToolGroup="true",e.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(s.dataset.activityGroupShimmer="true"),{bubble:s,body:c}}function Ff(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function Nt(t){return t?.type==="runtype"||t?.type==="custom"}var kC=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Nf(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:kC()}catch{return!1}}var Vf=/^\s*\|?[\s:|-]*-[\s:|-]*$/,$f=t=>t.includes("|"),zf=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())},PC=t=>`| ${t.join(" | ")} |`,LC=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,IC=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Uf=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(!$f(s)||Vf.test(s)||!Vf.test(i))continue;let l=zf(s).length;if(l<1)continue;let c=LC(l);e[o+1]!==c&&(e[o+1]=c,n=!0);let u=o+2;for(;u<e.length;u++){let p=e[u];if(p.trim()===""||!$f(p))break;let g=PC(IC(zf(p),l));e[u]!==g&&(e[u]=g,n=!0)}o=u-1}return n?e.join(`
3
- `):t};var qf="var(--persona-md-table-scroll-fade, 24px)",jf=new WeakSet;function Gf(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 Kf(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":qf),t.style.setProperty("--persona-fade-r",s<=1?"0px":qf)}function Bd(t){jf.has(t)||(jf.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Kf(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Kf)}var{setLoader:UA,load:HC,provide:qA,getSync:RC}=je({fallbackImport:()=>import("./client-stream-42FOI3EC.js")});var Tr=HC;var Yf=RC;var{setLoader:GA,load:WC}=je({fallbackImport:()=>import("./webmcp-runtime-V6ZWW3PI.js")});var Qf=WC;var BC="agent_",DC="flow_";function Xf(t){return t.startsWith(BC)?{kind:"agentId",agentId:t}:t.startsWith(DC)?{kind:"flowId",flowId:t}:null}function Jf(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 p=Xf(c);if(p)return p;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let u=e?.[l];if(!u)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:u(c).payload}}let s=Xf(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 bl(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function hs(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function Zf(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var OC=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),_C=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),FC=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=OC(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:_C(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},Dd=(t,e)=>{let n=[],o=[],s=[],i="",l,c=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:i,toolCalls:o},{role:"tool",content:"",createdAt:i,toolResults:s}),o=[],s=[])};for(let u of t){let p=FC(u);if(p){let y=u.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(y===void 0||y!==l)&&c(),o.length===0&&(i=u.createdAt,l=y),o.some(h=>h.toolCallId===p.call.toolCallId)||(o.push(p.call),s.push(p.result));continue}let g=e(u);g&&(c(),n.push(g))}return c(),n};var{setLoader:eM,load:NC,provide:tM}=je({fallbackImport:()=>import("./client-history-GOZWBDA5.js")});var fo=NC;var VC="https://api.runtype.com/v1/dispatch",bt=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},eh=t=>"reason"in t?t.reason:void 0,$C="The identity proof was rejected",Od=(t,e)=>t instanceof bt&&t.code===e,_d=t=>t.voiceCaption?!1:!!(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),th=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),nh=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function zC(t){switch(t){case"json":return Qm;case"regex-json":return Ym;case"xml":return Xm;default:return Gm}}var vi=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.#h=null;this.clientSession=null;this.#p=null;this.#S=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#n=null;this.#x=!1;this.#R=!1;this.#G=!1;this.#D=null;this.#$=new Set;this.#r=new Set;this.webMcpBridge=null;this.#l=null;this.#q=null;this.#me=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.#e=e.apiUrl??VC,this.#o={"Content-Type":"application/json","X-Persona-Version":ps,...e.headers},this.debug=!!e.debug,this.#m=e.streamParser??zC(e.parserType),this.#t=e.contextProviders??[],this.#i=e.requestMiddleware,this.#s=e.customFetch,this.#a=e.parseSSEEvent,this.#v=e.getHeaders,e.webmcp?.enabled===!0&&(this.#l=this.#A(e.webmcp))}#e;#o;#m;#t;#i;#s;#a;#v;#c;#h;#p;#S;#n;#x;#R;#G;#D;#$;#r;#l;#f;#A(e){return Qf().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Nm,getToolDisplayTitle:Ka,loadPolyfill:$m});return this.#f!==void 0&&o.setConfirmHandler(this.#f),this.webMcpBridge=o,o}).catch(n=>(this.#l=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#P(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#l||(this.#l=this.#A(this.config.webmcp)),this.#l)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#f=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.#P().then(s=>s?s.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#u(){let{agentId:e,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:e,flowId:n};let i=Jf(o,s);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#u().agentId)}#d(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||tf}#M(e){return`${this.#d()}/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 bt("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.#d()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),u=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":ps,"X-Visitor-Token":i},signal:e.signal});if(u.status===401&&!o){o=!0;let p=await fo();n=await p.recoverFromUnauthorized(this.#I(),await p.readErrorCode(this.#I(),u),null,!0);continue}if(!u.ok)throw await(await fo()).historyErrorFor(this.#I(),u,!0);return u}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#p||e&&new Date<e.expiresAt||this.#S===e?null:(this.#S=e,this.initSession().catch(()=>null))}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.#p)return this.#p;let e=this.#p=this.#re().then(n=>this.#p!==e?this.initSession():(this.clientSession=n,this.#S=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#p===e&&(this.#p=null)});return e}#C(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#x}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#y(){if(!this.#x){this.#z({state:"unavailable",reason:"history_disabled"}),this.#x=!0,!this.#R&&typeof console<"u"&&(this.#R=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#r])e(!1)}}getHistoryIdentityStatus(){return this.#D??this.#L()}subscribeHistoryIdentityStatus(e){return this.#$.add(e),()=>{this.#$.delete(e)}}subscribeHistoryAvailability(e){return this.#r.add(e),this.#x&&e(!1),()=>{this.#r.delete(e)}}#L(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#x?{state:"unavailable",reason:"history_disabled"}:this.#oe():{state:"unavailable",reason:"ineligible_mode"}}#oe(){let e=this.#D;return e?.state==="browser_only"?e:this.#Y()}#Y(){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"}}#z(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&eh(n)===eh(e);if(this.#D=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.#$])s(e)}}async#w(e){let n=this.#C()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.#u(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,u={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.#M("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(u),signal:e.signal});if(!p.ok){let y=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&y.error==="visitor_history_disabled"){if(this.#y(),c)throw new bt("history_disabled","Visitor history is disabled for this surface");return this.#w({...e,omitVisitorFields:!0})}throw p.status===403&&y.error==="durable_recovery_disabled"?new bt("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&y.error==="visitor_required"?new bt("visitor_required","Visitor credential no longer resolves"):c&&p.status===404?new bt("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${y.hint||y.error}`):p.status===403?new Error(`Origin not allowed: ${y.hint||y.error}`):new Error(y.error||"Failed to initialize session")}let g=await p.json();return g.visitor?.token&&await this.historyInternals.visitorStore?.set(g.visitor.token),{sessionId:g.sessionId,expiresAt:new Date(g.expiresAt),flow:g.flow,...g.conversationId?{conversationId:g.conversationId}:{},...g.targetId?{targetId:g.targetId}:{},...g.conversationRevision?{conversationRevision:g.conversationRevision}:{},...g.durableRecovery?{durableRecovery:g.durableRecovery}:{},...g.visitor?{visitor:g.visitor}:{},config:{welcomeMessage:g.config.welcomeMessage,placeholder:g.config.placeholder,theme:g.config.theme}}}async#re(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#C()&&!n)return this.#W(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.#w({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#O(s,e,!1)}catch(s){if(!Od(s,"not_found")&&!Od(s,"visitor_required")&&!Od(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(e,!0)}return this.#W(e,!1)}async#W(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#V(e,n)):this.#V(e,n)}async#V(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.#w({storedSessionId:o}),i=await this.#ge(s);return this.#O(i,e,n)}async#ue(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.#w({storedSessionId:n,identityProof:e}),i=this.#O(s,o,!1);return this.clientSession=i,this.#p=null,this.#S=!1,this.resetClientToolsFingerprint(),i}async#ge(e){if(!e.visitor?.token||this.#G||!this.#C()&&e.durableRecovery?.enabled!==!0)return e;this.#G=!0;try{return await this.#w({storedSessionId:e.sessionId})}catch{return e}finally{this.#G=!1}}#O(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}#U(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.#S=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#C())throw new bt("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 bt("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.#w({conversationId:e,identityProof:o});return this.#U(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#w({});return this.#U(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#C()&&this.#z(this.#Y())}clearClientSession(){this.clientSession=null,this.#p=null,this.#S=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#n=null}#Q(){return`${this.#d()}/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.#Q(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},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.#S=!1,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()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async#ae(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let s,i;try{let l=Promise.resolve().then(()=>o());s=e?await Promise.race([l,new Promise((c,u)=>{i=()=>u(e.reason),e.addEventListener("abort",i,{once:!0}),e.aborted&&i()})]):await l}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{i&&e?.removeEventListener("abort",i)}if(typeof s!="string"||!s.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:s}}#q;#B(){let e=this;return this.#q??={get config(){return e.config},headers:this.#o,getHeaders:this.#v,debug:this.debug,clientApiBase:()=>e.#d(),getClientApiUrl:n=>e.#M(n),getWebMcpBridge:()=>e.#P(),sendWithClientToolsDiff:(n,o,s,i)=>e.#se(n,o,s,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#me;#I(){let e=this;return this.#me??={HistoryClientError:bt,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#d(),setHistoryIdentityStatus:n=>e.#z(n),browserOnlyStatus:()=>e.#oe(),derivedBrowserOnly:()=>e.#Y(),reinitWithProof:n=>e.#ue(n),isHistoryCapable:()=>e.#C(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await fo()).listConversations(this.#I(),e)}async getConversation(e,n){return(await fo()).getConversation(this.#I(),e,n)}async finalizeDisplayProjections(e,n){return(await fo()).finalizeDisplayProjections(this.#I(),e,n)}async deleteConversation(e,n){return(await fo()).deleteConversation(this.#I(),e,n)}async deleteAllConversations(e){return(await fo()).deleteAllConversations(this.#I(),e)}async resetVisitor(){return(await fo()).resetVisitor(this.#I())}async dispatch(e,n){return e.signal?.throwIfAborted(),Tr().catch(()=>{}),this.isClientTokenMode()?this.#fe(e,n):this.isAgentMode()?this.#le(e,n):this.#he(e,n)}async#fe(e,n){let o=Zf();this.#h=o;let s=()=>this.#h===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=()=>{if(e.signal?.throwIfAborted(),!s())throw new DOMException("Turn superseded","AbortError")},c=this.clientSession??await this.initSession();l();let u=async()=>{l();let L=c,k=L.durableRecovery?.enabled===!0;if(k&&(!L.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");l();let R=await this.#w({...k||this.#C()?{conversationId:L.conversationId,durableResume:k}:{storedSessionId:L.sessionId},signal:e.signal});if(l(),L.conversationId&&R.conversationId!==L.conversationId||k&&R.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");c=this.#O(R,L.conversationId??null,!1),this.clientSession=c,this.#S=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await u();let p=await this.#F(e.messages),g=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,y=this.#C(),h={sessionId:c.sessionId,messages:e.messages.filter(_d).map(L=>{let k=y?gi(L):void 0;return{id:L.id,role:L.role,content:L.contentParts??L.llmContent??L.rawContent??L.content,...k!==void 0&&{displayContent:k}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},C=async()=>{l();let L=c.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return l(),this.#se(c.sessionId,p.clientTools,async k=>{l();let R=await this.#ae(e.signal);l();let B={...h,sessionId:c.sessionId,...k,...R&&{identityProof:R}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...B,...R&&{identityProof:{provider:R.provider,token:"[REDACTED]"}}}),fetch(this.#M("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps,...L?{"X-Visitor-Token":L}:{}},body:JSON.stringify(B),signal:e.signal})})},E=await C();if(l(),E.response.status===401){let L=await E.response.clone().json().catch(()=>null);l(),L?.error==="Session not found or expired"&&(await u(),E=await C(),l())}let{response:A,commit:I}=E;if(!A.ok){let L=await A.json().catch(()=>({error:"Chat request failed"}));if(A.status===401&&L.error==="invalid_identity_proof"){let R=new bt("invalid_identity_proof",$C);throw i({type:"error",error:R}),R}if(A.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let R=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:R}),R}if(A.status===429){let R=new Error(L.hint||"Message limit reached for this session.");throw i({type:"error",error:R}),R}if(A.status===410&&L.error==="conversation_deleted"){let R=new bt("conversation_deleted","This conversation was deleted");throw i({type:"error",error:R}),R}let k=new Error(L.error||"Failed to send message");throw i({type:"error",error:k}),k}if(!A.body){let L=new Error("No response body received");throw i({type:"error",error:L}),L}I(),i({type:"status",status:"connected"});try{await this.#X(A.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 bt)&&!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&i({type:"error",error:c}),c}}async#he(e,n){n({type:"status",status:"connecting"});let o=await this.#F(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.#o};if(this.#v)try{let l=await this.#v();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#s)try{i=await this.#s(this.#e,{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.#e,{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.#X(i.body,n)}finally{n({type:"status",status:"idle"})}}async#le(e,n){n({type:"status",status:"connecting"});let o=await this.#b(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.#o};if(this.#v)try{let l=await this.#v();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#s)try{i=await this.#s(this.#e,{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.#e,{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.#X(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.#X(e,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){return(await Tr()).resolveApproval(this.#B(),e,n)}async#se(e,n,o,s){let i=!!(n&&n.length>0),l=i?Vm(n):void 0,c=this.clientToolsFingerprintSessionId===e,u=i&&c&&this.lastSentClientToolsFingerprint===l,p=!i&&s?.emptyMeansReplace===!0&&this.#n===e,g=!1,y;for(let h=0;;h++){if(y=await o({...i&&(g||!u)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),y.status===409&&h===0&&i&&(await y.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:y,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.#n=e:p&&(this.#n=null)}}}async resumeFlow(e,n,o){return(await Tr()).resumeFlow(this.#B(),e,n,o)}#ce(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#_(e){let n={};this.#t.length&&await Promise.all(this.#t.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.#ce(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#E(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}#T(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#b(e,n){let o=this.#u().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=Dd(th(e),p=>_d(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?nh(p):null),i=this.#E(n),l={agent:this.#T(this.config.agent??{agentId:o},i),messages:s,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};i&&(l.composerOptions=i);let c=[...Md(this.config),...await(await this.#P())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let u=await this.#_(e);return u&&(l.context=u),l}async#F(e,n){let o=Dd(th(e),p=>_d(p)?nh(p):null),s=this.#u(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[p,g]of Object.entries(s.targetPayload))p!=="messages"&&(i[p]=g);let l=[...Md(this.config),...await(await this.#P())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#_(e);c&&(i.context=c);let u=this.#E(n);if(u&&(i.composerOptions=u),this.#i)try{let p=await this.#i({payload:{...i},config:this.config});if(p&&typeof p=="object"){let g=p;return i.clientTools!==void 0&&!("clientTools"in g)&&(g.clientTools=i.clientTools),g}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return i}async#X(e,n,o,s){let{streamResponse:i}=Yf()??await Tr();return i({config:()=>this.config,createStreamParser:this.#m,parseSSEEvent:this.#a,onSSEEvent:(l,c)=>this.#c?.(l,c)},e,n,o,s)}};var{setLoader:yM,load:UC,provide:bM,getSync:qC}=je({fallbackImport:()=>import("./ui-extras-entry-WAYFKVNW.js")});var vl=UC;var Fd=qC;var{setLoader:wM,load:jC,provide:SM,getSync:KC}=je({fallbackImport:()=>import("./session-actions-ISSKSI66.js")});var Nd=jC;var oh=KC;var GC=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function YC(t){let e=t?.text?.trim()??"";return e?vf(GC(t),e):""}function rh(t){let e=YC(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[zo(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
1
+ import{a as Nm,b as Ka,d as is,e as Vm,f as Ga,g as $m,h as Of,i as _f,m as Ff,n as ms,o as go}from"./chunk-QRKGQPU7.js";import{a as nl}from"./chunk-4HPTPUC6.js";import{b as gi,c as Pd,e as Ef,f as Tf,g as kf}from"./chunk-J4J3Y2P2.js";import{A as ff,B as hf,C as yf,D as Id,E as Uo,F as Mr,G as bf,H as qn,I as ol,J as rl,K as vf,L as sl,M as gs,N as il,O as al,P as ll,Q as Cf,R as Af,S as Mf,T as Rd,a as Sr,b as Pm,c as Lm,d as Im,e as Hm,f as Rm,g as xr,h as Wm,i as Bm,j as Dm,k as Ua,l as $o,m as rs,n as qa,o as Ar,p as Om,q as ja,r as ui,s as wd,t as df,u as pf,v as uf,w as Cn,x as gf,y as mf,z as Ld}from"./chunk-T7QM7YMF.js";import{a as je,c as _m,d as Fm,e as se}from"./chunk-ZC66NAIR.js";import{a as tl,c as sf,d as zo,f as us,g as kd,i as af,j as lf,k as cf}from"./chunk-S6PBWE75.js";import{a as pl,b as Bf,c as Bd,d as mi,e as ul,f as fi,g as gl,h as hi,i as Df,j as yi}from"./chunk-CPVD5P5B.js";import{a as Pf,b as Lf,c as uo,d as Er,e as If,f as Hf,g as Rf,h as Wd,i as Wf}from"./chunk-VK6JOIYJ.js";import{a as Qa,b as jm,c as as,d as xd,e as Td}from"./chunk-K6HKIP5K.js";import{c as cs,d as tf,j as nf,k as Md}from"./chunk-K7NA7G7J.js";import{a as gt,b as Dt,d as rf}from"./chunk-2ANTRKTV.js";import{a as Ed,d as el,e as of,f as ds}from"./chunk-TR2H475E.js";import{b as zm,c as Ya,d as Um,e as Sd,f as qm,g as ls,h as Km,i as Gm,j as Ym,k as Qm,l as Xa,m as Ja,n as Ad,o as Za,q as Xm,r as Jm,s as Zm,t as ef}from"./chunk-NQLDCJAP.js";import{a as ps}from"./chunk-AALCT54S.js";import{a as wf,b as cl,c as Hd,d as Sf}from"./chunk-HGUCGM3K.js";import{b as dl}from"./chunk-Q735PSZL.js";import{a as yt}from"./chunk-7NQ4ZTHF.js";import{a as P,c as Y,d as ss}from"./chunk-76IELU7F.js";import{a as xf}from"./chunk-UPO4GUFC.js";import{Circle as PC,Clock as LC}from"lucide";import{ChevronDown as xC,ChevronUp as AC}from"lucide";var MC=["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"],EC="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",TC="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",kC=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ml=(t,e)=>{let n=P("div",["persona-message-bubble",t,...MC].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},fl=t=>{let e=P("button",t.expandable?EC:TC);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},Dd=(t,e,n)=>{t.innerHTML="";let o=yt(e?AC:xC,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},fs=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=P("div","persona-flex persona-items-center");Dd(o,n.expanded,n.iconColor);let s=P("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},hl=t=>{let e=P("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?.();kC(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},yl=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&Dd(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"},bl=(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 u=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");u&&Dd(u,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};function vl(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return{...t,features:{...t?.features,[n]:{...e==="tool"?$o:rs,...t?.future?.v5Defaults===!0?qa.features?.[n]:{},...t?.features?.[n]}}}}function qo(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return t?.features?.[n]?.variant??(t?.future?.v5Defaults?"row":"card")}function bi(t){let e=Math.max(0,Math.floor((t??0)/1e3));return e<1?"a moment":e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function mo(t,e,n,o){if(qo(n,o)!=="row")return t;t.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,t.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(t.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let s=t.querySelector(":scope > button");if(!s)return t;s.className="persona-activity-header";let i=o==="tool"?e.toolCall:e.reasoning,l=i?.status!=="complete",c=e.approval?.status??e.toolCall?.approvalStatus,u=c==="denied"?"denied":c==="pending"?"awaiting-approval":e.toolCall?.success===!1?"error":l?i?.status==="pending"?"pending":"running":"done";t.dataset.activityState=u;let p=P("span","persona-activity-icon");p.dataset.activityIcon=u;let g={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},y=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,h=y?se(y,16,"currentColor",2):u==="pending"?yt(PC,16,"currentColor",2):u==="awaiting-approval"?yt(LC,16,"currentColor",2):se(g[u],16,"currentColor",2);h&&p.appendChild(h),s.querySelector(".persona-reasoning-header-icon")?.remove();let C=o==="tool"?"toolCallDisplay":"reasoningDisplay",E=n.features?.[C]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((E==="always"||E==="active"&&u!=="done")&&s.prepend(p),o==="tool"&&i){let k=P("span","persona-activity-duration");l&&i.startedAt&&k.setAttribute("data-tool-elapsed",String(i.startedAt));let R=(o==="tool"?e.toolCall?.duration:void 0)??i.durationMs??(i.completedAt!==void 0&&i.startedAt!==void 0?i.completedAt-i.startedAt:void 0);k.textContent=R===void 0?"":bi(R),s.appendChild(k)}s.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),s.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let L=t.querySelector(":scope > .persona-border-t");return L?.classList.add("persona-activity-body"),L&&(L.id=`activity-details-${e.id}`,s.setAttribute("aria-controls",L.id)),t}function Nf(t){let e=new Set,n=new Set,o=new Set,s=new Map,i=l=>{clearTimeout(s.get(l)),s.delete(l)};return{observe(l,c,u,p={}){let g=c==="tool"?l.toolCall:l.reasoning;if(!(!g||n.has(l.id))&&(!e.has(l.id)&&g.status!=="complete"&&g.chunks?.some(Boolean)&&(e.add(l.id),p.autoExpand!==!1&&u.add(l.id)),e.has(l.id)&&g.status==="complete"&&!o.has(l.id))){if(o.add(l.id),p.autoCollapseDelay===!1)return;s.set(l.id,setTimeout(()=>{s.delete(l.id),u.delete(l.id),t(l.id,c)},p.autoCollapseDelay??1e3))}},manual(l){n.add(l),i(l)},prune(l){for(let c of new Set([...e,...n,...o]))l.has(c)||(i(c),e.delete(c),n.delete(c),o.delete(c))},clear(){for(let l of s.keys())i(l);e.clear(),n.clear(),o.clear()}}}function Vf(t,e,n,o){let s=P("div","");s.id=`bubble-${t.id}`,s.dataset.messageId=t.id;let i=P("button","");i.type="button",i.dataset.expandHeader="true",i.dataset.bubbleType="tool",i.setAttribute("aria-expanded",String(n));let l=P("div","");typeof o=="string"?l.textContent=o:l.appendChild(o),fs(i,l,{expandable:!0,expanded:n,iconColor:e.toolCall?.toggleTextColor||e.toolCall?.headerTextColor||"currentColor",metaGap:!0});let c=P("div","persona-border-t");return c.id=`activity-details-${t.id}`,c.style.display=n?"":"none",i.setAttribute("aria-controls",c.id),s.append(i,c),mo(s,t,{...e,features:{...e.features,toolCallDisplay:{...e.features?.toolCallDisplay,variant:"row"}}},"tool"),s.dataset.personaToolGroup="true",e.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(s.dataset.activityGroupShimmer="true"),{bubble:s,body:c}}function $f(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function Ot(t){return t?.type==="runtype"||t?.type==="custom"}var IC=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function zf(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:IC()}catch{return!1}}var Uf=/^\s*\|?[\s:|-]*-[\s:|-]*$/,qf=t=>t.includes("|"),jf=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())},HC=t=>`| ${t.join(" | ")} |`,RC=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,WC=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Kf=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(!qf(s)||Uf.test(s)||!Uf.test(i))continue;let l=jf(s).length;if(l<1)continue;let c=RC(l);e[o+1]!==c&&(e[o+1]=c,n=!0);let u=o+2;for(;u<e.length;u++){let p=e[u];if(p.trim()===""||!qf(p))break;let g=HC(WC(jf(p),l));e[u]!==g&&(e[u]=g,n=!0)}o=u-1}return n?e.join(`
3
+ `):t};var Gf="var(--persona-md-table-scroll-fade, 24px)",Yf=new WeakSet;function Xf(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 Qf(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":Gf),t.style.setProperty("--persona-fade-r",s<=1?"0px":Gf)}function Od(t){Yf.has(t)||(Yf.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Qf(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Qf)}var{setLoader:GA,load:BC,provide:YA,getSync:DC}=je({fallbackImport:()=>import("./client-stream-N22JHTLE.js")});var Tr=BC;var Jf=DC;var{setLoader:JA,load:OC}=je({fallbackImport:()=>import("./webmcp-runtime-V6ZWW3PI.js")});var Zf=OC;var _C="agent_",FC="flow_";function eh(t){return t.startsWith(_C)?{kind:"agentId",agentId:t}:t.startsWith(FC)?{kind:"flowId",flowId:t}:null}function th(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 p=eh(c);if(p)return p;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let u=e?.[l];if(!u)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:u(c).payload}}let s=eh(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 Cl(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function hs(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function nh(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var NC=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),VC=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),$C=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=NC(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:VC(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},_d=(t,e)=>{let n=[],o=[],s=[],i="",l,c=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:i,toolCalls:o},{role:"tool",content:"",createdAt:i,toolResults:s}),o=[],s=[])};for(let u of t){let p=$C(u);if(p){let y=u.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(y===void 0||y!==l)&&c(),o.length===0&&(i=u.createdAt,l=y),o.some(h=>h.toolCallId===p.call.toolCallId)||(o.push(p.call),s.push(p.result));continue}let g=e(u);g&&(c(),n.push(g))}return c(),n};var{setLoader:rM,load:zC,provide:sM}=je({fallbackImport:()=>import("./client-history-LV3KHEFA.js")});var fo=zC;var UC="https://api.runtype.com/v1/dispatch",bt=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},oh=t=>"reason"in t?t.reason:void 0,qC="The identity proof was rejected",Fd=(t,e)=>t instanceof bt&&t.code===e,Nd=t=>t.voiceCaption?!1:!!(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),rh=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),sh=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function jC(t){switch(t){case"json":return Zm;case"regex-json":return Jm;case"xml":return ef;default:return Xm}}var vi=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.#h=null;this.clientSession=null;this.#p=null;this.#S=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#t=null;this.#x=!1;this.#R=!1;this.#G=!1;this.#D=null;this.#$=new Set;this.#r=new Set;this.webMcpBridge=null;this.#l=null;this.#q=null;this.#me=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.#e=e.apiUrl??UC,this.#o={"Content-Type":"application/json","X-Persona-Version":ps,...e.headers},this.debug=!!e.debug,this.#m=e.streamParser??jC(e.parserType),this.#n=e.contextProviders??[],this.#i=e.requestMiddleware,this.#s=e.customFetch,this.#a=e.parseSSEEvent,this.#v=e.getHeaders,e.webmcp?.enabled===!0&&(this.#l=this.#A(e.webmcp))}#e;#o;#m;#n;#i;#s;#a;#v;#c;#h;#p;#S;#t;#x;#R;#G;#D;#$;#r;#l;#f;#A(e){return Zf().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:zm,getToolDisplayTitle:Ya,loadPolyfill:qm});return this.#f!==void 0&&o.setConfirmHandler(this.#f),this.webMcpBridge=o,o}).catch(n=>(this.#l=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#P(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#l||(this.#l=this.#A(this.config.webmcp)),this.#l)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#f=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.#P().then(s=>s?s.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#u(){let{agentId:e,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:e,flowId:n};let i=th(o,s);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#u().agentId)}#d(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||rf}#M(e){return`${this.#d()}/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 bt("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.#d()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),u=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":ps,"X-Visitor-Token":i},signal:e.signal});if(u.status===401&&!o){o=!0;let p=await fo();n=await p.recoverFromUnauthorized(this.#I(),await p.readErrorCode(this.#I(),u),null,!0);continue}if(!u.ok)throw await(await fo()).historyErrorFor(this.#I(),u,!0);return u}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#p||e&&new Date<e.expiresAt||this.#S===e?null:(this.#S=e,this.initSession().catch(()=>null))}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.#p)return this.#p;let e=this.#p=this.#re().then(n=>this.#p!==e?this.initSession():(this.clientSession=n,this.#S=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#p===e&&(this.#p=null)});return e}#C(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#x}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#y(){if(!this.#x){this.#z({state:"unavailable",reason:"history_disabled"}),this.#x=!0,!this.#R&&typeof console<"u"&&(this.#R=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#r])e(!1)}}getHistoryIdentityStatus(){return this.#D??this.#L()}subscribeHistoryIdentityStatus(e){return this.#$.add(e),()=>{this.#$.delete(e)}}subscribeHistoryAvailability(e){return this.#r.add(e),this.#x&&e(!1),()=>{this.#r.delete(e)}}#L(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#x?{state:"unavailable",reason:"history_disabled"}:this.#oe():{state:"unavailable",reason:"ineligible_mode"}}#oe(){let e=this.#D;return e?.state==="browser_only"?e:this.#Y()}#Y(){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"}}#z(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&oh(n)===oh(e);if(this.#D=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.#$])s(e)}}async#w(e){let n=this.#C()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.#u(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,u={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.#M("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(u),signal:e.signal});if(!p.ok){let y=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&y.error==="visitor_history_disabled"){if(this.#y(),c)throw new bt("history_disabled","Visitor history is disabled for this surface");return this.#w({...e,omitVisitorFields:!0})}throw p.status===403&&y.error==="durable_recovery_disabled"?new bt("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&y.error==="visitor_required"?new bt("visitor_required","Visitor credential no longer resolves"):c&&p.status===404?new bt("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${y.hint||y.error}`):p.status===403?new Error(`Origin not allowed: ${y.hint||y.error}`):new Error(y.error||"Failed to initialize session")}let g=await p.json();return g.visitor?.token&&await this.historyInternals.visitorStore?.set(g.visitor.token),{sessionId:g.sessionId,expiresAt:new Date(g.expiresAt),flow:g.flow,...g.conversationId?{conversationId:g.conversationId}:{},...g.targetId?{targetId:g.targetId}:{},...g.conversationRevision?{conversationRevision:g.conversationRevision}:{},...g.durableRecovery?{durableRecovery:g.durableRecovery}:{},...g.visitor?{visitor:g.visitor}:{},config:{welcomeMessage:g.config.welcomeMessage,placeholder:g.config.placeholder,theme:g.config.theme}}}async#re(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#C()&&!n)return this.#W(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.#w({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#O(s,e,!1)}catch(s){if(!Fd(s,"not_found")&&!Fd(s,"visitor_required")&&!Fd(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(e,!0)}return this.#W(e,!1)}async#W(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#V(e,n)):this.#V(e,n)}async#V(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.#w({storedSessionId:o}),i=await this.#ge(s);return this.#O(i,e,n)}async#ue(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.#w({storedSessionId:n,identityProof:e}),i=this.#O(s,o,!1);return this.clientSession=i,this.#p=null,this.#S=!1,this.resetClientToolsFingerprint(),i}async#ge(e){if(!e.visitor?.token||this.#G||!this.#C()&&e.durableRecovery?.enabled!==!0)return e;this.#G=!0;try{return await this.#w({storedSessionId:e.sessionId})}catch{return e}finally{this.#G=!1}}#O(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}#U(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.#S=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#C())throw new bt("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 bt("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.#w({conversationId:e,identityProof:o});return this.#U(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#w({});return this.#U(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#C()&&this.#z(this.#Y())}clearClientSession(){this.clientSession=null,this.#p=null,this.#S=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#t=null}#Q(){return`${this.#d()}/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.#Q(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},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.#S=!1,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()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async#ae(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let s,i;try{let l=Promise.resolve().then(()=>o());s=e?await Promise.race([l,new Promise((c,u)=>{i=()=>u(e.reason),e.addEventListener("abort",i,{once:!0}),e.aborted&&i()})]):await l}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{i&&e?.removeEventListener("abort",i)}if(typeof s!="string"||!s.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:s}}#q;#B(){let e=this;return this.#q??={get config(){return e.config},headers:this.#o,getHeaders:this.#v,debug:this.debug,clientApiBase:()=>e.#d(),getClientApiUrl:n=>e.#M(n),getWebMcpBridge:()=>e.#P(),sendWithClientToolsDiff:(n,o,s,i)=>e.#se(n,o,s,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#me;#I(){let e=this;return this.#me??={HistoryClientError:bt,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#d(),setHistoryIdentityStatus:n=>e.#z(n),browserOnlyStatus:()=>e.#oe(),derivedBrowserOnly:()=>e.#Y(),reinitWithProof:n=>e.#ue(n),isHistoryCapable:()=>e.#C(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await fo()).listConversations(this.#I(),e)}async getConversation(e,n){return(await fo()).getConversation(this.#I(),e,n)}async finalizeDisplayProjections(e,n){return(await fo()).finalizeDisplayProjections(this.#I(),e,n)}async deleteConversation(e,n){return(await fo()).deleteConversation(this.#I(),e,n)}async deleteAllConversations(e){return(await fo()).deleteAllConversations(this.#I(),e)}async resetVisitor(){return(await fo()).resetVisitor(this.#I())}async dispatch(e,n){return e.signal?.throwIfAborted(),Tr().catch(()=>{}),this.isClientTokenMode()?this.#fe(e,n):this.isAgentMode()?this.#le(e,n):this.#he(e,n)}async#fe(e,n){let o=nh();this.#h=o;let s=()=>this.#h===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=()=>{if(e.signal?.throwIfAborted(),!s())throw new DOMException("Turn superseded","AbortError")},c=this.clientSession??await this.initSession();l();let u=async()=>{l();let L=c,k=L.durableRecovery?.enabled===!0;if(k&&(!L.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");l();let R=await this.#w({...k||this.#C()?{conversationId:L.conversationId,durableResume:k}:{storedSessionId:L.sessionId},signal:e.signal});if(l(),L.conversationId&&R.conversationId!==L.conversationId||k&&R.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");c=this.#O(R,L.conversationId??null,!1),this.clientSession=c,this.#S=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await u();let p=await this.#F(e.messages),g=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,y=this.#C(),h={sessionId:c.sessionId,messages:e.messages.filter(Nd).map(L=>{let k=y?gi(L):void 0;return{id:L.id,role:L.role,content:L.contentParts??L.llmContent??L.rawContent??L.content,...k!==void 0&&{displayContent:k}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"},...e.voiceSpoken&&{voice:{spoken:!0}}},C=async()=>{l();let L=c.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return l(),this.#se(c.sessionId,p.clientTools,async k=>{l();let R=await this.#ae(e.signal);l();let B={...h,sessionId:c.sessionId,...k,...R&&{identityProof:R}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...B,...R&&{identityProof:{provider:R.provider,token:"[REDACTED]"}}}),fetch(this.#M("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps,...L?{"X-Visitor-Token":L}:{}},body:JSON.stringify(B),signal:e.signal})})},E=await C();if(l(),E.response.status===401){let L=await E.response.clone().json().catch(()=>null);l(),L?.error==="Session not found or expired"&&(await u(),E=await C(),l())}let{response:A,commit:I}=E;if(!A.ok){let L=await A.json().catch(()=>({error:"Chat request failed"}));if(A.status===401&&L.error==="invalid_identity_proof"){let R=new bt("invalid_identity_proof",qC);throw i({type:"error",error:R}),R}if(A.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let R=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:R}),R}if(A.status===429){let R=new Error(L.hint||"Message limit reached for this session.");throw i({type:"error",error:R}),R}if(A.status===410&&L.error==="conversation_deleted"){let R=new bt("conversation_deleted","This conversation was deleted");throw i({type:"error",error:R}),R}let k=new Error(L.error||"Failed to send message");throw i({type:"error",error:k}),k}if(!A.body){let L=new Error("No response body received");throw i({type:"error",error:L}),L}I(),i({type:"status",status:"connected"});try{await this.#X(A.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 bt)&&!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&i({type:"error",error:c}),c}}async#he(e,n){n({type:"status",status:"connecting"});let o=await this.#F(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.#o};if(this.#v)try{let l=await this.#v();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#s)try{i=await this.#s(this.#e,{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.#e,{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.#X(i.body,n)}finally{n({type:"status",status:"idle"})}}async#le(e,n){n({type:"status",status:"connecting"});let o=await this.#b(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.#o};if(this.#v)try{let l=await this.#v();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#s)try{i=await this.#s(this.#e,{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.#e,{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.#X(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.#X(e,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){return(await Tr()).resolveApproval(this.#B(),e,n)}async#se(e,n,o,s){let i=!!(n&&n.length>0),l=i?Um(n):void 0,c=this.clientToolsFingerprintSessionId===e,u=i&&c&&this.lastSentClientToolsFingerprint===l,p=!i&&s?.emptyMeansReplace===!0&&this.#t===e,g=!1,y;for(let h=0;;h++){if(y=await o({...i&&(g||!u)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),y.status===409&&h===0&&i&&(await y.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:y,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.#t=e:p&&(this.#t=null)}}}async resumeFlow(e,n,o){return(await Tr()).resumeFlow(this.#B(),e,n,o)}#ce(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#_(e){let n={};this.#n.length&&await Promise.all(this.#n.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.#ce(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#E(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}#T(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#b(e,n){let o=this.#u().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=_d(rh(e),p=>Nd(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?sh(p):null),i=this.#E(n),l={agent:this.#T(this.config.agent??{agentId:o},i),messages:s,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};i&&(l.composerOptions=i);let c=[...Td(this.config),...await(await this.#P())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let u=await this.#_(e);return u&&(l.context=u),l}async#F(e,n){let o=_d(rh(e),p=>Nd(p)?sh(p):null),s=this.#u(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[p,g]of Object.entries(s.targetPayload))p!=="messages"&&(i[p]=g);let l=[...Td(this.config),...await(await this.#P())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#_(e);c&&(i.context=c);let u=this.#E(n);if(u&&(i.composerOptions=u),this.#i)try{let p=await this.#i({payload:{...i},config:this.config});if(p&&typeof p=="object"){let g=p;return i.clientTools!==void 0&&!("clientTools"in g)&&(g.clientTools=i.clientTools),g}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return i}async#X(e,n,o,s){let{streamResponse:i}=Jf()??await Tr();return i({config:()=>this.config,createStreamParser:this.#m,parseSSEEvent:this.#a,onSSEEvent:(l,c)=>this.#c?.(l,c)},e,n,o,s)}};var{setLoader:wM,load:KC,provide:SM,getSync:GC}=je({fallbackImport:()=>import("./ui-extras-entry-WAYFKVNW.js")});var wl=KC;var Vd=GC;var{setLoader:MM,load:YC,provide:EM,getSync:QC}=je({fallbackImport:()=>import("./session-actions-ISSKSI66.js")});var $d=YC;var ih=QC;var XC=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function JC(t){let e=t?.text?.trim()??"";return e?Sf(XC(t),e):""}function ah(t){let e=JC(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[zo(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
4
4
 
5
- `)}:{}}function Cl(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function sh(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 Vd(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 ih(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 Vd(t,n.id)?n.id:null}return null}function $d(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 zd(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 Ci=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):zd(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 wl=class{#e=null;#o=null;#m="idle";#t=new Set;#i=0;#s;constructor(e){this.#s=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#o===e?this.#m:"idle"}activeMessageId(){return this.#o}onChange(e){return this.#t.add(e),()=>this.#t.delete(e)}toggle(e,n){if(this.#o===e){if(this.#m==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#a(e,"paused")):this.stop();return}if(this.#m==="paused"){this.#e?.resume(),this.#a(e,"playing");return}if(this.#m==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.#i;this.#e?.stop(),this.#a(e,"loading");try{if(!this.#e){let s=await this.#s();if(o!==this.#i)return;if(!s){this.#a(null,"idle");return}this.#e=s}this.#e.speak(n,{onStart:()=>{o===this.#i&&this.#a(e,"playing")},onEnd:()=>{o===this.#i&&this.#a(null,"idle")},onError:()=>{o===this.#i&&this.#a(null,"idle")}})}catch{o===this.#i&&this.#a(null,"idle")}}stop(){this.#i++,this.#e?.stop(),this.#a(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#t.clear()}#a(e,n){this.#o=n==="idle"?null:e,this.#m=n;for(let o of this.#t)o(this.#o,this.#m)}};var wi=class{#e;#o=!1;start(e){this.#e=e,this.#o=!1}cancel(){this.#o=!0}accepts(e){return!this.#o&&(!e||!this.#e||e===this.#e)}};var{setLoader:HM,load:QC,getSync:XC}=je({fallbackImport:()=>import("./voice-runtime-XLU6YK2N.js")});var Si=QC,ah=XC;function Ud(t){if(!t)return"";let e=JC(t);return lh(e!==null?e:t)}function JC(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 lh(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,`
5
+ `)}:{}}function Sl(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function lh(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 zd(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 ch(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 zd(t,n.id)?n.id:null}return null}function Ud(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 qd(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 Ci=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):qd(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 xl=class{#e=null;#o=null;#m="idle";#n=new Set;#i=0;#s;constructor(e){this.#s=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#o===e?this.#m:"idle"}activeMessageId(){return this.#o}onChange(e){return this.#n.add(e),()=>this.#n.delete(e)}toggle(e,n){if(this.#o===e){if(this.#m==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#a(e,"paused")):this.stop();return}if(this.#m==="paused"){this.#e?.resume(),this.#a(e,"playing");return}if(this.#m==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.#i;this.#e?.stop(),this.#a(e,"loading");try{if(!this.#e){let s=await this.#s();if(o!==this.#i)return;if(!s){this.#a(null,"idle");return}this.#e=s}this.#e.speak(n,{onStart:()=>{o===this.#i&&this.#a(e,"playing")},onEnd:()=>{o===this.#i&&this.#a(null,"idle")},onError:()=>{o===this.#i&&this.#a(null,"idle")}})}catch{o===this.#i&&this.#a(null,"idle")}}stop(){this.#i++,this.#e?.stop(),this.#a(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#n.clear()}#a(e,n){this.#o=n==="idle"?null:e,this.#m=n;for(let o of this.#n)o(this.#o,this.#m)}};var wi=class{#e;#o=!1;start(e){this.#e=e,this.#o=!1}cancel(){this.#o=!0}accepts(e){return!this.#o&&(!e||!this.#e||e===this.#e)}};var{setLoader:DM,load:ZC,getSync:ew}=je({fallbackImport:()=>import("./voice-runtime-LVUMPUDS.js")});var Si=ZC,dh=ew;function jd(t){if(!t)return"";let e=tw(t);return ph(e!==null?e:t)}function tw(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 ph(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,`
6
6
  `),e=e.replace(/\n{2,}/g,`
7
- `),e.trim()}var ch=null;var qd=()=>ch?ch():import("./runtype-tts-entry-NFBVWR7N.js");var{setLoader:OM,load:ZC}=je({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var dh=ZC;var ew=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function tw(t,e){return ew.some(n=>t[n]!==e[n])}var jn=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function jd(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}
7
+ `),e.trim()}var uh=null;var Kd=()=>uh?uh():import("./runtype-tts-entry-NFBVWR7N.js");var{setLoader:VM,load:nw}=je({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var gh=nw;var ow=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function rw(t,e){return ow.some(n=>t[n]!==e[n])}var jn=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function Gd(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}
8
8
 
9
- _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.#e=new Map;this.abortController=null;this.#m=Date.now();this.clientSession=null;this.agentExecution=null;this.#t=null;this.#i=null;this.#s=!1;this.#a=null;this.#v=null;this.#c=null;this.artifacts=new Map;this.#h=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#p=0;this.webMcpApprovalResolvers=new Map;this.#S=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#n=null;this.#x=null;this.#R=0;this.#G=0;this.#D=!1;this.#$="disconnected";this.#r=null;this.#l=null;this.#f=null;this.#A=0;this.#P=!1;this.#u=null;this.#d=!1;this.#M=null;this.#C=new Map;this.#y=null;this.#L=new Map;this.#oe=null;this.#Y=null;this.#z=!1;this.#w=null;this.#re=null;this.#W=!1;this.#V=null;this.#O=null;this.#U=null;this.#Q=new wi;this.#ae=Promise.resolve();this.#q=null;this.#B=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new wl(()=>this.#me());this.#Ze=null;this.#j=0;this.handleEvent=e=>{let n=this.#B;if(n&&(e.type==="error"||e.type==="status"&&e.status==="error"?n.failed=!0:e.type==="message"&&e.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id))),e.type==="message"){this.upsertMessage(e.message),e.message.variant==="approval"&&e.message.approval&&e.message.approval.status!=="pending"&&this.#e.set(e.message.id,this.#o),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant==="approval"||e.message.agentMetadata?.awaitingLocalTool===!0)&&Nd().catch(()=>{});let o=e.message.toolCall,s=!!o?.name&&(Cd(o.name)||o.name===Ad&&ds(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&s&&this.#et(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.#st(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.#it()){this.#Se();return}if(this.#H(e.status),e.status==="connecting")this.#g(!0);else if(e.status==="idle"||e.status==="error"){this.#De()||this.#pe(),this.webMcpResolveControllers.size===0&&(this.#g(!1),this.abortController=null,this.#Ke(),this.#qe());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.#tt()}}else e.type==="error"?(this.#H("error"),this.#pe(),this.webMcpResolveControllers.size===0&&(this.#g(!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.#rt(e)};this.historyInternals=this.#ce(o),this.messages=[...e.initialMessages??[]].map(s=>({...s,sequence:s.sequence??this.#k()})),this.messages=this.#K(this.messages),this.client=new vi(e,this.historyInternals),this.#ke(),this.#We();for(let s of e.initialArtifacts??[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.#h=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#te(),this.callbacks.onStatusChanged(this.status),this.#ge(),this.#ue()}#e;#o;#m;#t;#i;#s;#a;#v;#c;#h;#p;#S;#n;#x;#R;#G;#D;#$;#r;#l;#f;#A;#P;#u;#d;#M;#C;#y;#L;#oe;#Y;#z;#w;#re;#W;#V;#ue(){this.config.voiceRecognition?.provider&&Si().catch(()=>{})}#ge(){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||qd().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 Nf(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#D}getVoiceStatus(){return this.#$}getVoiceDisclosure(){return this.#n?.getDisclosure?.()??null}getVoiceLevel(){return this.#n?.onLevel?this.#G:null}getVoiceInterruptionMode(){return this.#n?.getInterruptionMode?this.#n.getInterruptionMode():"none"}stopVoicePlayback(){this.#n?.stopPlayback&&(this.#Q.cancel(),this.#q?.cancel(),this.#n.stopPlayback())}isBargeInActive(){return this.#n?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#n?.deactivateBargeIn&&await this.#n.deactivateBargeIn()}#O;#U;#Q;#ae;#q;#B;#me(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Ci.isSupported()?new Ci({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 qd().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:u})=>{let p=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new u(p,n,{onFallback:g=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${g.message}`)}):p});if(l&&n)return i&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#ae,s=++this.#R;this.#x=Si().then(async i=>{await o,s===this.#R&&this.#I(i,i.createVoiceProvider(n))}).catch(i=>{console.error("Failed to setup voice:",i)}).finally(()=>{s===this.#R&&(this.#x=null)})}catch(n){console.error("Failed to setup voice:",n)}}#I(e,n){this.#n=n;let o=this;e.wireSessionVoice({session:this,provider:()=>o.#n,generation:()=>o.#R,get keyed(){return o.#q},set keyed(s){o.#q=s},get pendingUser(){return o.#O},set pendingUser(s){o.#O=s},get pendingAssistant(){return o.#U},set pendingAssistant(s){o.#U=s},turns:()=>o.#Q,busy:()=>o.#fe(),setStreaming:s=>o.#g(s),setDelegation:s=>{o.#B=s},setLevel:s=>{o.#G=s},setStatus:s=>{o.#$=s,o.#D=s==="listening"},settlePending:s=>o.#le(s)},n,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#n&&this.#x&&await this.#x,!this.#n){console.error("Voice not configured");return}if(this.#D)await this.#n.stopListening();else{this.stopSpeaking();try{await this.#n.startListening()}catch(e){console.error("Failed to start voice:",e)}}}prewarmVoice(){if(!Nt(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#R,n=()=>{let o=this.#n;!o?.prewarm||e!==this.#R||this.#D||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#n&&this.#x){this.#x.then(n,()=>{});return}n()}#fe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#s||this.status==="resuming"}cleanupVoice(){let e=this.#n!==null;if(this.#R++,this.#x=null,this.#n){let n=this.#n;this.#n=null,this.#ae=this.#he(n)}this.#D=!1,this.#$="disconnected",this.#le(!0),this.#q?.settle(),this.#q=null,this.#Q=new wi,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#he(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#le(e){let n=e?this.#O:null,o=this.#U;!n&&!o||(o&&this.#Q.cancel(),e&&(this.#O=null),this.#U=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(s=>s.id!==n&&s.id!==o?[s]:s.id===o&&!s.content.trim()?[]:[{...s,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.#g(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};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.#Y=this.historyInternals.getStoredConversationRevision?.()??null,this.#z=!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}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,e)})}setClientSession(e,n){this.clientSession=e,this.#se(e,n)}#se(e,n=!this.messages.length){if(this.#P||!e.config.welcomeMessage||!n)return;let o=this.messages[0],s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.#k()};this.#N(s)}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.#ce(e),this.client.setHistoryInternals(this.historyInternals),this.#ke()}destroy(){this.cleanupVoice(),this.#w?.(),this.#w=null,this.#re=null}#ce(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.#Ne(o),n?.(o)}}}get#_(){return this.historyInternals.historyProvider??null}#E(){let e=this.#_;if(!e)throw new jn("history_unavailable","No conversation history provider is installed");return e}#T(e){let n=this.#E(),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 el("unsupported_scope","This history scope is not supported.");return{scope:i}}getHistoryState(){return{activeConversationId:this.#r,conversationRevision:this.#l,nextMessageCursor:this.#f,recovery:this.#u,sendBlocked:this.#d}}getActiveConversationId(){return this.#r}#b(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#F(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.#M;e&&await e.catch(()=>{});let n=this.#y;n&&await n.catch(()=>{})}#X(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new jn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#E().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.#T(e?.scope)})}async openConversation(e,n){let o=this.#E();this.#X();let s=this.#T(n?.scope);await this.awaitHistorySettled();let i=++this.#A,l=await o.getPage(e,{context:s});if(i!==this.#A)throw new jn("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.#A)throw c.discard(),new jn("superseded","A later selection won");this.#P=!0;try{await this.#Ee(c)}finally{this.#P=!1}this.#r=c.conversationId||e,this.#l=c.conversationRevision||l.conversationRevision||null,this.#f=l.nextCursor,this.#u=null,this.#d=!1,this.#Te();for(let u of l.messages)this.#L.set(u.id,u.content);return this.#be(),this.hydrateMessages(l.messages),this.#b(),{summary:l.summary,nextMessageCursor:l.nextCursor}}loadOlderMessages(e,n,o){let s=this.#E(),i=this.#T(o?.scope),l=n??this.#f;if(!l)return Promise.resolve({messages:[],nextMessageCursor:null});let c=`${e} ${l}`,u=this.#C.get(c);if(u)return u;let p=this.#_e(s,e,l,i).finally(()=>{this.#C.delete(c)});return this.#C.set(c,p),p}async#_e(e,n,o,s){let i=this.messages[0]?.createdAt,l=await e.getPage(n,{cursor:o,...i?{beforeCreatedAt:i}:{},context:s});if(this.#r&&this.#r!==n)return{messages:[],nextMessageCursor:l.nextCursor};let c=Td(this.messages,l.messages);this.messages=this.#K(c.map(u=>this.#ie(u))),this.#f=l.nextCursor;for(let u of l.messages)this.#L.set(u.id,u.content);return this.historyInternals.setStoredMessageCursor?.(l.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#b(),{messages:l.messages,nextMessageCursor:l.nextCursor}}async startNewConversation(e){let n=this.#E(),o=this.#T(e?.scope);await this.awaitHistorySettled();let s=++this.#A,i=await n.prepareStartNew({context:o});if(s!==this.#A)throw i.discard(),new jn("superseded","A later action won");await this.#ye(i)}async#ye(e){this.#J(),await this.#Ee(e),this.#r=e.conversationId||null,this.#l=e.conversationRevision||null,this.#f=null,this.#u=null,this.#d=!1,this.#be(),this.#b()}async deleteConversation(e,n){let o=this.#E(),s=this.#T(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:s}),e===this.#r&&await this.#Ae(s)}async updateConversation(e,n,o){let s=this.#E();if(!s.update)throw new jn("history_unavailable","This history provider cannot update conversations");let i=this.#T(o?.scope);return await this.awaitHistorySettled(),s.update(e,n,{context:i})}canUpdateConversations(){return typeof this.#_?.update=="function"}async clearConversationHistory(e){let n=this.#E(),o=this.#T(e?.scope);await this.awaitHistorySettled();let s=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.#Ae(o),s}async resetHistoryDevice(){let e=this.#E();if(!e.resetDevice)throw new jn("history_unavailable","This history provider cannot reset the device");this.#A+=1,this.#y=null;try{return await e.resetDevice()}finally{this.#J(),this.#r=null,this.#l=null,this.#f=null,this.#u=null,this.#d=!1,this.#b()}}async#Ae(e){this.#A+=1,this.#y=null,this.#J(),this.#r=null,this.#l=null,this.#f=null,this.#d=!0,this.#u=null,this.#b(),await this.#Me(e)}async#Me(e){let n=this.#_;if(!n){this.#d=!1,this.#b();return}try{let o=await n.prepareStartNew({context:e});await this.#ye(o)}catch{this.#d=!0,this.#u="new_conversation_required",this.#b(),this.#F("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#Fe(){if(!(this.#u!=="new_conversation_required"||!this.#_)&&(this.#u=null,await this.#Me(this.#T()),this.#u==="new_conversation_required"))throw new jn("new_conversation_required","A new conversation is required before sending")}async#Ee(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.#r=e.conversationId,this.#l=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#P||this.#se(e)}#be(){this.#r?this.config.setStoredConversationId?.(this.#r):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#l),this.historyInternals.setStoredMessageCursor?.(this.#f)}#Te(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#we(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#L.clear(),this.#Z(null)}#J(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.messages=[],this.#Te(),this.#C.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#g(!1),this.#H("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Ne(e){this.#A+=1,this.#y=null,this.#d=!0,this.#J(),this.#r=e.conversationId,this.#l=null,this.#f=null,this.#u=null,this.#b(),this.#F("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#M=Promise.resolve().then(()=>{this.#d=!1,this.#M=null,this.#b()})}#ke(){let e=this.historyInternals.visitorStore??null;e!==this.#re&&(this.#w?.(),this.#w=null,this.#re=e,e&&(this.#w=e.subscribe(n=>this.#Ve(n))))}#Ve(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#A+=1,this.#y=null,this.#W=!0,this.#V=null;let n=this.messages.length>0;n||this.#r!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#J():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#C.clear(),this.#Z(null)),this.#r=null,this.#l=null,this.#f=null,this.#u=null,this.#b(),n&&this.#F("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#$e(){return this.#W?(this.#V||(this.#V=this.#ze().finally(()=>{this.#V=null})),this.#V):Promise.resolve()}async#ze(){if(!this.isClientTokenMode()){this.#W=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#W=!1}catch{}}reconcileBootConversation(e){let n=this.#_,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#r;if(!n||!o)return Promise.resolve();let s=this.#T(e?.scope);this.#d=!0,this.#b();let i=this.#Ue(n,o,s).finally(()=>{this.#d=this.#u!==null,this.#M===i&&(this.#M=null),this.#b()});return this.#M=i,i}async#Ue(e,n,o){this.#r=n;let s=this.clientSession?.conversationRevision??this.#l??null,i=this.#z?this.#Y:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#z=!1,this.#f=this.historyInternals.getStoredMessageCursor?.()??this.#f,await this.replayPendingProjections(),s&&i&&s===i){this.#l=s;return}let l=await e.getPage(n,{context:o}),c=new Set(l.messages.map(y=>y.id)),u=this.messages.some(y=>c.has(y.id)),p=l.messages[0]?.createdAt,g;if(!u)g=l.messages.map(y=>this.#ie(y));else{let y=this.#t?this.#i:null,h=this.messages.filter(C=>c.has(C.id)||C.id===y?!0:p!==void 0&&C.createdAt<p);g=Td(h,l.messages).map(C=>this.#ie(C))}this.#f=l.nextCursor,this.#l=l.conversationRevision||s||null,this.#L.clear();for(let y of l.messages)this.#L.set(y.id,y.content);this.#be(),this.messages=this.#K(g),this.callbacks.onMessagesChanged([...this.messages])}#ve(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#Z(e){this.#oe=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Pe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#oe}#Le(e){if(this.#ve())for(let n of e){let o=gi(n);o!==void 0&&this.#L.set(n.id,o)}}#qe(){if(!this.#ve())return;let e=this.#r;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let s=gi(o);s!==void 0&&this.#L.get(o.id)!==s&&n.push({id:o.id,displayContent:s})}n.length!==0&&(this.#Z({conversationId:e,messageIds:n.map(o=>o.id)}),this.#Ie(e,n))}#Ie(e,n){let s=(this.#y??Promise.resolve()).catch(()=>{}).then(()=>this.#He(e,n,!1)).finally(()=>{this.#y===s&&(this.#y=null)});this.#y=s}async#He(e,n,o){if(this.#r!==e)return;let s=n.filter(i=>this.#L.get(i.id)!==i.displayContent);if(s.length===0){this.#Ce(e,n);return}try{let{conversationRevision:i}=await this.client.finalizeDisplayProjections(e,s);for(let l of s)this.#L.set(l.id,l.displayContent);this.#r===e&&i&&(this.#l=i),this.#Ce(e,n)}catch(i){if(!o&&this.#je(i)){await this.#He(e,s,!0);return}if(i instanceof bt&&(i.code==="not_found"||i.code==="conversation_deleted")){this.#Ce(e,n);return}this.#F("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#je(e){return e instanceof bt?e.code==="request_failed":e instanceof Error}#Ce(e,n){let o=this.#Pe();if(!o||o.conversationId!==e)return;let s=new Set(n.map(l=>l.id)),i=o.messageIds.filter(l=>!s.has(l));this.#Z(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ve())return;let e=this.#Pe();if(!e)return;if(this.#r&&e.conversationId!==this.#r){this.#Z(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.#Z(null);return}this.#Ie(e.conversationId,n),await this.#y?.catch(()=>{})}#Ke(){this.#r&&(this.#l=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Re(){await this.awaitHistorySettled(),await this.#$e(),this.#u==="new_conversation_required"&&await this.#Fe()}static#Ge(e){return e instanceof bt&&e.code==="conversation_deleted"}async#Ye(e,n,o,s,i){this.#Le(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.#Ge(l))throw l;let c=await this.#Qe(s);if(!c)throw l;this.#Le([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions},this.handleEvent)}}async#Qe(e){let n=this.messages.find(s=>s.id===e);if(!n)return null;let o={...n};this.#A+=1,this.#y=null,this.#J(),this.#r=null,this.#l=null,this.#f=null,this.#P=!0;try{let s=this.#_;if(s){let i=await s.prepareStartNew({context:this.#T()});await this.#ye(i)}else{this.client.clearClientSession();let i=await this.client.initSession();this.bindActivatedSession(i)}}catch{return this.#d=!0,this.#u="new_conversation_required",this.#b(),this.#F("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#P=!1}return this.#N(o),this.#g(!0),this.#F("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=Ff(this.config,o),i=tw(this.config,o);this.config=o,s&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Nt(o.voiceRecognition.provider)&&this.setupVoice());let l=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!i){this.client.updateConfig(o),l&&this.#Be();return}this.#ee(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let c=this.client.getSSEEventCallback();this.client=new vi(this.config,this.historyInternals),l&&this.#Be(),this.#We(),c&&this.client.setSSEEventCallback(c)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:s,contentParts:i,id:l,createdAt:c,sequence:u,streaming:p=!1,voiceProcessing:g,voiceCaption:y,rawContent:h}=e,E={id:l??(n==="user"?bl():n==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:u??this.#k(),streaming:p,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...y&&{voiceCaption:y},...h!==void 0&&{rawContent:h}};return this.upsertMessage(E),E}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:u,createdAt:p,sequence:g,streaming:y=!1,voiceProcessing:h,rawContent:C}=o,A={id:u??(s==="user"?bl():s==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:p??new Date().toISOString(),sequence:g??this.#k(),streaming:y,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...h!==void 0&&{voiceProcessing:h},...C!==void 0&&{rawContent:C}};n.push(A)}return this.messages=this.#K([...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:u}=e,p={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(p),...i!==void 0&&{llmContent:i},...l!==void 0&&{id:l},...c!==void 0&&{createdAt:c},...u!==void 0&&{sequence:u}})}async#Xe(e,n,o){let s;try{s=await o()}catch{return}let i=s.blocks.join(`
9
+ _Details: ${n.message}_`:o}var mh=t=>Sd(t)||t===Ed,Al=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.#e=new Map;this.abortController=null;this.#m=Date.now();this.clientSession=null;this.agentExecution=null;this.#n=null;this.#i=null;this.#s=!1;this.#a=null;this.#v=null;this.#c=null;this.artifacts=new Map;this.#h=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#p=0;this.webMcpApprovalResolvers=new Map;this.#S=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#t=null;this.#x=null;this.#R=0;this.#G=0;this.#D=!1;this.#$="disconnected";this.#r=null;this.#l=null;this.#f=null;this.#A=0;this.#P=!1;this.#u=null;this.#d=!1;this.#M=null;this.#C=new Map;this.#y=null;this.#L=new Map;this.#oe=null;this.#Y=null;this.#z=!1;this.#w=null;this.#re=null;this.#W=!1;this.#V=null;this.#O=null;this.#U=null;this.#Q=new wi;this.#ae=Promise.resolve();this.#q=null;this.#B=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new xl(()=>this.#me());this.#Ze=null;this.#j=0;this.handleEvent=e=>{let n=this.#B,o=!1;if(n&&(e.type==="error"||e.type==="status"&&e.status==="error"?n.failed=!0:e.type==="message"&&e.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id),o=!0)),e.type==="message"){this.upsertMessage(e.message),o&&n.onUpdate?.(),e.message.variant==="approval"&&e.message.approval&&e.message.approval.status!=="pending"&&this.#e.set(e.message.id,this.#o),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant==="approval"||e.message.agentMetadata?.awaitingLocalTool===!0)&&$d().catch(()=>{});let s=e.message.toolCall,i=!!s?.name&&(Sd(s.name)||s.name===Ed&&ds(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&i&&this.#et(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.#st(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.#it()){this.#Se();return}if(this.#H(e.status),e.status==="connecting")this.#g(!0);else if(e.status==="idle"||e.status==="error"){this.#De()||this.#pe(),this.webMcpResolveControllers.size===0&&(this.#g(!1),this.abortController=null,this.#Ke(),this.#qe());let s=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":s||(this.agentExecution.status="complete")),this.#tt()}}else e.type==="error"?(this.#H("error"),this.#pe(),this.webMcpResolveControllers.size===0&&(this.#g(!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.#rt(e)};this.historyInternals=this.#ce(o),this.messages=[...e.initialMessages??[]].map(s=>({...s,sequence:s.sequence??this.#k()})),this.messages=this.#K(this.messages),this.client=new vi(e,this.historyInternals),this.#ke(),this.#We();for(let s of e.initialArtifacts??[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.#h=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#te(),this.callbacks.onStatusChanged(this.status),this.#ge(),this.#ue()}#e;#o;#m;#n;#i;#s;#a;#v;#c;#h;#p;#S;#t;#x;#R;#G;#D;#$;#r;#l;#f;#A;#P;#u;#d;#M;#C;#y;#L;#oe;#Y;#z;#w;#re;#W;#V;#ue(){this.config.voiceRecognition?.provider&&Si().catch(()=>{})}#ge(){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||Kd().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 zf(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#D}getVoiceStatus(){return this.#$}getVoiceNotice(){return this.#t?.takeNotice?.()??null}getVoiceDisclosure(){return this.#t?.getDisclosure?.()??null}getVoiceLevel(){return this.#t?.onLevel?this.#G:null}getVoiceInterruptionMode(){return this.#t?.getInterruptionMode?this.#t.getInterruptionMode():"none"}stopVoicePlayback(){this.#t?.stopPlayback&&(this.#Q.cancel(),this.#q?.cancel(),this.#t.stopPlayback())}isBargeInActive(){return this.#t?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#t?.deactivateBargeIn&&await this.#t.deactivateBargeIn()}#O;#U;#Q;#ae;#q;#B;#me(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Ci.isSupported()?new Ci({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 Kd().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:u})=>{let p=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new u(p,n,{onFallback:g=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${g.message}`)}):p});if(l&&n)return i&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#ae,s=++this.#R;this.#x=Si().then(async i=>{await o,s===this.#R&&this.#I(i,i.createVoiceProvider(n))}).catch(i=>{console.error("Failed to setup voice:",i)}).finally(()=>{s===this.#R&&(this.#x=null)})}catch(n){console.error("Failed to setup voice:",n)}}#I(e,n){this.#t=n;let o=this;e.wireSessionVoice({session:this,provider:()=>o.#t,generation:()=>o.#R,get keyed(){return o.#q},set keyed(s){o.#q=s},get pendingUser(){return o.#O},set pendingUser(s){o.#O=s},get pendingAssistant(){return o.#U},set pendingAssistant(s){o.#U=s},turns:()=>o.#Q,busy:()=>o.#fe(),setStreaming:s=>o.#g(s),setDelegation:s=>{o.#B=s},setLevel:s=>{o.#G=s},setStatus:s=>{o.#$=s,o.#D=s==="listening"},settlePending:s=>o.#le(s)},n,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#t&&this.#x&&await this.#x,!this.#t){console.error("Voice not configured");return}if(this.#D)await this.#t.stopListening();else{this.stopSpeaking();try{await this.#t.startListening()}catch(e){console.error("Failed to start voice:",e)}}}prewarmVoice(){if(!Ot(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#R,n=()=>{let o=this.#t;!o?.prewarm||e!==this.#R||this.#D||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#t&&this.#x){this.#x.then(n,()=>{});return}n()}#fe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#s||this.status==="resuming"}cleanupVoice(){let e=this.#t!==null;if(this.#R++,this.#x=null,this.#t){let n=this.#t;this.#t=null,this.#ae=this.#he(n)}this.#D=!1,this.#$="disconnected",this.#le(!0),this.#q?.settle(),this.#q=null,this.#Q=new wi,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#he(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#le(e){let n=e?this.#O:null,o=this.#U;!n&&!o||(o&&this.#Q.cancel(),e&&(this.#O=null),this.#U=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(s=>s.id!==n&&s.id!==o?[s]:s.id===o&&!s.content.trim()?[]:[{...s,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.#g(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};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.#Y=this.historyInternals.getStoredConversationRevision?.()??null,this.#z=!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}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,e)})}setClientSession(e,n){this.clientSession=e,this.#se(e,n)}#se(e,n=!this.messages.length){if(this.#P||!e.config.welcomeMessage||!n)return;let o=this.messages[0],s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.#k()};this.#N(s)}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.#ce(e),this.client.setHistoryInternals(this.historyInternals),this.#ke()}destroy(){this.cleanupVoice(),this.#w?.(),this.#w=null,this.#re=null}#ce(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.#Ne(o),n?.(o)}}}get#_(){return this.historyInternals.historyProvider??null}#E(){let e=this.#_;if(!e)throw new jn("history_unavailable","No conversation history provider is installed");return e}#T(e){let n=this.#E(),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 nl("unsupported_scope","This history scope is not supported.");return{scope:i}}getHistoryState(){return{activeConversationId:this.#r,conversationRevision:this.#l,nextMessageCursor:this.#f,recovery:this.#u,sendBlocked:this.#d}}getActiveConversationId(){return this.#r}#b(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#F(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.#M;e&&await e.catch(()=>{});let n=this.#y;n&&await n.catch(()=>{})}#X(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new jn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#E().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.#T(e?.scope)})}async openConversation(e,n){let o=this.#E();this.#X();let s=this.#T(n?.scope);await this.awaitHistorySettled();let i=++this.#A,l=await o.getPage(e,{context:s});if(i!==this.#A)throw new jn("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.#A)throw c.discard(),new jn("superseded","A later selection won");this.#P=!0;try{await this.#Ee(c)}finally{this.#P=!1}this.#r=c.conversationId||e,this.#l=c.conversationRevision||l.conversationRevision||null,this.#f=l.nextCursor,this.#u=null,this.#d=!1,this.#Te();for(let u of l.messages)this.#L.set(u.id,u.content);return this.#be(),this.hydrateMessages(l.messages),this.#b(),{summary:l.summary,nextMessageCursor:l.nextCursor}}loadOlderMessages(e,n,o){let s=this.#E(),i=this.#T(o?.scope),l=n??this.#f;if(!l)return Promise.resolve({messages:[],nextMessageCursor:null});let c=`${e} ${l}`,u=this.#C.get(c);if(u)return u;let p=this.#_e(s,e,l,i).finally(()=>{this.#C.delete(c)});return this.#C.set(c,p),p}async#_e(e,n,o,s){let i=this.messages[0]?.createdAt,l=await e.getPage(n,{cursor:o,...i?{beforeCreatedAt:i}:{},context:s});if(this.#r&&this.#r!==n)return{messages:[],nextMessageCursor:l.nextCursor};let c=Pd(this.messages,l.messages);this.messages=this.#K(c.map(u=>this.#ie(u))),this.#f=l.nextCursor;for(let u of l.messages)this.#L.set(u.id,u.content);return this.historyInternals.setStoredMessageCursor?.(l.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#b(),{messages:l.messages,nextMessageCursor:l.nextCursor}}async startNewConversation(e){let n=this.#E(),o=this.#T(e?.scope);await this.awaitHistorySettled();let s=++this.#A,i=await n.prepareStartNew({context:o});if(s!==this.#A)throw i.discard(),new jn("superseded","A later action won");await this.#ye(i)}async#ye(e){this.#J(),await this.#Ee(e),this.#r=e.conversationId||null,this.#l=e.conversationRevision||null,this.#f=null,this.#u=null,this.#d=!1,this.#be(),this.#b()}async deleteConversation(e,n){let o=this.#E(),s=this.#T(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:s}),e===this.#r&&await this.#Ae(s)}async updateConversation(e,n,o){let s=this.#E();if(!s.update)throw new jn("history_unavailable","This history provider cannot update conversations");let i=this.#T(o?.scope);return await this.awaitHistorySettled(),s.update(e,n,{context:i})}canUpdateConversations(){return typeof this.#_?.update=="function"}async clearConversationHistory(e){let n=this.#E(),o=this.#T(e?.scope);await this.awaitHistorySettled();let s=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.#Ae(o),s}async resetHistoryDevice(){let e=this.#E();if(!e.resetDevice)throw new jn("history_unavailable","This history provider cannot reset the device");this.#A+=1,this.#y=null;try{return await e.resetDevice()}finally{this.#J(),this.#r=null,this.#l=null,this.#f=null,this.#u=null,this.#d=!1,this.#b()}}async#Ae(e){this.#A+=1,this.#y=null,this.#J(),this.#r=null,this.#l=null,this.#f=null,this.#d=!0,this.#u=null,this.#b(),await this.#Me(e)}async#Me(e){let n=this.#_;if(!n){this.#d=!1,this.#b();return}try{let o=await n.prepareStartNew({context:e});await this.#ye(o)}catch{this.#d=!0,this.#u="new_conversation_required",this.#b(),this.#F("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#Fe(){if(!(this.#u!=="new_conversation_required"||!this.#_)&&(this.#u=null,await this.#Me(this.#T()),this.#u==="new_conversation_required"))throw new jn("new_conversation_required","A new conversation is required before sending")}async#Ee(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.#r=e.conversationId,this.#l=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#P||this.#se(e)}#be(){this.#r?this.config.setStoredConversationId?.(this.#r):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#l),this.historyInternals.setStoredMessageCursor?.(this.#f)}#Te(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#we(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#L.clear(),this.#Z(null)}#J(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.messages=[],this.#Te(),this.#C.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#g(!1),this.#H("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Ne(e){this.#A+=1,this.#y=null,this.#d=!0,this.#J(),this.#r=e.conversationId,this.#l=null,this.#f=null,this.#u=null,this.#b(),this.#F("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#M=Promise.resolve().then(()=>{this.#d=!1,this.#M=null,this.#b()})}#ke(){let e=this.historyInternals.visitorStore??null;e!==this.#re&&(this.#w?.(),this.#w=null,this.#re=e,e&&(this.#w=e.subscribe(n=>this.#Ve(n))))}#Ve(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#A+=1,this.#y=null,this.#W=!0,this.#V=null;let n=this.messages.length>0;n||this.#r!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#J():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#C.clear(),this.#Z(null)),this.#r=null,this.#l=null,this.#f=null,this.#u=null,this.#b(),n&&this.#F("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#$e(){return this.#W?(this.#V||(this.#V=this.#ze().finally(()=>{this.#V=null})),this.#V):Promise.resolve()}async#ze(){if(!this.isClientTokenMode()){this.#W=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#W=!1}catch{}}reconcileBootConversation(e){let n=this.#_,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#r;if(!n||!o)return Promise.resolve();let s=this.#T(e?.scope);this.#d=!0,this.#b();let i=this.#Ue(n,o,s).finally(()=>{this.#d=this.#u!==null,this.#M===i&&(this.#M=null),this.#b()});return this.#M=i,i}async#Ue(e,n,o){this.#r=n;let s=this.clientSession?.conversationRevision??this.#l??null,i=this.#z?this.#Y:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#z=!1,this.#f=this.historyInternals.getStoredMessageCursor?.()??this.#f,await this.replayPendingProjections(),s&&i&&s===i){this.#l=s;return}let l=await e.getPage(n,{context:o}),c=new Set(l.messages.map(y=>y.id)),u=this.messages.some(y=>c.has(y.id)),p=l.messages[0]?.createdAt,g;if(!u)g=l.messages.map(y=>this.#ie(y));else{let y=this.#n?this.#i:null,h=this.messages.filter(C=>c.has(C.id)||C.id===y?!0:p!==void 0&&C.createdAt<p);g=Pd(h,l.messages).map(C=>this.#ie(C))}this.#f=l.nextCursor,this.#l=l.conversationRevision||s||null,this.#L.clear();for(let y of l.messages)this.#L.set(y.id,y.content);this.#be(),this.messages=this.#K(g),this.callbacks.onMessagesChanged([...this.messages])}#ve(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#Z(e){this.#oe=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Pe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#oe}#Le(e){if(this.#ve())for(let n of e){let o=gi(n);o!==void 0&&this.#L.set(n.id,o)}}#qe(){if(!this.#ve())return;let e=this.#r;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let s=gi(o);s!==void 0&&this.#L.get(o.id)!==s&&n.push({id:o.id,displayContent:s})}n.length!==0&&(this.#Z({conversationId:e,messageIds:n.map(o=>o.id)}),this.#Ie(e,n))}#Ie(e,n){let s=(this.#y??Promise.resolve()).catch(()=>{}).then(()=>this.#He(e,n,!1)).finally(()=>{this.#y===s&&(this.#y=null)});this.#y=s}async#He(e,n,o){if(this.#r!==e)return;let s=n.filter(i=>this.#L.get(i.id)!==i.displayContent);if(s.length===0){this.#Ce(e,n);return}try{let{conversationRevision:i}=await this.client.finalizeDisplayProjections(e,s);for(let l of s)this.#L.set(l.id,l.displayContent);this.#r===e&&i&&(this.#l=i),this.#Ce(e,n)}catch(i){if(!o&&this.#je(i)){await this.#He(e,s,!0);return}if(i instanceof bt&&(i.code==="not_found"||i.code==="conversation_deleted")){this.#Ce(e,n);return}this.#F("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#je(e){return e instanceof bt?e.code==="request_failed":e instanceof Error}#Ce(e,n){let o=this.#Pe();if(!o||o.conversationId!==e)return;let s=new Set(n.map(l=>l.id)),i=o.messageIds.filter(l=>!s.has(l));this.#Z(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ve())return;let e=this.#Pe();if(!e)return;if(this.#r&&e.conversationId!==this.#r){this.#Z(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.#Z(null);return}this.#Ie(e.conversationId,n),await this.#y?.catch(()=>{})}#Ke(){this.#r&&(this.#l=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Re(){await this.awaitHistorySettled(),await this.#$e(),this.#u==="new_conversation_required"&&await this.#Fe()}static#Ge(e){return e instanceof bt&&e.code==="conversation_deleted"}async#Ye(e,n,o,s,i){this.#Le(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions,interrupt:i?.interrupt,voiceSpoken:i?.voiceSpoken},this.handleEvent);return}catch(l){if(!t.#Ge(l))throw l;let c=await this.#Qe(s);if(!c)throw l;this.#Le([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions,voiceSpoken:i?.voiceSpoken},this.handleEvent)}}async#Qe(e){let n=this.messages.find(s=>s.id===e);if(!n)return null;let o={...n};this.#A+=1,this.#y=null,this.#J(),this.#r=null,this.#l=null,this.#f=null,this.#P=!0;try{let s=this.#_;if(s){let i=await s.prepareStartNew({context:this.#T()});await this.#ye(i)}else{this.client.clearClientSession();let i=await this.client.initSession();this.bindActivatedSession(i)}}catch{return this.#d=!0,this.#u="new_conversation_required",this.#b(),this.#F("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#P=!1}return this.#N(o),this.#g(!0),this.#F("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=$f(this.config,o),i=rw(this.config,o);this.config=o,s&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Ot(o.voiceRecognition.provider)&&this.setupVoice());let l=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!i){this.client.updateConfig(o),l&&this.#Be();return}this.#ee(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let c=this.client.getSSEEventCallback();this.client=new vi(this.config,this.historyInternals),l&&this.#Be(),this.#We(),c&&this.client.setSSEEventCallback(c)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:s,contentParts:i,id:l,createdAt:c,sequence:u,streaming:p=!1,voiceProcessing:g,voiceCaption:y,rawContent:h}=e,E={id:l??(n==="user"?Cl():n==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:u??this.#k(),streaming:p,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...y&&{voiceCaption:y},...h!==void 0&&{rawContent:h}};return this.upsertMessage(E),E}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:u,createdAt:p,sequence:g,streaming:y=!1,voiceProcessing:h,rawContent:C}=o,A={id:u??(s==="user"?Cl():s==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:p??new Date().toISOString(),sequence:g??this.#k(),streaming:y,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...h!==void 0&&{voiceProcessing:h},...C!==void 0&&{rawContent:C}};n.push(A)}return this.messages=this.#K([...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:u}=e,p={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(p),...i!==void 0&&{llmContent:i},...l!==void 0&&{id:l},...c!==void 0&&{createdAt:c},...u!==void 0&&{sequence:u}})}async#Xe(e,n,o){let s;try{s=await o()}catch{return}let i=s.blocks.join(`
10
10
 
11
11
  `),l=[i,n].filter(Boolean).join(`
12
12
 
13
- `),c=Array.isArray(e.contentParts)&&e.contentParts.length>0,u=s.contentParts.length>0;if(c){let p=[];i&&p.push(zo(i)),p.push(...s.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(u){let p=[];l&&p.push(zo(l)),p.push(...s.contentParts),e.contentParts=p}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.#B&&!n?.voiceTurn&&(this.#B.failed=!0,this.#B=null),(this.#M||this.#y||this.#d||this.#W)&&await this.#Re(),this.stopSpeaking(),this.abortController?.abort(),this.#ee(),this.#j++,this.#ne();let i=n?.voiceTurn?.userMessageId,l=i?this.messages.find(C=>C.id===i&&C.role==="user"):void 0,c=l?.id??bl(),u=hs();this.#i=null;let p=n?.contentParts&&nf(n.contentParts)?Za:"",g={id:c,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#k(),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??{}};l?(l.viaVoice=!0,delete l.voiceCaption,l.content.trim()!==o&&(l.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#N(g),this.#g(!0);let y=new AbortController;if(this.abortController=y,n?.mentions){let C=this.messages.find(E=>E.id===c)??g;if(await this.#Xe(C,o,n.mentions.finalize),y.signal.aborted||this.abortController!==y)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let C=this.messages.find(A=>A.id===c)??g,E=rh({quote:n.quote,text:C.llmContent??C.content,contentParts:C.contentParts});E.contentParts&&(C.contentParts=E.contentParts),E.llmContent!==void 0&&(C.llmContent=E.llmContent),(E.contentParts||E.llmContent!==void 0)&&(C.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let h=l?[...this.messages.filter(C=>C!==l),{...l,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(h,y,u,c,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(C){if(this.status==="resuming"||this.#s)return;this.#B&&(this.#B.failed=!0);let E=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!E){let A=jd(C,this.config.errorMessage);if(A){let I={id:u,role:"assistant",createdAt:new Date().toISOString(),content:A,sequence:this.#k()};this.#N(I)}}this.#H("idle"),this.#g(!1),this.abortController=null,E||(C instanceof Error?this.callbacks.onError?.(C):this.callbacks.onError?.(new Error(String(C))))}}resubmitFrom(e,n){let o=sh(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 p=i?void 0:{...s.llmContent!==void 0&&{llmContent:s.llmContent},...s.rawContent!==void 0&&{rawContent:s.rawContent},...s.mentionContext&&{mentionContext:s.mentionContext},...s.contextMentions&&{contextMentions:s.contextMentions},...s.quote&&{quote:s.quote}},g=i?this.#Je(i.options):s.composerOptions,y=i?i.contentSegments:s.contentSegments,h=i?i.options?.quote:void 0,C=i?i.viaVoice:s.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(l??"",{...c?.length?{contentParts:[...c]}:{},...y?.length?{contentSegments:[...y]}:{},...g?{composerOptions:g}:{},...h?{quote:h}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:C===!0}),!0}#Je(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.#M||this.#y||this.#d||this.#W)&&await this.#Re(),this.abortController?.abort(),this.#ne();let e=hs();this.#i=null,this.#g(!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.#s)return;let i=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!i){let l=jd(s,this.config.errorMessage);if(l){let c={id:e,role:"assistant",createdAt:new Date().toISOString(),content:l,sequence:this.#k()};this.#N(c)}}this.#H("idle"),this.#g(!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.#i=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let l of this.messages)l.streaming&&l.id!==o&&(l.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.#g(!0);let i={};try{await this.client.processStream(e,l=>{let c=this.#o;this.#o=i;try{this.handleEvent(l)}finally{this.#o=c}},n?.assistantMessageId,n?.seedContent),this.#xe(i)}catch(l){if(this.status==="resuming"||this.#s){this.#pt(i);return}this.#xe(i),this.#H("error"),this.webMcpResolveControllers.size===0&&(this.#g(!1),this.abortController=null),this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}}#We(){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.#S}`,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")}#Ze;#j;#de(e){let n=this.#Ze??={s:this,setStreaming:i=>this.#g(i),appendMessage:i=>this.#N(i),nextSequence:()=>this.#k(),settleApprovalPausedToolCall:i=>this.#Oe(i),resumeAfter:i=>this.#t?.executionId===i?this.#t.lastEventId:void 0},o=oh();if(o)return e(o,n);let s=this.#j;return Nd().then(i=>s===this.#j?e(i,n):void 0,i=>{this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))})}resolveApproval(e,n,o){return this.#de((s,i)=>s.resolveApproval(i,e,n,o))}resolveAskUserQuestion(e,n){return this.#de((o,s)=>o.resolveAskUserQuestion(s,e,n))}resolveWebMcpToolCall(e){return this.#de((n,o)=>n.resolveWebMcpToolCall(o,e))}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}:{}}})}#et(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let i=this.#p;queueMicrotask(()=>{i===this.#p&&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))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#p;queueMicrotask(()=>{if(e===this.#p)for(let n of[...this.webMcpAwaitBatches.keys()])this.#nt(n)})}#nt(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.#de((s,i)=>s.resolveWebMcpToolCallBatch(i,e,o))}#ee(){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.#p++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#g(!1),this.#H("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.messages=[],this.agentExecution=null,this.#we(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#g(!1),this.#H("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#h}selectArtifact(e){this.#h=e,this.#te()}clearArtifacts(){this.#we()}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.#h=n,this.#te(),e.transcript!==!1&&this.#ot(o),o}#ot(e){let n=`artifact-ref-${e.id}`,o=as(this.config.features?.artifacts,e),s=wd(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})}#Be(){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=as(this.config.features?.artifacts,n),i=wd(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])}#we(){this.artifacts.size===0&&this.#h===null||(this.artifacts.clear(),this.#h=null,this.#te())}#te(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#h})}#rt(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.#h=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.#te()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#K(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#k()}))),this.#g(!1),this.#H("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.#h=n,this.#te()}#st(e){let n=this.agentExecution?.executionId;if(!n||!this.#i||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:e,assistantMessageId:this.#i,status:"running"},this.#dt(o)}#it(){return this.#t!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#De()}#De(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}#Se(){this.#s||!this.#t||typeof this.config.reconnectStream!="function"||(this.#s=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#g(!0),this.#H("resuming"),this.#at().then(e=>{this.#s&&this.#t&&e.begin()}))}#at(){return this.#a?Promise.resolve(this.#a):(this.#v||(this.#v=dh().then(({createReconnectController:e})=>{let n=e(this.#lt());return this.#a=n,n}),this.#v.catch(()=>{this.#v=null})),this.#v)}#lt(){let e=this;return{get config(){return e.config},getResumable:()=>e.#t,clearResumable:()=>e.#pe(),getStatus:()=>e.status,setStatus:n=>e.#H(n),setStreaming:n=>e.#g(n),setReconnecting:n=>{e.#s=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.#N(n),nextSequence:()=>e.#k(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>jd(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.#s){this.#a?.wake();return}this.#Se()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.#s)return;let n=this.#ct();n||(n=hs(),this.#N({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#k()})),this.#i=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#t={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.#Se()}#ct(){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}#ne(){this.#s=!1,this.#a?.teardown(),this.#pe()}#pe(){this.#c&&(clearTimeout(this.#c),this.#c=null);let e=this.#t!==null;this.#t=null,e&&this.config.onExecutionState?.(null)}#dt(e){let n=this.config.onExecutionState;if(n){if(e){this.#c&&(clearTimeout(this.#c),this.#c=null),n(this.#t);return}this.#c||(this.#c=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#H(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#g(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&(this.#xe(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let s=[...this.messages].reverse().find(l=>l.role==="assistant"&&l.content&&!l.voiceProcessing);if(!s||e&&!e.includes(s.id))return;if(this.ttsSpokenMessageIds.has(s.id)){this.ttsSpokenMessageIds.delete(s.id);return}let i=Ud(s.content);i.trim()&&this.readAloud.play(s.id,{text:i,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(e){return zd(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=Ud(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()}#xe(e){for(let[n,o]of[...this.#e])o===e&&(this.#e.delete(n),this.#Oe(n))}#pt(e){for(let[n,o]of this.#e)o===e&&this.#e.set(n,void 0)}#Oe(e){let n=this.messages.find(c=>c.id===e)?.approval,o=n?.toolCallId,s=o&&this.messages.find(c=>c.toolCall?.id===o),i=s&&s.toolCall;if(!i||i.status==="complete"||n.status==="pending")return;let l={...i,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...s,streaming:!1,toolCall:l})}#N(e){let n=this.#ie(e);this.messages=this.#K([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.#ie(e),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.#N(n);return}this.messages=this.messages.map((s,i)=>{if(i!==o)return s;let l={...s,...n};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});let c=s.agentMetadata?.clientToolAnswer;if(c&&l.agentMetadata&&!l.agentMetadata.clientToolAnswer&&(l.agentMetadata={...l.agentMetadata,clientToolAnswer:c}),s.approval&&n.approval&&s.approval.id===n.approval.id){let y=s.approval,h=n.approval;l.approval={...y,...h,executionId:h.executionId||y.executionId,toolName:h.toolName||y.toolName,description:h.description||y.description,toolType:h.toolType??y.toolType,reason:h.reason??y.reason,parameters:h.parameters??y.parameters,toolCallId:h.toolCallId??y.toolCallId}}let u=n.toolCall?.name,p=n.agentMetadata?.executionId,g=n.toolCall?.id;if(u&&ph(u)&&p&&g&&n.agentMetadata?.awaitingLocalTool===!0){let y=`${p}:${g}`,h=this.webMcpInflightKeys.has(y),C=this.webMcpResolvedKeys.has(y),E=s.toolCall?.name,A=s.agentMetadata?.executionId===p&&s.toolCall?.id===g&&E!==void 0&&ph(E)&&s.toolCall?.status==="complete";(h||C||A)&&(l.agentMetadata={...l.agentMetadata??{},awaitingLocalTool:!1},l.toolCall=s.toolCall,l.streaming=s.streaming)}return l}),this.messages=this.#K(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#ie(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.#k()}}#k(){return this.#m++}#K(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 nw,FileCode as ow,FileSpreadsheet as rw,FileText as Kd,X as sw}from"lucide";var iw={add:t=>of(t)},aw=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,xl={allowedTypes:us,maxFileSize:10*1024*1024,maxFiles:4};function lw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cw(t){return t==="application/pdf"?Kd:t.startsWith("text/")?Kd:t.includes("word")?Kd:t.includes("excel")||t.includes("spreadsheet")?rw:t==="application/json"?ow:nw}var xi=class t{constructor(e={}){this.attachments=[];this.#e=null;this.#o=new Map;this.#m=!1;this.config={allowedTypes:e.allowedTypes??xl.allowedTypes,maxFileSize:e.maxFileSize??xl.maxFileSize,maxFiles:e.maxFiles??xl.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#e;#o;#m;#t(){return typeof this.config.adapter?.add=="function"}#i(){return this.#t()?this.config.adapter:iw}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML="";for(let n of this.attachments)this.#h(n)}this.#n()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:xl.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.#m)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let s=rf(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:lw(),file:o,previewUrl:Ed(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#t()?"uploading":"processing",progress:this.#t()?0:void 0};this.attachments.push(i),this.#h(i),n.push(i)}this.#n(),this.#c(),await Promise.all(n.map(o=>this.#s(o)))}async#s(e){let n=new AbortController;this.#o.set(e.id,n);let o=()=>this.#m||n.signal.aborted||this.#o.get(e.id)!==n||!this.attachments.includes(e);try{let s=await this.#i().add(e.file,{signal:n.signal,onProgress:i=>{o()||e.status!=="uploading"||(e.progress=aw(i),this.#p(e),this.#c())}});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.#o.get(e.id)===n&&this.#o.delete(e.id)}this.#p(e),this.#c()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.#m||(n.status=this.#t()?"uploading":"processing",n.progress=this.#t()?0:void 0,n.error=void 0,this.#p(n),this.#c(),this.#s(n))}#a(e){let n=this.#o.get(e);n&&(this.#o.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.#a(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.#e?.querySelector(`[data-attachment-id="${e}"]`);s&&s.remove(),o.status==="ready"&&o.contentPart&&this.#v(o.contentPart),this.#n(),this.#c()}#v(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.#a(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#o.clear(),this.#e&&(this.#e.innerHTML=""),this.#n(),this.#c()}destroy(){if(!this.#m){this.#m=!0;for(let e of this.#o.values())e.abort();this.#o.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#m||this.config.onAttachmentsChange?.(this.getAttachments())}#h(e){if(!this.#e)return;let n=Ed(e.file),o=P("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let g=P("img");g.src=e.previewUrl,g.alt=e.file.name,g.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",g.style.width="48px",g.style.height="48px",g.style.objectFit="cover",g.style.borderRadius="8px",o.appendChild(g)}else{let g=P("div");g.style.width="48px",g.style.height="48px",g.style.borderRadius="8px",g.style.backgroundColor="var(--persona-container, #f3f4f6)",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.display="flex",g.style.flexDirection="column",g.style.alignItems="center",g.style.justifyContent="center",g.style.gap="2px",g.style.overflow="hidden";let y=cw(e.file.type),h=yt(y,20,"var(--persona-muted, #6b7280)",1.5);h&&g.appendChild(h);let C=P("span");C.textContent=sf(e.file.type,e.file.name),C.style.fontSize="8px",C.style.fontWeight="600",C.style.color="var(--persona-muted, #6b7280)",C.style.textTransform="uppercase",C.style.lineHeight="1",g.appendChild(C),o.appendChild(g)}let s=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),i=P("div","persona-attachment-progress");i.appendChild(P("div","persona-attachment-progress__bar"));let l=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=se("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);c?l.appendChild(c):l.textContent="\u21BB",l.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.retryAttachment(e.id)}),s.append(i,l),o.appendChild(s);let u=P("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");u.type="button",u.setAttribute("aria-label","Remove attachment"),u.style.position="absolute",u.style.top="-4px",u.style.insetInlineEnd="-4px",u.style.width="18px",u.style.height="18px",u.style.borderRadius="50%",u.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",u.style.border="none",u.style.cursor="pointer",u.style.display="flex",u.style.alignItems="center",u.style.justifyContent="center",u.style.padding="0";let p=yt(sw,10,"var(--persona-text-inverse, #ffffff)",2);p?u.appendChild(p):(u.textContent="\xD7",u.style.color="var(--persona-text-inverse, #ffffff)",u.style.fontSize="14px",u.style.lineHeight="1"),u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(u),this.#e.appendChild(o),this.#S(o,e)}#p(e){let n=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.#S(n,e)}#S(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)}%`:""}}#n(){this.#e&&(this.#e.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 uh=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),dw=(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 gh(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,s=!1,i=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",l=()=>{let g=i();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(y=>Object.freeze({...y}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:g,inputDisabled:t.inputDisabled,sendDisabled:g!=="idle"||t.sendDisabled||t.inputDisabled})},c=()=>(n||(n=l()),n),u=()=>{if(o=!1,s||e.size===0)return;let g=c();for(let y of[...e])try{y(g)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},p=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(u))};return{getState:c,subscribe:g=>(e.add(g),()=>e.delete(g)),setText:g=>{t.text!==g&&(t.text=g,p())},setAttachments:g=>{dw(t.attachments,g)||(t.attachments=[...g],p())},setMentionRefs:g=>{uh(t.mentionRefs,g)||(t.mentionRefs=[...g],p())},setSelectedModelId:g=>{t.selectedModelId!==g&&(t.selectedModelId=g,p())},setActiveModeIds:g=>{uh(t.activeModeIds,g)||(t.activeModeIds=[...g],p())},setQuote:g=>{let y=t.quote;y?.text===g?.text&&y?.messageId===g?.messageId&&y?.sourceLabel===g?.sourceLabel||(t.quote=g?{...g}:void 0,p())},setPendingSubmission:g=>{t.pendingSubmission!==g&&(t.pendingSubmission=g,p())},setPreparing:g=>{t.preparing!==g&&(t.preparing=g,p())},setStreaming:g=>{t.streaming!==g&&(t.streaming=g,p())},setInputDisabled:g=>{t.inputDisabled!==g&&(t.inputDisabled=g,p())},setSendDisabled:g=>{t.sendDisabled!==g&&(t.sendDisabled=g,p())},flush:()=>{o&&u()},destroy:()=>{s=!0,o=!1,e.clear()}}}var Qt=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},mh=(t,e)=>{let n=P("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function fh(t,e={}){let n=Qt(t,"[data-persona-composer-form]"),o=Qt(t,"[data-persona-composer-input]");if(!n||!o){let L=`[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(L);return typeof console<"u"&&console.warn(L),null}let s={header:Qt(t,"[data-persona-composer-header]"),body:Qt(t,"[data-persona-composer-body]"),actionsStart:Qt(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Qt(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Qt(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Qt(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Qt(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=mh("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,u=(I,L,k,R,B)=>{if(L)return L;i.add(I);let O=mh(k,R);return B.appendChild(O),O},p=u("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),g=u("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),y=u("suggestions",s.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),h=u("status",s.status,"persona-widget-composer__status","data-persona-composer-status",t),C=[],E=(I,L)=>I.target===L.target&&I.type===L.type&&I.handler===L.handler,A=Qt(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:l,body:c,actionsStart:p,actionsEnd:g,suggestions:y,status:h,attachmentInput:A,attachmentPreviews:Qt(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Qt(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Qt(t,"[data-persona-composer-submit]")??void 0,micButton:Qt(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(I,L,k,R)=>{I.addEventListener(L,k,R),C.push({target:I,type:L,handler:k,options:R})},removeListener:(I,L,k,R)=>{I.removeEventListener(L,k,R),C=C.filter(B=>!E(B,{target:I,type:L,handler:k}))},destroy:()=>{for(let I of C)I.target.removeEventListener(I.type,I.handler,I.options);C=[]}}}var pw='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',uw=["--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"],Gd="data-persona-menu-focus",gw=new Set(["ArrowDown","ArrowUp","Home","End"]);function hh(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(pw)??t}var mw=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function yh(t){let e=t.label,n=!1,o=P("div","persona-send-button-wrapper"),s=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Uo} ${Mr}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=Y("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),l=()=>{let x=t.getButtonSize?.()??"";s.style.width=x,s.style.height=x,s.style.minWidth=x,s.style.minHeight=x,s.style.lineHeight="1",s.replaceChildren();let z=se("plus",qn,"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 u=[],p=-1,g=!1,y=()=>{let z=i.getRootNode().activeElement;return z instanceof HTMLElement?z:null},h=()=>{let x=y();for(let z of u){let W=!!x&&hh(z)===x;z.toggleAttribute(Gd,W&&g)}},C=()=>u.filter(x=>x.isConnected||i.contains(x)).map(hh).filter(x=>!mw(x)),E=(x,z)=>{x.forEach((W,ee)=>{W.setAttribute("tabindex",ee===z?"0":"-1")})},A=x=>{let z=C();if(z.length===0)return;let W=(x%z.length+z.length)%z.length;p=W,E(z,W),z[W].focus(),h()},I=()=>o.ownerDocument??document,L=null,k=null,R=null,B=()=>{L&&(I().removeEventListener("focusin",L,!0),L=null)},O=()=>{k&&(i.removeEventListener("focusin",k),k=null),R&&(i.removeEventListener("pointerdown",R,!0),R=null)},V=null,J=()=>(V||(V=ll({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),B()}})),V),_=()=>V?.isOpen===!0,Q=(x=!1)=>{if(_()){V?.close(),s.setAttribute("aria-expanded","false"),B(),O(),p=-1,g=!1;for(let z of u)z.removeAttribute(Gd);x&&s.focus()}},G=(x=0,z=!1)=>{if(n||_())return;g=z,tl(s,i,uw),J().open(),s.setAttribute("aria-expanded","true");let W=C();E(W,-1),A(x<0?W.length-1:x),L=ee=>{let ne=typeof ee.composedPath=="function"?ee.composedPath():[];ne.includes(i)||ne.includes(o)||Q()},I().addEventListener("focusin",L,!0),k=()=>h(),i.addEventListener("focusin",k),R=()=>{g=!1},i.addEventListener("pointerdown",R,!0)},w=x=>{x.preventDefault(),x.stopPropagation(),_()?Q(!0):G(0)},v=x=>{if(x.key==="ArrowDown"||x.key==="Enter"||x.key===" "){x.preventDefault(),g=!0,_()?A(0):G(0,!0);return}x.key==="ArrowUp"&&(x.preventDefault(),g=!0,_()?A(-1):G(-1,!0))},T=x=>{switch(gw.has(x.key)&&(g=!0),x.key){case"ArrowDown":x.preventDefault(),A(p+1);return;case"ArrowUp":x.preventDefault(),A(p-1);return;case"Home":x.preventDefault(),A(0);return;case"End":x.preventDefault(),A(C().length-1);return;case"Escape":x.preventDefault(),x.stopPropagation(),Q(!0);return;case"Tab":Q(!0);return;default:}};return s.addEventListener("click",w),s.addEventListener("keydown",v),i.addEventListener("keydown",T),{trigger:o,triggerButton:s,panel:i,setItems:x=>{for(let W of u)x.includes(W)||W.removeAttribute(Gd);if(u=[...x],!_())return;let z=C();E(z,Math.min(p,z.length-1)),h()},isOpen:_,open:()=>G(0),close:Q,setLabel:x=>{x!==e&&(e=x,c())},applyButtonSize:l,destroy:()=>{n=!0,B(),O(),s.removeEventListener("click",w),s.removeEventListener("keydown",v),i.removeEventListener("keydown",T),V?.destroy(),V=null,o.remove(),i.remove(),u=[]}}}var Kn={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},bh="data-persona-composer-action",Yd="data-persona-composer-disable-when-streaming",fw="core:overflow",hw=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function yw(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=P("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 Qd(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 vh=(t,e)=>{!t||typeof console>"u"||console.warn(e)},bw=(t,e)=>e.includes(":")?e:`${t}:${e}`;function vw(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let u=o.get(c.id);if(u){vh(e,`[Persona] composer action "${c.id}" is already contributed by ${Ch(u)}; the ${Ch(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,u,p)=>{let g=p?bw(p,c.id):c.id,y=c.order??Kn.custom;c.placement==="end"&&y>=Kn.send&&(vh(e,`[Persona] composer action "${g}" ordered at ${y} would render after send; clamped to ${Kn.send-1}.`),y=Kn.send-1),i({id:g,placement:c.placement,presentation:c.presentation??"bar",order:y,sequence:s++,source:u,pluginId:p,action:c})};for(let c of t.configActions??[])l(c,"config");for(let c of t.plugins){if(!c.contributeComposerActions)continue;let u;try{u=c.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,p);continue}for(let p of u??[])l(p,"plugin",c.id)}return n.sort((c,u)=>c.order===u.order?c.sequence-u.sequence:c.order-u.order)}var Ch=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",wh=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,Cw=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function ww(t,e){if(!t||t==="always")return!0;let n=Cw(e);return t==="when-text"?n:!n}var jo=t=>t.kind==="custom",Xd=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,Sw=t=>{let e=Xd(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},xw='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Aw(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(xw)||o.childNodes.forEach(n)};return n(t),e.trim()}var Mw=t=>Aw(t).length===0;function Sh(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(w,v)=>{let T=w.button;if(!T)return;T.setAttribute("role","menuitem"),T.setAttribute("tabindex","-1"),T.className="persona-composer-overflow-menu__item";for(let W of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])T.style[W]="";T.style.lineHeight="1",v.tooltipText?T.setAttribute("title",v.tooltipText):T.removeAttribute("title"),T.replaceChildren();let x=P("span","persona-composer-overflow-menu__icon");if(v.iconName){let W=se(v.iconName,16,"currentColor",1.5);W&&x.appendChild(W)}let z=P("span","persona-composer-overflow-menu__label");z.textContent=v.shortLabel??v.label,T.append(x,z)},l=(w,v)=>{let T=w.button;if(!T)return;if(T.setAttribute("aria-label",v.label),v.pressed===void 0?T.removeAttribute("aria-pressed"):T.setAttribute("aria-pressed",v.pressed?"true":"false"),T.toggleAttribute(Yd,v.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,i(w,v);return}T.removeAttribute("role"),T.removeAttribute("tabindex"),T.removeAttribute("title");let x=s(),z=!!v.shortLabel;if(T.className=ss("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Uo,Mr,z&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),T.style.width=x&&!z?x:"",T.style.height=x??"",T.style.minWidth=x&&!z?x:"",T.style.minHeight=x??"",T.style.fontSize=z?"":"18px",T.style.lineHeight="1",T.style.color=v.iconColor??"",T.style.backgroundColor=v.backgroundColor??"",T.replaceChildren(),v.iconName){let W=se(v.iconName,qn,"currentColor",1.5);W&&T.appendChild(W)}if(z){let W=P("span","persona-composer-action-button__label");W.textContent=v.shortLabel,T.appendChild(W)}else T.firstChild||(T.textContent=v.label);w.tooltip?.destroy(),w.tooltip=vn({anchor:T,trigger:w.element,text:()=>v.tooltipText??v.label,enabled:!!v.tooltipText})},c=(w,v)=>{let T=w.action,x=Y("button",{attrs:{type:"button"}}),z=x;if(v==="bar"){let ne=P("div","persona-send-button-wrapper");ne.appendChild(x),z=ne}z.setAttribute(bh,w.id);let W={resolved:w,element:z,button:x,owned:!0,managed:!0,busy:!1,visible:!0,mode:v},ee=ne=>{if(ne.preventDefault(),ne.stopPropagation(),W.busy||x.disabled)return;let he=W.resolved.action;W.mode==="menu"&&C?.close(!0);let ve;try{ve=he.onSelect(t.actionContext,ne)}catch(Xe){t.reportError(Xe,{actionId:W.resolved.id});return}!ve||typeof ve.then!="function"||(W.busy=!0,x.setAttribute("aria-busy","true"),ve.catch(Xe=>{t.reportError(Xe,{actionId:W.resolved.id})}).finally(()=>{W.busy=!1,x.removeAttribute("aria-busy")}))};return x.addEventListener("click",ee),W.detach=()=>x.removeEventListener("click",ee),l(W,T),W},u=w=>{let v=w.action,T;try{T=v.render({...t.actionContext,id:w.id,action:v})}catch(x){return t.reportError(x,{actionId:w.id}),null}return T?.element?(T.element.setAttribute(bh,w.id),T.element.toggleAttribute(Yd,v.disableWhenStreaming===!0),{resolved:w,element:T.element,owned:!0,managed:!0,destroy:T.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(w,v)=>{if(w.builtIn){let x=w.builtIn.element;return x?{resolved:w,element:x,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let T=w.action;return T?jo(T)?u(w):c(w,v):null},g=w=>{if(w.detach?.(),w.tooltip?.destroy(),w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0,w.owned){try{w.destroy?.()}catch(v){t.reportError(v,{actionId:w.resolved.id})}w.element.remove()}},y=(w,v)=>{for(let T=0;T<v.length;T++){let x=v[T];if(!x.managed)continue;let z=null;for(let W=T+1;W<v.length;W++){let ee=v[W];if(!ee.managed&&ee.element.parentElement===w){z=ee.element;break}}z?(x.element.parentElement!==w||x.element.nextSibling!==z)&&w.insertBefore(x.element,z):w.lastChild!==x.element&&w.appendChild(x.element)}},h=(w,v)=>{if(w.button){w.button.disabled=v;return}if(!w.owned)return;let T=w.element;T.toggleAttribute("data-disabled",v),T.setAttribute("aria-disabled",v?"true":"false");let x=T instanceof HTMLButtonElement||T instanceof HTMLSelectElement||T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement?T:T.querySelector("button, select, input, textarea");x&&(x.disabled=v)},C=null,E=null,A=null,I=0,L=()=>{let w=t.getOverflow?.();return w?.enabled===!0?w:void 0},k=()=>(C?C.setLabel(t.getOverflowLabel?.()??"More actions"):C=yh({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),C),R=w=>{E!==w&&(A?.disconnect(),E=w,I=Qd(w),!(typeof ResizeObserver>"u")&&(A=new ResizeObserver(v=>{let x=v[v.length-1]?.contentRect?.width??Qd(w);x!==I&&(I=x,Q())}),A.observe(w)))},B=(w,v)=>{let T=yw(w.collapseAutoActionsBelow,v);if(T===null)return!1;let x=I||Qd(v);return x>0&&x<T},O=(w,v,T)=>{if(!v)return"bar";if(w.resolved.builtIn){let z=hw(w.resolved.id);return z&&v.includeBuiltIns?.includes(z)?"menu":"bar"}let x=w.resolved.presentation;return x==="overflow"||x==="auto"&&T?"menu":"bar"},V=w=>{let v=w.menuSlot;if(!v)return;if(!Mw(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let T=Sw(w.element);if(!T){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=P("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==T&&(w.menuLabel.textContent=T),w.menuLabel.parentElement!==v&&v.appendChild(w.menuLabel)},J=(w,v)=>{if(w.mode===v)return w;let T=w.resolved.action;if(T&&!jo(T)){g(w),e.delete(w.resolved.id);let x=c(w.resolved,v);return e.set(w.resolved.id,x),x}if(v==="menu"){let x=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[lf]:""}});x.appendChild(w.element),cf(Xd(w.element)),w.menuSlot=x;let z=W=>{let ee=Xd(w.element);if(ee.disabled)return;let ne=W.target===ee||ee.contains(W.target);C?.close(!0),ne||ee.click()};x.addEventListener("click",z,!0),w.detachMenuSlot=()=>x.removeEventListener("click",z,!0),w.managed=!0,V(w)}else w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0;return w.mode=v,w},_=(w,v)=>{let T=v.map(x=>x.menuSlot??x.element);for(T.forEach((x,z)=>{let W=w.children[z];W!==x&&(W?w.insertBefore(x,W):w.appendChild(x))});w.children.length>T.length;)w.lastElementChild?.remove()},Q=()=>{if(o)return;let w=t.getBindings();if(!w)return;let v=t.getState(),T=v.phase==="streaming",x=L();x&&R(w.footer);let z=x?B(x,w.footer):!1,W={start:[],end:[]},ee=[];for(let ne of n){let he=e.get(ne.id);if(!he)continue;let ve=ne.action,Xe=ve?wh(ve.visible,v,!0)&&ww(ve.visibility,v):!0;if(he.visible!==Xe&&(he.visible=Xe,!Xe&&he.managed&&(he.menuSlot??he.element).remove()),!!Xe){if(he=J(he,O(he,x,z)),ve){let Je=wh(ve.disabled,v,!1)||ve.disableWhenStreaming===!0&&T;h(he,Je),!jo(ve)&&ve.pressed!==void 0&&he.button?.setAttribute("aria-pressed",ve.pressed?"true":"false")}he.mode==="menu"?(V(he),ee.push(he)):W[ne.placement].push(he)}}if(ee.length>0){let ne=k();_(ne.panel,ee),ne.setItems(ee.map(Je=>Je.menuSlot??Je.element)),ne.applyButtonSize();let he=Number.isFinite(x?.order)?x?.order:Kn.overflow,ve=W.start.findIndex(Je=>Je.resolved.order>he),Xe={resolved:{id:fw,placement:"start",presentation:"bar",order:he,sequence:-1,source:"core"},element:ne.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};W.start.splice(ve<0?W.start.length:ve,0,Xe)}else C&&(C.close(),C.trigger.remove(),C.setItems([]));y(w.actionsStart,W.start),y(w.actionsEnd,W.end)};return{resolve:()=>{if(o)return;let w=vw(t.collect()),v=new Set(w.map(T=>T.id));for(let[T,x]of e)v.has(T)||(g(x),e.delete(T));for(let T of w){let x=e.get(T.id);if(!x){let ne=p(T,"bar");ne&&e.set(T.id,ne);continue}let z=x.resolved.action,W=T.action;if(!!z!=!!W||z&&W&&jo(z)!==jo(W)||z&&W&&jo(z)&&jo(W)&&z.render!==W.render){g(x),e.delete(T.id);let ne=p(T,x.mode);ne&&e.set(T.id,ne);continue}x.resolved=T,T.builtIn?(x.managed=T.builtIn.managed===!0||x.mode==="menu",T.builtIn.element&&x.mode==="bar"&&(x.element=T.builtIn.element)):W&&!jo(W)?l(x,W):W&&x.element.toggleAttribute(Yd,W.disableWhenStreaming===!0)}n=w,Q()},sync:Q,getResolved:()=>n,getOverflowMenu:()=>C,destroy:()=>{if(!o){o=!0,A?.disconnect(),A=null,E=null;for(let w of e.values())g(w);e.clear(),C?.destroy(),C=null,n=[]}}}}var Ew="core:model",Tw=700,xh=16,kw=["--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"],Ah=()=>{let t=Y("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=Y("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Mh(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=u=>{let p=t.getSelectedModelId();return u.find(g=>g.id===p)??u[0]},i=()=>{let u=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",g=()=>{let A=t.getModels(),I=A.map(L=>`${L.id}:${L.label}`).join("|");I!==p&&(p=I,u.replaceChildren(...A.map(L=>{let k=Y("option",{attrs:{value:L.id}});return k.textContent=L.label,k}))),u.value=s(A)?.id??""};g(),o=g;let y=()=>{u.value&&t.onSelect(u.value)};u.addEventListener("change",y);let h=A=>A.stopPropagation();u.addEventListener("click",h);let{wrapper:C,chevron:E}=Ah();return C.append(u,E),{element:C,destroy:()=>{o===g&&(o=null),u.removeEventListener("change",y),u.removeEventListener("click",h)}}},l=()=>{let u=Y("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"}}),p=P("span","persona-composer-model-picker-label"),g=P("span","persona-composer-model-picker-suffix");u.append(p,g);let y=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),h=new Map,C="",E=null,A=()=>E?.isOpen===!0,I=(v=!1)=>{A()&&(E?.close(),u.setAttribute("aria-expanded","false"),v&&u.focus())},L=v=>{let T=[...h.values()];if(T.length===0)return;let x=(v%T.length+T.length)%T.length;T[x].focus()},k=v=>{if(A())return;E||(E=ll({anchor:u,content:y,placement:"top-start",offset:6,onDismiss:()=>u.setAttribute("aria-expanded","false")})),tl(u,y,kw),E.open(),u.setAttribute("aria-expanded","true");let x=[...h.keys()].indexOf(s(t.getModels())?.id??"");L(v??(x>=0?x:0))},R=v=>{I(!0),t.onSelect(v)},B=v=>{v.preventDefault(),v.stopPropagation();let T=v.currentTarget.getAttribute("data-persona-model-option");T&&R(T)},O=v=>{let T=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":v.id}});if(v.icon){let ne=se(v.icon,xh,"currentColor",1.5);if(ne){let he=P("span","persona-composer-model-option-icon");he.appendChild(ne),T.appendChild(he)}}let x=P("span","persona-composer-model-option-body"),z=P("span","persona-composer-model-option-label");if(z.textContent=v.label,x.appendChild(z),v.description){let ne=P("span","persona-composer-model-option-description");ne.textContent=v.description,x.appendChild(ne)}T.appendChild(x);let W=P("span","persona-composer-model-option-check");W.setAttribute("aria-hidden","true");let ee=se("check",xh,"currentColor",2);return ee&&W.appendChild(ee),T.appendChild(W),T.addEventListener("click",B),T},V=()=>{let v=t.getModels(),T=v.map(W=>`${W.id}:${W.label}:${W.icon??""}:${W.description??""}`).join("|");if(T!==C){C=T;for(let W of h.values())W.removeEventListener("click",B);h.clear(),y.replaceChildren(...v.map(W=>{let ee=O(W);return h.set(W.id,ee),ee}))}let x=s(v);for(let[W,ee]of h)ee.setAttribute("aria-selected",String(W===x?.id));p.textContent=x?.label??"";let z=t.getSuffix?.()??"";g.textContent=z,u.setAttribute("aria-label",[e,[x?.label,z].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let J=v=>{v.preventDefault(),v.stopPropagation(),A()?I(!0):k()},_=v=>{if(v.key==="ArrowDown"){v.preventDefault(),A()?L(0):k(0);return}v.key==="ArrowUp"&&(v.preventDefault(),A()?L(-1):k(-1))},Q=v=>{let T=[...h.values()],x=T.indexOf(v.target?.closest?.(".persona-composer-model-option"));switch(v.key){case"ArrowDown":v.preventDefault(),L(x+1);return;case"ArrowUp":v.preventDefault(),L(x-1);return;case"Home":v.preventDefault(),L(0);return;case"End":v.preventDefault(),L(T.length-1);return;case"Escape":v.preventDefault(),v.stopPropagation(),I(!0);return;case"Tab":I(!0);return;default:}};u.addEventListener("click",J),u.addEventListener("keydown",_),y.addEventListener("keydown",Q);let{wrapper:G,chevron:w}=Ah();return G.append(u,w),{element:G,destroy:()=>{o===V&&(o=null),u.removeEventListener("click",J),u.removeEventListener("keydown",_),y.removeEventListener("keydown",Q);for(let v of h.values())v.removeEventListener("click",B);h.clear(),E?.destroy(),E=null,y.remove()}}};return{action:{id:Ew,kind:"custom",placement:"end",order:Tw,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var Pw=":scope > [data-persona-composer-mode]";function Eh(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=p=>{let g=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let E=P("span","persona-mention-chip-icon"),A=se(p.iconName,12,"currentColor",1.5);A&&E.appendChild(A),g.appendChild(E)}let y=P("span","persona-mention-chip-label");y.textContent=p.shortLabel??p.label,g.appendChild(y);let h=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),C=se("x",12,"currentColor",2);return C?h.appendChild(C):h.textContent="\xD7",h.addEventListener("click",E=>{E.preventDefault(),E.stopPropagation(),t.onRemove(p.id)}),g.appendChild(h),g},l=()=>Array.from(e.querySelectorAll(Pw)),c=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let g=()=>{p.remove(),al(e)},y=e.ownerDocument.defaultView,h=typeof y?.getComputedStyle=="function"?y.getComputedStyle(p).animationName:"";if(!h||h==="none"){g();return}p.addEventListener("animationend",g,{once:!0}),p.addEventListener("animationcancel",g,{once:!0})},u=()=>{for(let p of l())p.remove()};return{element:e,render:(p,g)=>{if(o)return;let y=g.filter(A=>p.includes(A.id)),h=y.map(A=>`${A.id}:${A.shortLabel??A.label}`).join("|");if(h===n)return;n=h;let C=new Map;for(let A of l()){let I=A.getAttribute("data-persona-composer-mode");I&&y.some(k=>k.id===I)&&!A.hasAttribute("data-persona-chip-exit")?C.set(I,A):A.hasAttribute("data-persona-chip-exit")||c(A)}let E=e.firstChild;for(let A of y){let I=C.get(A.id);I||(I=i(A),s.has(A.id)||(I.setAttribute("data-persona-chip-enter",""),I.addEventListener("animationend",()=>I?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(A.id),I!==E&&e.insertBefore(I,E),E=I.nextSibling}al(e)},destroy:()=>{o=!0,u(),al(e)}}}var Th=t=>`core:mode:${t}`;var Jd=t=>Math.min(300+t,499),kh=t=>`core:mode-group:${t}`;function Al(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function Lw(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Ph(t,e){return t?.length?t.filter(n=>!Al(n.groupId,e)&&!Lw(n.groupId,e)):[]}var Iw=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Lh(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(Iw(s,o)==="single"){let c=n.filter(u=>u.groupId===s.groupId).map(u=>u.id);l=new Set([...l].filter(u=>!c.includes(u)))}l.add(e)}return n.filter(c=>l.has(c.id)).map(c=>c.id)}function Ml(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Ih(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Hh(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var Hw=16;function Rh(t){let e=null;return{action:{id:kh(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=Y("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=p=>{p.preventDefault(),p.stopPropagation();let y=p.currentTarget.getAttribute("data-persona-composer-mode");!y||t.getActiveIds().includes(y)&&t.getGroup()?.selection==="single"||t.onSelect(y)},c=p=>{let g=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let h=se(p.iconName,Hw,"currentColor",1.5);h&&g.appendChild(h)}let y=P("span","persona-composer-segmented-label");return y.textContent=p.shortLabel??p.label,g.appendChild(y),g.addEventListener("click",l),g},u=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let g=t.getModes(),y=g.map(C=>`${C.id}:${C.shortLabel??C.label}:${C.iconName??""}`).join("|");if(y!==i){i=y;for(let E of s.values())E.removeEventListener("click",l);s.clear();let C=g.map(E=>{let A=c(E);return s.set(E.id,A),A});o.replaceChildren(...C)}let h=t.getActiveIds();for(let[C,E]of s)E.setAttribute("aria-pressed",String(h.includes(C)))};return u(),e=u,{element:o,destroy:()=>{e===u&&(e=null);for(let p of s.values())p.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function Wh(t){let e=Y("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,s=i=>{let l=P("span","persona-composer-quote-bar"),c=P("div","persona-composer-quote-content");if(i.sourceLabel){let y=P("div","persona-composer-quote-source");y.textContent=i.sourceLabel,c.appendChild(y)}let u=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});u.textContent=Cl(i.text),c.appendChild(u);let p=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),g=se("x",12,"currentColor",2);g?p.appendChild(g):p.textContent="\xD7",p.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),t.onDismiss()}),e.replaceChildren(l,c,p)};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 Bh(t){let e=Y("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,u,p)=>{let g=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[u]:""}}),y=se(l,12,"currentColor",2);return y?g.appendChild(y):g.textContent=c,g.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),g},i=l=>{let c=Cl(l.text??"",90);if(c)return c;let u=l.contentParts?.length??0;return u>0?u===1?"1 attachment":`${u} attachments`:(l.mentionRefs?.length??0)>0?l.mentionRefs.map(g=>g.label).join(", "):"Queued message"};return{element:e,render:l=>{if(o||l===n)return;if(n=l,!l){e.replaceChildren(),e.style.display="none";return}let c=P("span","persona-composer-pending-badge");c.textContent=t.label??"Sends next";let u=Y("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});u.textContent=i(l),e.replaceChildren(c,u,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 Dh(t){let e=Y("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=Y("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=P("div","persona-message-edit-actions"),i=(c,u,p,g)=>{let y=Y("button",{className:`persona-message-edit-button ${u}`,attrs:{type:"button",[p]:""},text:c});return y.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),g()}),y},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 Oh(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 _h(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(u=>n.has(u.sourceId)),s=o.length===(t.mentionRefs?.length??0)&&o.length>0,i=new Set(e.modes.map(u=>u.id)),l=(t.activeModeIds??[]).filter(u=>i.has(u)),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 Fh(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 Nh(t){return t.wrapped||t.text.includes(`
14
- `)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission)}function Vh(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function $h(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 Zd(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 Uh(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var Rw=t=>typeof t?.then=="function";function zh(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 qh(t,e,n){let o;try{o=t(Zd(e),{signal:n})}catch(s){return{status:"error",error:s}}return Rw(o)?Promise.resolve(o).then(s=>n.aborted?{status:"aborted"}:zh(e,s),s=>n.aborted?{status:"aborted"}:{status:"error",error:s}):zh(e,o)}var El=t=>t?.launcher?.variant??(t?.future?.v5Defaults===!0?"circle":"pill"),Tl={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var Pl="16px",Ll="transparent",Ww=(()=>{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})(),Ai={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:Ww,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"}},kl={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"}},an={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:Rm,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Pl,canvasBackground:Ll,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",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"}}},Bw=Ai.colors.gray,Dw={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},Ow={...Ai,colors:{...Ai.colors,gray:Bw}},_w={...Ai,colors:{...Ai.colors,gray:Dw},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var Fw=kl,Nw={...kl,colors:{...kl.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...kl.typography,fontSize:"14px",lineHeight:"1.5"}};var tp=an,Vw={...an,launcher:Tl,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...an.input,borderRadius:"palette.radius.full"},introCard:{...an.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...an.suggestion.chip,fontWeight:"400"},card:{...an.suggestion.card,fontWeight:"400"},list:{...an.suggestion.list,fontWeight:"400"}},panel:{...an.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...an.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...an.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...an.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...an.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...an.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}};var $w=t=>Ar({future:t}),np=t=>$w(t)==="v5"?{palette:_w,semantic:Nw,components:Vw}:{palette:Ow,semantic:Fw,components:tp};function Pt(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."))?Pt(t,o):o}function Kh(t){let e={};function n(o,s){for(let[i,l]of Object.entries(o)){let c=`${s}.${i}`;if(typeof l=="string"){let u=Pt(t,l);u!==void 0&&(e[c]={path:c,value:u,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 zw(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 Gh(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]=Gh(i,s):n[o]=s}return n}function Uw(t,e){return e?Gh(t,e):t}function ys(t,e={}){let n=np(e.future),o={palette:n.palette,semantic:n.semantic,components:n.components},s={palette:{...o.palette,...t?.palette,colors:{...o.palette.colors,...t?.palette?.colors},spacing:{...o.palette.spacing,...t?.palette?.spacing},typography:{...o.palette.typography,...t?.palette?.typography},shadows:{...o.palette.shadows,...t?.palette?.shadows},borders:{...o.palette.borders,...t?.palette?.borders},radius:{...o.palette.radius,...t?.palette?.radius}},semantic:{...o.semantic,...t?.semantic,colors:{...o.semantic.colors,...t?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...t?.semantic?.spacing},typography:{...o.semantic.typography,...t?.semantic?.typography}},components:Uw(o.components,t?.components)},i=t?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let g of["rowHeight","labelSize","iconSize","indent","bodySurface"])i?.[g]!==void 0&&(s.components[p][g]=i[g]);let l=t?.components?.collapsibleWidget?.surface;l!==void 0&&i?.bodySurface===void 0&&(s.components.activity={...s.components.activity,bodySurface:l});let c=t?.components?.header;c?.padding!==void 0&&c.minimalPadding===void 0&&(s.components.header.minimalPadding=s.components.header.padding);let u=t?.components?.message;if(u?.gap!==void 0&&u.fullscreenGap===void 0&&(s.components.message.fullscreenGap=s.components.message.gap),e.validate!==!1){let p=zw(s);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(g=>g.message).join(", ")}`)}if(e.plugins)for(let p of e.plugins)s=p.transform(s);return s}var ep=t=>t.trim()==="0"?"0px":t,jh="--persona-",qw=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(u=>{let p=u.endsWith("%"),g=parseFloat(p?u.slice(0,-1):u);return p?g/100*255:g}))}}if(!n||n.some(l=>!Number.isFinite(l)))return;let[o,s,i]=n.map(l=>{let c=Math.max(0,Math.min(255,l))/255;return c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4)});return .2126*o+.7152*s+.0722*i},jw=.179,kt=(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[jh+i],s!==void 0)break;s!==void 0&&(t[jh+n]=s)}};function Yh(t){let e=Kh(t),n={};for(let[H,Me]of Object.entries(e)){let de=H.replace(/\./g,"-");n[`--persona-${de}`]=Me.value}kt(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"],kt(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"]]),kt(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"]}`,kt(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"]??Pl,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ll,kt(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"]]),kt(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"],kt(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"],kt(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 u=n["--persona-components-history-railHeader-background"];u&&(n["--persona-history-rail-header-bg"]=u);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let g=n["--persona-components-history-railHeader-minHeight"];g&&(n["--persona-history-rail-header-min-height"]=g);for(let[H,Me]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let de=n[`--persona-components-history-overlay-${H}`];de&&(n[`--persona-history-overlay-${Me}`]=de)}for(let[H,Me]of[["background","bg"],["borderRadius","radius"]]){let de=n[`--persona-components-history-menu-${H}`];de&&(n[`--persona-history-menu-${Me}`]=de)}let y=t.components?.history?.motion;if(y){let H=In=>{if(In===void 0)return;let Ps=String(In).trim();return/^\d+(\.\d+)?$/.test(Ps)?`${Ps}ms`:Ps},Me=H(y.enterDurationMs);Me!==void 0&&(n["--persona-history-enter-ms"]=Me);let de=H(y.exitDurationMs);de!==void 0&&(n["--persona-history-exit-ms"]=de),y.enterEasing&&(n["--persona-history-enter-easing"]=y.enterEasing),y.exitEasing&&(n["--persona-history-exit-easing"]=y.exitEasing)}let h=n["--persona-components-history-dangerForeground"];h&&(n["--persona-history-danger-fg"]=h),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 H of["scrim","shadow"]){let Me=n[`--persona-components-history-confirm-${H}`];Me&&(n[`--persona-history-confirm-${H}`]=Me)}for(let[H,Me]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let de=n[`--persona-components-tooltip-${H}`];de&&(n[`--persona-tooltip-${Me}`]=de)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[H,Me]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let de=n[`--persona-components-messageActions-${H}`];de&&(n[`--persona-message-action-${Me}`]=de)}kt(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let C=n["--persona-components-introCard-background"],E=n["--persona-components-introCard-shadow"],A=(!C||C==="transparent"||C==="none")&&(!E||E==="none"),I=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=A&&I==="1.5rem"?"1.5rem 0":I,kt(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"]]),kt(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 L=n["--persona-components-markdown-heading-h1-fontSize"];L&&(n["--persona-md-h1-size"]=L);let k=n["--persona-components-markdown-heading-h1-fontWeight"];k&&(n["--persona-md-h1-weight"]=k);let R=n["--persona-components-markdown-heading-h2-fontSize"];R&&(n["--persona-md-h2-size"]=R);let B=n["--persona-components-markdown-heading-h2-fontWeight"];B&&(n["--persona-md-h2-weight"]=B);let O=n["--persona-components-markdown-prose-fontFamily"];O&&O!=="inherit"&&(n["--persona-md-prose-font-family"]=O),kt(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"]]),kt(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),kt(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),kt(n,[["md-hr-color","components-markdown-hr-color","divider"]]),kt(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"]]);let V=[["container","surface"],["surface","surface"],["border","border"]];for(let[H,Me]of V){let de=n[`--persona-components-collapsibleWidget-${H}`]??n[`--persona-${Me}`];de!==void 0&&(n[`--persona-cw-${H}`]=de,n[`--cw-${H}`]=de)}kt(n,[["message-border","components-message-border","border"]]),kt(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-border-width","components-message-assistant-borderWidth"],["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 J=t.components,_=J?.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 Q=J?.labelButton;Q&&(Q.background&&(n["--persona-label-btn-bg"]=Q.background),Q.border&&(n["--persona-label-btn-border"]=Q.border),Q.color&&(n["--persona-label-btn-color"]=Q.color),Q.padding&&(n["--persona-label-btn-padding"]=Q.padding),Q.borderRadius&&(n["--persona-label-btn-radius"]=Q.borderRadius),Q.hoverBackground&&(n["--persona-label-btn-hover-bg"]=Q.hoverBackground),Q.fontSize&&(n["--persona-label-btn-font-size"]=Q.fontSize),Q.gap&&(n["--persona-label-btn-gap"]=Q.gap));let G=J?.toggleGroup;G&&(G.gap&&(n["--persona-toggle-group-gap"]=G.gap),G.borderRadius&&(n["--persona-toggle-group-radius"]=G.borderRadius));let w=J?.artifact;if(w?.toolbar){let H=w.toolbar;H.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=H.iconHoverColor),H.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=H.iconHoverBackground),H.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=H.iconPadding),H.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=H.iconBorderRadius),H.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=H.iconBorder),H.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ep(H.toggleGroupGap)),H.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=H.toggleBorderRadius),H.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=ep(H.toggleGroupPadding)),H.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=H.toggleGroupBorder),H.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=H.toggleGroupBorderRadius),H.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Pt(t,H.toggleGroupBackground)??H.toggleGroupBackground),H.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=H.copyBackground),H.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=H.copyBorder),H.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=H.copyColor),H.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ep(H.copyBorderRadius)),H.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=H.copyPadding),H.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=H.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??H.copyMenuBackground),H.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=H.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??H.copyMenuBorder),H.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=H.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??H.copyMenuShadow),H.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=H.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??H.copyMenuBorderRadius),H.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=H.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??H.copyMenuItemHoverBackground),H.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=H.iconBackground),H.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=H.toolbarBorder)}if(w?.tab){let H=w.tab;H.background&&(n["--persona-artifact-tab-bg"]=H.background),H.activeBackground&&(n["--persona-artifact-tab-active-bg"]=H.activeBackground),H.activeBorder&&(n["--persona-artifact-tab-active-border"]=H.activeBorder),H.borderRadius&&(n["--persona-artifact-tab-radius"]=H.borderRadius),H.textColor&&(n["--persona-artifact-tab-color"]=H.textColor),H.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=H.hoverBackground),H.listBackground&&(n["--persona-artifact-tab-list-bg"]=H.listBackground),H.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=H.listBorderColor),H.listPadding&&(n["--persona-artifact-tab-list-padding"]=H.listPadding)}if(w?.pane){let H=w.pane;if(H.toolbarBackground){let Me=Pt(t,H.toolbarBackground)??H.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Me}}if(w?.card){let H=w.card;H.background&&(n["--persona-artifact-card-bg"]=H.background),H.border&&(n["--persona-artifact-card-border"]=H.border),H.borderRadius&&(n["--persona-artifact-card-radius"]=H.borderRadius),H.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=H.hoverBackground),H.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=H.hoverBorderColor)}if(w?.inline){let H=w.inline;H.background&&(n["--persona-artifact-inline-bg"]=Pt(t,H.background)??H.background),H.border&&(n["--persona-artifact-inline-border"]=H.border),H.borderRadius&&(n["--persona-artifact-inline-radius"]=H.borderRadius),H.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Pt(t,H.chromeBackground)??H.chromeBackground),H.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Pt(t,H.chromeBorder)??H.chromeBorder),H.titleColor&&(n["--persona-artifact-inline-title-color"]=Pt(t,H.titleColor)??H.titleColor),H.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Pt(t,H.mutedColor)??H.mutedColor),H.frameHeight&&(n["--persona-artifact-inline-frame-height"]=H.frameHeight)}let v=J?.code;v&&(v.keywordColor&&(n["--persona-code-keyword-color"]=v.keywordColor),v.stringColor&&(n["--persona-code-string-color"]=v.stringColor),v.commentColor&&(n["--persona-code-comment-color"]=v.commentColor),v.numberColor&&(n["--persona-code-number-color"]=v.numberColor),v.tagColor&&(n["--persona-code-tag-color"]=v.tagColor),v.attrColor&&(n["--persona-code-attr-color"]=v.attrColor),v.propertyColor&&(n["--persona-code-property-color"]=v.propertyColor),v.lineNumberColor&&(n["--persona-code-line-number-color"]=v.lineNumberColor),v.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=v.gutterBorderColor),v.background&&(n["--persona-code-bg"]=Pt(t,v.background)??v.background));let T=n["--persona-surface"],x=n["--persona-container"],z=n["--persona-palette-colors-gray-100"]??"#f3f4f6",W=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ee=n["--persona-palette-colors-gray-300"]??"#d1d5db",ne=!x||x===T,he=qw(T??n["--persona-background"]),ve=ne&&he!==void 0&&he<jw,Xe=ve?"rgba(255, 255, 255, 0.08)":z,Je=ve?"rgba(255, 255, 255, 0.12)":W,Wt=ve?"rgba(255, 255, 255, 0.16)":ee,$e=ne?Xe:x,Ce=ne?Je:x;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??$e,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Ce,ne&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??Wt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??$e,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??$e,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??$e,n}var Kw=t=>!!t&&"launcher"in t&&(t.launcher?.sidebarMode===!0||t.launcher?.mountMode==="docked"),Qh=(t,e)=>{if(!e||!Kw(e))return t;let n=e.theme?.components?.panel?.width,o=e.darkTheme?.components?.panel?.width;return(Ei(e)==="dark"?o??n:n)!=null?t:{...t,components:{...t.components,panel:{...t.components.panel,width:Ar(e)==="v5"?"400px":"420px"}}}},Gw={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"}}},Mi={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)"}}}},op=Gw,Yw={...op,colors:{...op.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},Qw=Mi,Xw={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",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"}}},components:{...Mi.components,button:{...Mi.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...Mi.components?.eventStream,badge:{...Mi.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},Jw=t=>Ar({future:t})==="v5"?{palette:Yw,components:Xw}:{palette:op,components:Qw},Xh=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},rp=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Zw=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":rp()},Ei=t=>Zw(t),eS=(t,e={})=>ys(t,e),tS=(t,e={})=>{let n=Jw(e.future),o=Sr(n.components,t??{})??{};return ys({...o,palette:{...o.palette,colors:Ar(e)==="v5"?Sr(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:e.future})},ho=t=>{let e=Ei(t),n=Xh(t?.theme),o=El(t)==="circle"?Tl:{...tp.launcher,...t?.future?.v5Defaults?{offset:"1.5rem"}:{}},s=Sr({components:{launcher:o}},n),i=Xh(t?.darkTheme);return Qh(e==="dark"?tS(Sr(s??{},i??{}),{future:t?.future}):eS(s,{future:t?.future}),t)},nS=t=>Yh(t),Ti=(t,e)=>{let n=ho(e),o=nS(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",Ei(e)),t.setAttribute("data-persona-defaults",Ar(e))},Il=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(rp())});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(rp());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 fb,Check as hb,Copy as yb}from"lucide";var Ko=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Hl="24px",sp=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",ki=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},Jh=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);import{Idiomorph as oS}from"idiomorph";var Rl=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;oS.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 Zh=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var ip={index:-1,draft:""};function ey(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 ty(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 ny(){return new Map}function oy(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function ry(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function sy(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:fT,load:rS}=je({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var iy=rS;function ap(t,e=Dt){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 Pi=0,Go=null;function lp(t=document){if(Pi++,Pi===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Go={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,Pi=Math.max(0,Pi-1),Pi===0&&Go)){let n=t.body,o=t.defaultView??window;n.style.overflow=Go.originalOverflow,n.style.position=Go.originalPosition,n.style.top=Go.originalTop,n.style.width=Go.originalWidth,o.scrollTo(0,Go.scrollY),Go=null}}}var Li={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},rt=t=>(t?.launcher?.mountMode??"floating")==="docked",Ii=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Cn=t=>{let e=t?.launcher?.dock,n=xr(t).dockWidth?e?.width:Pt(ho(t),"components.panel.width");return{side:e?.side??Li.side,width:n??Li.width,animate:e?.animate??Li.animate,reveal:e?.reveal??Li.reveal,maxHeight:e?.maxHeight??Li.maxHeight}};import{ArrowRight as sS}from"lucide";var cp=t=>t==="followUp"?"follow-up":t,dp=(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"}},ay=new WeakSet,iS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,aS=t=>{iS()||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"})})},pp=t=>{let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:u,chipsConfig:p,session:g,getTextarea:y,eventTarget:h,submitPrompt:C}=t,E=o==="followUp",A=e.behavior,I=()=>{if(g.isStreaming())return;let R={suggestion:{...e},surface:o,source:s,behavior:A},B=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:R,bubbles:!0,composed:!0,cancelable:!0}));if(E&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!B)return;for(let V of u)if(V.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let O=y();if(A==="fill"){O.value=e.prompt,O.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),O.focus();return}if(C){C(e.prompt);return}O.value="",g.sendMessage(e.prompt)},L=()=>{let R=P("button",`persona-suggestion persona-suggestion--${i}`);if(R.type="button",R.disabled=l,R.dataset.suggestionId=e.id,R.dataset.emphasis=e.emphasis,R.dataset.behavior=A,i==="chip"&&(p?.fontWeight&&(R.style.fontWeight=p.fontWeight),p?.paddingX&&(R.style.paddingLeft=p.paddingX,R.style.paddingRight=p.paddingX),p?.paddingY&&(R.style.paddingTop=p.paddingY,R.style.paddingBottom=p.paddingY)),e.icon){let O=se(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);O&&(O.classList.add("persona-suggestion__icon"),e.iconColor&&(O.style.color=e.iconColor),R.appendChild(O))}let B=P("span","persona-suggestion__copy");if(B.appendChild(Y("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&B.appendChild(Y("span",{className:"persona-suggestion__description",text:e.description})),R.appendChild(B),i!=="chip"){let O=yt(sS,16,"currentColor",1.8);O&&(O.classList.add("persona-suggestion__arrow"),R.appendChild(O))}return R.addEventListener("click",I),R},k=null;for(let R of u)if(R.renderSuggestion&&(k=R.renderSuggestion({suggestion:{...e},index:n,surface:o,source:s,variant:i,streaming:l,config:c,defaultRenderer:L,select:I}),k))break;return k??=L(),k.dataset.suggestionId||=e.id,k.dataset.behavior||=A,k.dataset.emphasis||=e.emphasis,k instanceof HTMLButtonElement||k.setAttribute("aria-disabled",l?"true":"false"),k},Hi=t=>{let e=[],n=[],o=null,s=null,i=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},l=()=>{if(s=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){i();return}let g=Math.max(0,t.scrollWidth-t.clientWidth);if(g<=1){i();return}let y=getComputedStyle(t).direction==="rtl",h=Math.min(g,Math.max(0,Math.abs(t.scrollLeft))),C=4,E=h<=C,A=h>=g-C,I=y?!A:!E,L=y?!E:!A;t.toggleAttribute("data-scroll-left",I),t.toggleAttribute("data-scroll-right",L)},c=()=>{if(s!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&l();return}s=requestAnimationFrame(l)};t.addEventListener("scroll",c,{passive:!0});let u=typeof ResizeObserver=="function"?new ResizeObserver(c):null;return u?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",c),u?.disconnect(),s!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(s),s=null},render:(g,y,h,C,E,A)=>{t.replaceChildren(),e.length=0,n.length=0;let I=A?.source??"config",L=A?.surface??(I==="config"?"starter":"followUp"),k=L==="followUp",R=A?.variant??"chip",B=A?.behavior??"send",O=A?.overflow??"wrap",V=A?.config??{},J=A?.plugins??[],_=typeof A?.maxItems=="number"?Math.max(0,Math.floor(A.maxItems)):void 0,Q=k?"followUps":"starters";!ay.has(V)&&V.debug===!0&&R!=="chip"&&V.suggestions?.[Q]?.overflow!==void 0&&(ay.add(V),console.info(`[persona] suggestions.${Q}.overflow applies to the "chip" variant only; the "${R}" variant manages its own stacking.`));let G=W=>W.map(dp).filter(ee=>ee!==null).map(ee=>({...ee,behavior:ee.behavior??B})),w=G(g??[]);J.forEach(W=>{W.transformSuggestions&&(w=G(W.transformSuggestions({suggestions:w.map(ee=>({...ee})),surface:L,source:I,config:V})))});let v=_===void 0?w:w.slice(0,_);if(!v.length){t.hidden=!0,o=null,i();return}if(!k&&(C??y.getMessages()).some(ee=>ee.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=cp(L),t.dataset.variant=R,t.dataset.overflow=O;let T=document.createDocumentFragment(),x=y.isStreaming();v.forEach((W,ee)=>{let ne=pp({item:W,index:ee,surface:L,source:I,variant:R,streaming:x,config:V,plugins:J,chipsConfig:E,session:y,getTextarea:()=>h,eventTarget:t,submitPrompt:A?.submitPrompt});T.appendChild(ne),n.push(ne),[...ne instanceof HTMLButtonElement?[ne]:[],...Array.from(ne.querySelectorAll("button"))].forEach(ve=>{e.includes(ve)||(ve.disabled=x,e.push(ve))})}),t.appendChild(T),l(),c();let z=JSON.stringify({normalized:v,surface:L,variant:R,source:I});z!==o&&(o=z,aS(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:v.map(W=>({...W})),surface:L,source:I,variant:R},bubbles:!0,composed:!0})),k&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:v.map(W=>W.prompt)},bubbles:!0,composed:!0})))}}};var ln={"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 lS="persona-header-control",cS="persona-header-control--glyph",dS="persona-header-control--sparse",pS=20,uS={x:[1.4,1.05]},ly="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",gS="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wl=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=uS[e]??[1,1.5],c=!o;t.classList.toggle(cS,c),t.classList.toggle(dS,c&&i!==1);let u=parseFloat(o??"")||pS,p=se(e,`${Math.round(u*i)}px`,"currentColor",l);p?(p.style.display="block",c||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((l/1.5).toFixed(4))})`),t.replaceChildren(p)):s&&(t.textContent=s)},bs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=ly,size:c,iconSize:u,color:p,backgroundColor:g,borderWidth:y,borderColor:h,borderRadius:C,paddingX:E,paddingY:A,hidden:I,extraClassName:L,attrs:k}=t,R=P("div",l),B=!!(y||h),O=Y("button",{className:ss(lS,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"persona-bg-transparent hover:persona-bg-gray-100",!B&&"persona-border-none",!C&&"persona-rounded-full",L),attrs:{type:"button","aria-label":e,...k},style:{width:c,height:c,minWidth:c,minHeight:c,display:I?"none":void 0,color:p||Vt.actionIconColor,backgroundColor:g,border:B?`${y||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:C,paddingLeft:E,paddingRight:E,paddingTop:A,paddingBottom:A}});return s?Wl(O,s,{iconSize:u,iconText:i}):i&&(O.textContent=i),R.appendChild(O),vn({anchor:O,trigger:R,text:()=>O.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:O,wrapper:R}},vs=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=ly,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",u=l.closeButtonShowTooltip??!0,{button:p,wrapper:g}=bs({ariaLabel:c,tooltip:u,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:p,wrapper:g}},Cs=(t,e={})=>{let{wrapperClassName:n=gS,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",u=l.showTooltip??!0,{button:p,wrapper:g}=bs({ariaLabel:c,tooltip:u,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:p,wrapper:g}};var Vt={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-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},up={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)"},mS={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)"},kr=t=>{let{config:e,showClose:n=!0}=t,o=Y("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:Vt.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??$a,l=s.closeButtonPlacement??"inline",c=s.headerIconHidden??!1,u=s.headerIconName,p=Y("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(u){let O=parseFloat(i)||24,V=se(u,O*.6,"currentColor",1);V?(V.style.width=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,V.style.height=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(V)):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let O=P("img");O.src=e.launcher.iconUrl,O.alt="",O.className="persona-rounded-xl persona-object-cover",O.style.height=i,O.style.width=i,p.replaceChildren(O)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let g=P("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),y=Y("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Vt.titleColor,...up}}),h=Y("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Vt.subtitleColor,...mS}});g.append(y,h),c?o.append(g):o.append(p,g);let C=s.clearChat??{},E=C.enabled??!0,A=C.placement??"inline",I=null,L=null;if(E){let V=Cs(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});I=V.button,L=V.wrapper,A==="top-right"&&(L.style.right="48px"),A==="inline"&&o.appendChild(L)}let k=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":E&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:B}=vs(e,{showClose:n,wrapperClassName:k});return l!=="top-right"&&o.appendChild(B),{header:o,iconHolder:p,headerTitle:y,headerSubtitle:h,closeButton:R,closeButtonWrapper:B,clearChatButton:I,clearChatButtonWrapper:L}},Ri=(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 fS=t=>{let e=kr({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 hS(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=bs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?xf(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=Af(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=Wf({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 yS=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:i}=t,l=e?.launcher??{},c=P("div","persona-flex persona-items-center persona-justify-between");c.setAttribute("data-persona-theme-zone","header"),c.style.minHeight=Vt.minHeight,c.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",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 u=s?.titleMenu,p,g;if(u){let B=Df({label:l.title??"Chat Assistant",menuItems:u.menuItems,onSelect:O=>{let V=_=>{_===!1&&B.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:O}}))},J=u.onSelect(O);J instanceof Promise?J.then(V,()=>{}):V(J)},hover:u.hover,className:""});p=B.element,p.style.color=Vt.titleColor,g=p.querySelector(".persona-combo-btn-label")??p}else{if(p=P("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=P("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=Vt.titleColor,Object.assign(g.style,up),g.textContent=l.title??"Chat Assistant",p.appendChild(g),s?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let O=s.onTitleClick;p.addEventListener("click",V=>{V.target.closest("button")||O()}),p.addEventListener("keydown",V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),O())})}let B=s?.titleRowHover;B&&(p.style.borderRadius=B.borderRadius??"10px",p.style.padding=B.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=B.background??"",p.style.borderColor=B.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}c.appendChild(p);let y="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:C}=vs(e,{showClose:n,wrapperClassName:y});o&&h.addEventListener("click",o);let E=P("div","persona-flex persona-items-center persona-gap-1");u||hS(E,s?.trailingActions,s?.onAction??i);let A=l.clearChat??{},I=null,L=null;if(A.enabled??!0){let B=A.placement??"inline",O=Cs(e,{wrapperClassName:B==="top-right"?"persona-absolute persona-top-4 persona-z-50":y});I=O.button,L=O.wrapper,B==="top-right"?L.style.right="48px":E.appendChild(L)}E.appendChild(C),c.appendChild(E);let k=P("div");k.style.display="none";let R=P("span");return R.style.display="none",{header:c,iconHolder:k,headerTitle:g,headerSubtitle:R,closeButton:h,closeButtonWrapper:C,clearChatButton:I,clearChatButtonWrapper:L}},cy={default:fS,minimal:yS},bS=t=>cy[t]??cy.default,Bl=(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=P("div");c.style.display="none";let u=P("span"),p=P("span"),g=P("button");g.style.display="none";let y=P("div");return y.style.display="none",{header:l,iconHolder:c,headerTitle:u,headerSubtitle:p,closeButton:g,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=bS(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 Wi=t=>{let{config:e}=t,n=Y("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=il(),s=Y("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":""}}),{textarea:i,attachAutoResize:l}=nl(e);l();let c=ol(e),u=gs(e),p=rl(e),g=sl(e),y=Y("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(y),p&&(p.previewsContainer.style.gap="8px",y.append(p.previewsContainer),s.append(p.input)),s.append(i);let h=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),C=Y("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),E=Y("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&C.append(p.wrapper),u&&E.append(u.wrapper),E.append(c.wrapper),h.append(C,E),s.append(h),s.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&i.focus()}),e?.statusIndicator?.mode==="transient"?n.append(o,g,s):n.append(o,s,g),{footer:n,suggestions:o,composerForm:s,header:y,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:g,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:h,leftActions:C,rightActions:E,setSendButtonMode:c.setMode}};import{ChevronUp as vS,MessageSquare as CS}from"lucide";var dy=()=>{let t=Y("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=P("span","persona-pill-peek__icon"),n=yt(CS,16,"currentColor",1.5);n&&e.appendChild(n);let o=P("span","persona-pill-peek__text"),s=P("span","persona-pill-peek__caret"),i=yt(vS,16,"currentColor",1.5);return i&&s.appendChild(i),t.append(e,o,s),{root:t,textNode:o}},Dl=t=>{let{config:e}=t,n=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=il(),s=sl(e);s.style.display="none";let{textarea:i,attachAutoResize:l}=nl(e,{defaultMaxLines:5});l();let c=ol(e),u=gs(e),p=rl(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let g=Y("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),y=Y("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&y.append(p.wrapper);let h=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});u&&h.append(u.wrapper),h.append(c.wrapper),g.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&i.focus()}),p&&g.append(p.input),g.append(y,i,h);let C=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(C),p&&C.append(p.previewsContainer),n.append(o,g,s);let E=g;return{footer:n,suggestions:o,composerForm:g,header:C,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:s,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:E,leftActions:y,rightActions:h,setSendButtonMode:c.setMode}};var wS=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}},SS=(t,e)=>{if(!t)return null;let n=wS(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},xS=(t,e)=>{let n=P("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},AS=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},mp=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(":"))},fp=320,fy=320,MS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),ES=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),TS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),kS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),PS=t=>{if(!t||t.length===0)return null;let e=Y("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Y("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=P("span","persona-mention-chip-icon"),i=se(n.iconName??"at-sign",13,"currentColor",2);i&&s.appendChild(i),o.appendChild(s),o.appendChild(Y("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},LS=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Id(o.ref,{readonly:!0,render:e}))}return n},py="\uE000",uy="\uE001",IS=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=h=>`${py}${s}:${h}${uy}`,l=e.map((h,C)=>h.kind==="text"?h.text:i(C)).join(""),c=n(l);if(!e.every((h,C)=>h.kind==="text"||c.includes(i(C)))){t.replaceChildren(LS(e,o));return}t.innerHTML=c;let p=new RegExp(`${py}${s}:(\\d+)${uy}`),g=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),y=[];for(let h=g.nextNode();h;h=g.nextNode())y.push(h);for(let h of y){let C=h;for(let E=p.exec(C.data);E;E=p.exec(C.data)){let A=e[Number(E[1])],I=C.splitText(E.index);I.data=I.data.slice(E[0].length),A?.kind==="mention"&&I.parentNode?.insertBefore(Id(A.ref,{readonly:!0,render:o}),I),C=I}}},HS=(t,e,n)=>{if(t.length===0)return null;try{let o=P("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,u)=>{let p=P("img");p.alt=c.alt?.trim()||`Attached image ${u+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${fp}px`,p.style.maxHeight=`${fy}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;s+=1,p.addEventListener("error",()=>{g||(g=!0,s=Math.max(0,s-1),p.remove(),s===0&&l())}),p.addEventListener("load",()=>{g=!0}),AS(c.image)?(p.src=c.image,o.appendChild(p)):(g=!0,s=Math.max(0,s-1),p.remove())}),s===0?(l(),null):o}catch{return n?.(),null}},RS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!mp(o.audio))return;let s=P("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${fp}px`,e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},WS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!mp(o.video))return;let s=P("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${fp}px`,s.style.maxHeight=`${fy}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}},BS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!mp(o.data))return;let s=P("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}},Bi=()=>{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},DS=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Bi};if(e){let s=e(o);if(s!==null)return s}return Bi()},OS=(t,e)=>{let n=P("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=P("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},gy=(t,e,n="div")=>{let o=P(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},Di=(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},my={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"}},_S=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=my[n??"bubble"]??my.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)`)},Ol="custom:",FS=t=>`${Ol}${t}`,hy=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),NS=(t,e,n,o)=>{let s=e.showCopy??!0,i=e.showUpvote??!1,l=e.showDownvote??!1,c=e.showReadAloud??!1,u=(e.showRegenerate??!1)&&o?.canRegenerate===!0,p=(e.showEdit??!1)&&o?.canEdit===!0,g=(e.showQuote??!1)&&o?.canQuote!==!1,y=hy(e,t.role);if(!s&&!i&&!l&&!c&&!u&&!p&&!g&&y.length===0){let R=P("div");return R.style.display="none",R.id=`actions-${t.id}`,R.setAttribute("data-actions-for",t.id),R}let h=e.visibility??"hover",C=e.align??"right",E=e.layout??"pill-inside",A={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[C],I={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[E],L=P("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${A} ${I} ${h==="hover"?"persona-message-actions-hover":""}`);L.id=`actions-${t.id}`,L.setAttribute("data-actions-for",t.id);let k=(R,B,O)=>{let V=Bf({icon:R,label:B,size:14,className:"persona-message-action-btn",chromeless:!0});return V.setAttribute("data-action",O),V};s&&L.appendChild(k("copy","Copy message","copy")),c&&L.appendChild(k("volume-2","Read aloud","read-aloud")),i&&L.appendChild(k("thumbs-up","Upvote","upvote")),l&&L.appendChild(k("thumbs-down","Downvote","downvote")),u&&L.appendChild(k("refresh-cw","Regenerate response","regenerate")),p&&L.appendChild(k("pencil","Edit message","edit")),g&&L.appendChild(k("quote","Quote message","quote"));for(let R of y)L.appendChild(k(R.iconName??"ellipsis",R.label,FS(R.id)));return L},hp=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",u=l.avatar,p=l.timestamp,g=u?.show??!1,y=p?.show??!1,h=u?.position??"left",C=p?.position??"below",E=Di(t.role,c),A=P("div",E.join(" "));A.id=`bubble-${t.id}`,A.setAttribute("data-message-id",t.id),A.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let I=np(i?.widgetConfig?.future).components.message,L=i?.widgetConfig?.theme?.components?.message;_S(A,t.role,c,t.role==="user"?{...I.user,...L?.user,...i?.widgetConfig?.darkTheme?.components?.message?.user}:{...I.assistant,...L?.assistant,...i?.widgetConfig?.darkTheme?.components?.message?.assistant}),c==="flat"?(A.style.backgroundColor="transparent",A.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=MS(t),R=t.content?.trim()??"",O=k.length>0&&R===Za,V=cl(i?.widgetConfig?.features?.streamAnimation),J=i?.widgetConfig?.features?.streamAnimation?.plugins,_=t.role==="assistant"&&V.type!=="none"?mi(V.type,J):null,Q=t.role==="assistant"&&_?.isAnimating?.(t)===!0,G=t.role==="assistant"&&_!==null&&(!!t.streaming||Q);G&&_?.bubbleClass&&A.classList.add(_.bubbleClass);let w=document.createElement("div");w.classList.add("persona-message-content"),t.streaming&&w.classList.add("persona-content-streaming"),G&&_&&(_.containerClass&&w.classList.add(_.containerClass),w.style.setProperty("--persona-stream-step",`${V.speed}ms`),w.style.setProperty("--persona-stream-duration",`${V.duration}ms`));let v=G?dl(t.content??"",V.buffer,_,t,!!t.streaming):t.content??"",T=()=>{let Ce=e({text:v,message:t,streaming:!!t.streaming,raw:t.rawContent});return G&&_?.wrap==="char"?fi(Ce,"char",t.id,{skipTags:_.skipTags}):G&&_?.wrap==="word"?fi(Ce,"word",t.id,{skipTags:_.skipTags}):Ce},x=null;if(O?(x=document.createElement("div"),x.innerHTML=T(),x.style.display="none",w.appendChild(x)):t.contentSegments?.length?IS(w,t.contentSegments,Ce=>e({text:Ce,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):w.innerHTML=T(),G&&_?.useCaret&&!O&&R){let Ce=pl(),H=w.querySelectorAll(".persona-stream-char, .persona-stream-word"),Me=H[H.length-1];if(Me?.parentNode)Me.parentNode.insertBefore(Ce,Me.nextSibling);else{let de=w.lastElementChild;de?de.appendChild(Ce):w.appendChild(Ce)}}if(y&&C==="inline"&&t.createdAt){let Ce=gy(t,p,"span");Ce.classList.add("persona-timestamp-inline");let H=w.lastElementChild;H?H.appendChild(Ce):w.appendChild(Ce)}if(k.length>0){let Ce=HS(k,!O&&!!R,()=>{O&&x&&(x.style.display="")});Ce?A.appendChild(Ce):O&&x&&(x.style.display="")}let z=ES(t);if(z.length>0){let Ce=RS(z);Ce&&A.appendChild(Ce)}let W=TS(t);if(W.length>0){let Ce=WS(W);Ce&&A.appendChild(Ce)}let ee=kS(t);if(ee.length>0){let Ce=BS(ee);Ce&&A.appendChild(Ce)}let ne=t.contentSegments?.length?null:PS(t.contextMentions);if(ne&&A.appendChild(ne),A.appendChild(w),y&&C==="below"&&t.createdAt){let Ce=gy(t,p);Ce.classList.add("persona-mt-1"),A.appendChild(Ce)}let he=t.role==="assistant"?SS(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Ce=!!(v&&v.trim()),H=V.placeholder==="skeleton",Me=H&&V.buffer==="line"&&Ce;if(Ce)Me&&A.appendChild(hi());else if(H)A.appendChild(hi());else{let de=DS("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);de&&A.appendChild(de)}}he&&t.stopReason&&!t.streaming&&(R||(w.style.display="none"),A.appendChild(xS(t.stopReason,he)));let ve=t.role==="assistant"&&!t.streaming&&!t.voiceCaption&&t.content&&t.content.trim()&&o?.enabled!==!1,Xe=i?.actionEligibility,Je=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Xe?.canEdit===!0||o?.showQuote===!0&&Xe?.canQuote===!0||hy(o,"user").length>0);if((ve||Je)&&o){let Ce=NS(t,Je?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,Xe);A.appendChild(Ce)}if(!g||t.role==="system")return A;let Wt=P("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),$e=OS(u,t.role);return h==="right"||h==="left"&&t.role==="user"?Wt.append(A,$e):Wt.append($e,A),Wt};var VS=40,$S=(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=se(e.name,VS);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(Y("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(Y("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},yy=(t,e,n={})=>{let o=Y("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let s=P("p","persona-welcome-kicker");s.hidden=!0;let i=P("h2","persona-welcome-title"),l=P("p","persona-welcome-subtitle"),c=Y("div",{className:"persona-welcome-head-text"},s,i),u=Y("div",{className:"persona-welcome-title-row"},o,c);return{host:Y("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)"}},u,l,e),iconHolder:o,kicker:s,title:i,subtitle:l,starterSuggestions:e}},ws=(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)},Fl=(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==="",$S(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-layout",e.layout??"top"),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")},zS="data-persona-welcome-plugin",by="data-persona-welcome-overlay",_l="persona-welcome-overlay-active",yp=new WeakMap,bp=(t,e,n)=>{n.setAttribute(zS,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(by,""),t.classList.contains(_l)||(yp.set(t,t.scrollTop),t.classList.add(_l),t.scrollTop=0)},vp=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(by),t.classList.contains(_l)&&(t.classList.remove(_l),t.scrollTop=yp.get(t)??t.scrollTop,yp.delete(t))},vy=()=>{let t=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},Nl=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",s=Y("div",{className:Di("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(Y("div",{className:"persona-flex"},s)),t.hidden=!1},Cy=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,wy=(t,e)=>{if(Cy()||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 E=getComputedStyle(o);s=parseFloat(E.rowGap)||0;let A=t.previousElementSibling,I=t.nextElementSibling,k=o.getBoundingClientRect().top+(parseFloat(E.borderTopWidth)||0)+(parseFloat(E.paddingTop)||0)-o.scrollTop;i=Math.max(0,A?n.top-A.getBoundingClientRect().bottom-s:n.top-k),l=Math.max(0,I?I.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let u=getComputedStyle(t),p=parseFloat(u.paddingTop)||0,g=parseFloat(u.paddingBottom)||0,y=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${g}px`,marginTop:`${i}px`,marginBottom:`${l}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-s}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,C=()=>{h||(h=!0,t.style.overflow=c,e(y))};return y.finished.then(C).catch(C),y},Sy=(t,e,n,o=260)=>{if(e<=1||Cy()||typeof t.animate!="function"||!t.isConnected)return null;let s=n==="drop"?-e:e;return t.animate([{transform:`translateY(${s}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var US="Hello \u{1F44B}",qS="I can answer questions and help you get things done here.",xy=new WeakSet,$t=(t,e)=>!!t&&t[e]!==void 0,jS=(t,e)=>{!t||t.debug!==!0||!e.length||xy.has(t)||(xy.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Vl=(t,e=t?.launcher?.fullHeight===!0&&!t.launcher.sidebarMode&&t.launcher.mountMode!=="docked")=>{let n=t?.welcome,o=t?.copy,s=t?.future?.v5Defaults===!0,i=n?.layout??(s?"centered":"top"),l=$t(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",c=l==="hero"&&!s&&n?.layout===void 0?"on-first-message":$t(n,"dismiss")?n.dismiss:s||l==="hero"?"on-first-message":"never",u=[];$t(n,"title")&&$t(o,"welcomeTitle")&&u.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),$t(n,"subtitle")&&$t(o,"welcomeSubtitle")&&u.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),$t(n,"variant")&&$t(o,"showWelcomeCard")&&u.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),l==="hero"&&$t(n,"message")&&u.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!s&&n?.layout===void 0&&l==="hero"&&$t(n,"dismiss")&&n.dismiss!=="on-first-message"&&u.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(i==="centered"&&e?"center":"bottom"),g=ki(n?.anchorComposerTop)!==null;return $t(n,"anchorComposerTop")&&!g&&u.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&($t(n,"anchorComposerTop")||$t(n,"composerGap"))&&u.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),jS(t,u),{title:$t(n,"title")?n.title:o?.welcomeTitle??(s?"What can I help with?":US),kicker:n?.kicker??"",subtitle:$t(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(s?"":qS),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:i==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:l,dismiss:c,message:l==="hero"?void 0:n?.message,layout:i,anchor:p,anchorComposerTop:g?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Hl}},Ay=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ss=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var KS="var(--persona-components-panel-maxWidth)",My="var(--persona-components-panel-height)",GS="var(--persona-components-panel-maxHeight)",Pr=t=>{let e=xr(t),n=e.launcherWidth?t?.launcher?.width:e.legacyLauncherWidth?t?.launcherWidth:void 0,o=t?.launcher?.heightOffset??0,s=o===0?`max(200px, ${My})`:`max(200px, calc(${My} - ${o}px))`;return{width:n??Lm,maxWidth:n??KS,height:s,maxHeight:GS}},Ey="16px",wp="10px",Sp="14px",Ty=t=>{let e=t?.launcher?.enabled??!0,n=rt(t);if(Ii(t)){let p=t?.launcher?.composerBar??{},g=P("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Dt);let y=P("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",g.appendChild(y);let h=P("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=p.expandedSize??"anchored",h.style.zIndex=String(t?.launcher?.zIndex??Dt),{wrapper:g,panel:y,pillRoot:h}}if(n){let p=P("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=P("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(g),{wrapper:p,panel:g}}if(!e){let p=P("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=P("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=xr(t),C=y.launcherWidth||y.legacyLauncherWidth||t?.theme?.components?.panel?.width!==void 0?Pr(t).width:"100%";return p.style.width=C,g.style.width="100%",p.appendChild(g),{wrapper:p,panel:g}}let s=t?.launcher??{},i=s.position&&ln[s.position]?ln[s.position]:ln["bottom-right"],l=P("div",`persona-widget-wrapper persona-fixed ${i} persona-transition`);l.style.zIndex=String(t?.launcher?.zIndex??Dt);let c=P("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=Pr(t);return c.style.width=u.width,c.style.maxWidth=u.maxWidth,l.appendChild(c),{wrapper:l,panel:c}},xp=t=>{let e=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":cp(t)}});return e.hidden=!0,e},ky=(t,e)=>{let n=xp("starter"),o=yy(t,n,{flatShadow:rt(t)}),s=Vl(t);Fl(o,s),ws(e,o.host,Ss(s,t?.initialMessages));let i=vy();return Nl(i,s.message,t),{welcome:o,greetingHost:i}},YS=(t,e)=>{let n=P("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}=vs(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:Ey,iconSize:wp});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 J=Cs(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Ey,iconSize:Sp});l=J.button,c=J.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let u=Y("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Y("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"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:g,greetingHost:y}=ky(t,p),{host:h,title:C,subtitle:E}=g,A=g.starterSuggestions,I=P("div","persona-widget-messages persona-flex persona-flex-col");I.style.gap="var(--persona-components-message-gap, 12px)";let L=xp("followUp"),k=Ko(t,!0);k&&(I.style.maxWidth=k,I.style.marginLeft="auto",I.style.marginRight="auto",I.style.width="100%"),p.append(h,y,I,L);let R=Y("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),B=Dl({config:t}),{root:O,textNode:V}=dy();return n.append(u,s,p,R),c&&n.appendChild(c),{container:n,body:p,messagesWrapper:I,starterSuggestions:A,transcriptSuggestions:L,composerOverlay:R,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,welcomeHost:h,welcomeIconHolder:g.iconHolder,greetingHost:y,introKicker:g.kicker,introTitle:C,introSubtitle:E,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:P("span"),headerTitle:P("span"),headerSubtitle:P("span"),header:u,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:O,peekTextNode:V}},Py=(t,e=!0)=>{if(Ii(t))return YS(t,e);let n=Y("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?Bl(t,o,{showClose:e}):kr({config:t,showClose:e}),l=Y("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:u}=ky(t,l),{host:p,title:g,subtitle:y}=c,h=c.starterSuggestions,C=P("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let E=xp("followUp"),A=Ko(t,!1);A&&(C.style.maxWidth=A,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),l.append(p,u,C,E);let I=Wi({config:t}),L=t?.layout?.showFooter!==!1;s?Ri(n,i,t):(i.header.style.display="none",Ri(n,i,t)),n.append(l);let k=Y("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 L||(I.footer.style.display="none"),n.append(I.footer),n.append(k),{container:n,body:l,messagesWrapper:C,starterSuggestions:h,transcriptSuggestions:E,composerOverlay:k,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,welcomeHost:p,welcomeIconHolder:c.iconHolder,greetingHost:u,introKicker:c.kicker,introTitle:g,introSubtitle:y,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:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode}};var Ap=(t,e)=>{let n=P("button");n.type="button",n.innerHTML=`
13
+ `),c=Array.isArray(e.contentParts)&&e.contentParts.length>0,u=s.contentParts.length>0;if(c){let p=[];i&&p.push(zo(i)),p.push(...s.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(u){let p=[];l&&p.push(zo(l)),p.push(...s.contentParts),e.contentParts=p}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.#B&&!n?.voiceTurn&&(this.#B.failed=!0,this.#B=null),(this.#M||this.#y||this.#d||this.#W)&&await this.#Re(),this.stopSpeaking(),this.abortController?.abort(),this.#ee(),this.#j++,this.#ne();let i=n?.voiceTurn?.userMessageId,l=i?this.messages.find(C=>C.id===i&&C.role==="user"):void 0,c=l?.id??Cl(),u=hs();this.#i=null;let p=n?.contentParts&&sf(n.contentParts)?tl:"",g={id:c,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#k(),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??{}};l?(l.viaVoice=!0,delete l.voiceCaption,l.content.trim()!==o&&(l.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#N(g),this.#g(!0);let y=new AbortController;if(this.abortController=y,n?.mentions){let C=this.messages.find(E=>E.id===c)??g;if(await this.#Xe(C,o,n.mentions.finalize),y.signal.aborted||this.abortController!==y)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let C=this.messages.find(A=>A.id===c)??g,E=ah({quote:n.quote,text:C.llmContent??C.content,contentParts:C.contentParts});E.contentParts&&(C.contentParts=E.contentParts),E.llmContent!==void 0&&(C.llmContent=E.llmContent),(E.contentParts||E.llmContent!==void 0)&&(C.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let h=l?[...this.messages.filter(C=>C!==l),{...l,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(h,y,u,c,{composerOptions:n?.composerOptions,interrupt:n?.interrupt,voiceSpoken:!!n?.voiceTurn})}catch(C){if(this.status==="resuming"||this.#s)return;this.#B&&(this.#B.failed=!0);let E=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!E){let A=Gd(C,this.config.errorMessage);if(A){let I={id:u,role:"assistant",createdAt:new Date().toISOString(),content:A,sequence:this.#k()};this.#N(I)}}this.#H("idle"),this.#g(!1),this.abortController=null,E||(C instanceof Error?this.callbacks.onError?.(C):this.callbacks.onError?.(new Error(String(C))))}}resubmitFrom(e,n){let o=lh(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 p=i?void 0:{...s.llmContent!==void 0&&{llmContent:s.llmContent},...s.rawContent!==void 0&&{rawContent:s.rawContent},...s.mentionContext&&{mentionContext:s.mentionContext},...s.contextMentions&&{contextMentions:s.contextMentions},...s.quote&&{quote:s.quote}},g=i?this.#Je(i.options):s.composerOptions,y=i?i.contentSegments:s.contentSegments,h=i?i.options?.quote:void 0,C=i?i.viaVoice:s.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(l??"",{...c?.length?{contentParts:[...c]}:{},...y?.length?{contentSegments:[...y]}:{},...g?{composerOptions:g}:{},...h?{quote:h}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:C===!0}),!0}#Je(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.#M||this.#y||this.#d||this.#W)&&await this.#Re(),this.abortController?.abort(),this.#ne();let e=hs();this.#i=null,this.#g(!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.#s)return;let i=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!i){let l=Gd(s,this.config.errorMessage);if(l){let c={id:e,role:"assistant",createdAt:new Date().toISOString(),content:l,sequence:this.#k()};this.#N(c)}}this.#H("idle"),this.#g(!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.#i=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let l of this.messages)l.streaming&&l.id!==o&&(l.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.#g(!0);let i={};try{await this.client.processStream(e,l=>{let c=this.#o;this.#o=i;try{this.handleEvent(l)}finally{this.#o=c}},n?.assistantMessageId,n?.seedContent),this.#xe(i)}catch(l){if(this.status==="resuming"||this.#s){this.#pt(i);return}this.#xe(i),this.#H("error"),this.webMcpResolveControllers.size===0&&(this.#g(!1),this.abortController=null),this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}}#We(){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.#S}`,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")}#Ze;#j;#de(e){let n=this.#Ze??={s:this,setStreaming:i=>this.#g(i),appendMessage:i=>this.#N(i),nextSequence:()=>this.#k(),settleApprovalPausedToolCall:i=>this.#Oe(i),resumeAfter:i=>this.#n?.executionId===i?this.#n.lastEventId:void 0},o=ih();if(o)return e(o,n);let s=this.#j;return $d().then(i=>s===this.#j?e(i,n):void 0,i=>{this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))})}resolveApproval(e,n,o){return this.#de((s,i)=>s.resolveApproval(i,e,n,o))}resolveAskUserQuestion(e,n){return this.#de((o,s)=>o.resolveAskUserQuestion(s,e,n))}resolveWebMcpToolCall(e){return this.#de((n,o)=>n.resolveWebMcpToolCall(o,e))}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}:{}}})}#et(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let i=this.#p;queueMicrotask(()=>{i===this.#p&&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))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#p;queueMicrotask(()=>{if(e===this.#p)for(let n of[...this.webMcpAwaitBatches.keys()])this.#nt(n)})}#nt(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.#de((s,i)=>s.resolveWebMcpToolCallBatch(i,e,o))}#ee(){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.#p++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#g(!1),this.#H("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.messages=[],this.agentExecution=null,this.#we(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#g(!1),this.#H("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#h}selectArtifact(e){this.#h=e,this.#te()}clearArtifacts(){this.#we()}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.#h=n,this.#te(),e.transcript!==!1&&this.#ot(o),o}#ot(e){let n=`artifact-ref-${e.id}`,o=as(this.config.features?.artifacts,e),s=xd(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})}#Be(){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=as(this.config.features?.artifacts,n),i=xd(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])}#we(){this.artifacts.size===0&&this.#h===null||(this.artifacts.clear(),this.#h=null,this.#te())}#te(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#h})}#rt(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.#h=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.#te()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#K(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#k()}))),this.#g(!1),this.#H("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.#h=n,this.#te()}#st(e){let n=this.agentExecution?.executionId;if(!n||!this.#i||this.agentExecution?.status!=="running")return;let o=this.#n===null;this.#n={executionId:n,lastEventId:e,assistantMessageId:this.#i,status:"running"},this.#dt(o)}#it(){return this.#n!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#De()}#De(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}#Se(){this.#s||!this.#n||typeof this.config.reconnectStream!="function"||(this.#s=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#n}),this.#g(!0),this.#H("resuming"),this.#at().then(e=>{this.#s&&this.#n&&e.begin()}))}#at(){return this.#a?Promise.resolve(this.#a):(this.#v||(this.#v=gh().then(({createReconnectController:e})=>{let n=e(this.#lt());return this.#a=n,n}),this.#v.catch(()=>{this.#v=null})),this.#v)}#lt(){let e=this;return{get config(){return e.config},getResumable:()=>e.#n,clearResumable:()=>e.#pe(),getStatus:()=>e.status,setStatus:n=>e.#H(n),setStreaming:n=>e.#g(n),setReconnecting:n=>{e.#s=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.#N(n),nextSequence:()=>e.#k(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>Gd(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.#s){this.#a?.wake();return}this.#Se()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.#s)return;let n=this.#ct();n||(n=hs(),this.#N({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#k()})),this.#i=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#n={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.#Se()}#ct(){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}#ne(){this.#s=!1,this.#a?.teardown(),this.#pe()}#pe(){this.#c&&(clearTimeout(this.#c),this.#c=null);let e=this.#n!==null;this.#n=null,e&&this.config.onExecutionState?.(null)}#dt(e){let n=this.config.onExecutionState;if(n){if(e){this.#c&&(clearTimeout(this.#c),this.#c=null),n(this.#n);return}this.#c||(this.#c=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#n)},500))}}getResumableHandle(){return this.#n}#H(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#g(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&(this.#xe(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let s=[...this.messages].reverse().find(l=>l.role==="assistant"&&l.content&&!l.voiceProcessing);if(!s||e&&!e.includes(s.id))return;if(this.ttsSpokenMessageIds.has(s.id)){this.ttsSpokenMessageIds.delete(s.id);return}let i=jd(s.content);i.trim()&&this.readAloud.play(s.id,{text:i,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(e){return qd(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=jd(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()}#xe(e){for(let[n,o]of[...this.#e])o===e&&(this.#e.delete(n),this.#Oe(n))}#pt(e){for(let[n,o]of this.#e)o===e&&this.#e.set(n,void 0)}#Oe(e){let n=this.messages.find(c=>c.id===e)?.approval,o=n?.toolCallId,s=o&&this.messages.find(c=>c.toolCall?.id===o),i=s&&s.toolCall;if(!i||i.status==="complete"||n.status==="pending")return;let l={...i,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...s,streaming:!1,toolCall:l})}#N(e){let n=this.#ie(e);this.messages=this.#K([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.#ie(e),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.#N(n);return}this.messages=this.messages.map((s,i)=>{if(i!==o)return s;let l={...s,...n};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});let c=s.agentMetadata?.clientToolAnswer;if(c&&l.agentMetadata&&!l.agentMetadata.clientToolAnswer&&(l.agentMetadata={...l.agentMetadata,clientToolAnswer:c}),s.approval&&n.approval&&s.approval.id===n.approval.id){let y=s.approval,h=n.approval;l.approval={...y,...h,executionId:h.executionId||y.executionId,toolName:h.toolName||y.toolName,description:h.description||y.description,toolType:h.toolType??y.toolType,reason:h.reason??y.reason,parameters:h.parameters??y.parameters,toolCallId:h.toolCallId??y.toolCallId}}let u=n.toolCall?.name,p=n.agentMetadata?.executionId,g=n.toolCall?.id;if(u&&mh(u)&&p&&g&&n.agentMetadata?.awaitingLocalTool===!0){let y=`${p}:${g}`,h=this.webMcpInflightKeys.has(y),C=this.webMcpResolvedKeys.has(y),E=s.toolCall?.name,A=s.agentMetadata?.executionId===p&&s.toolCall?.id===g&&E!==void 0&&mh(E)&&s.toolCall?.status==="complete";(h||C||A)&&(l.agentMetadata={...l.agentMetadata??{},awaitingLocalTool:!1},l.toolCall=s.toolCall,l.streaming=s.streaming)}return l}),this.messages=this.#K(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#ie(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.#k()}}#k(){return this.#m++}#K(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 sw,FileCode as iw,FileSpreadsheet as aw,FileText as Yd,X as lw}from"lucide";var cw={add:t=>af(t)},dw=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Ml={allowedTypes:us,maxFileSize:10*1024*1024,maxFiles:4};function pw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function uw(t){return t==="application/pdf"?Yd:t.startsWith("text/")?Yd:t.includes("word")?Yd:t.includes("excel")||t.includes("spreadsheet")?aw:t==="application/json"?iw:sw}var xi=class t{constructor(e={}){this.attachments=[];this.#e=null;this.#o=new Map;this.#m=!1;this.config={allowedTypes:e.allowedTypes??Ml.allowedTypes,maxFileSize:e.maxFileSize??Ml.maxFileSize,maxFiles:e.maxFiles??Ml.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#e;#o;#m;#n(){return typeof this.config.adapter?.add=="function"}#i(){return this.#n()?this.config.adapter:cw}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML="";for(let n of this.attachments)this.#h(n)}this.#t()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ml.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.#m)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let s=lf(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:pw(),file:o,previewUrl:kd(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#n()?"uploading":"processing",progress:this.#n()?0:void 0};this.attachments.push(i),this.#h(i),n.push(i)}this.#t(),this.#c(),await Promise.all(n.map(o=>this.#s(o)))}async#s(e){let n=new AbortController;this.#o.set(e.id,n);let o=()=>this.#m||n.signal.aborted||this.#o.get(e.id)!==n||!this.attachments.includes(e);try{let s=await this.#i().add(e.file,{signal:n.signal,onProgress:i=>{o()||e.status!=="uploading"||(e.progress=dw(i),this.#p(e),this.#c())}});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.#o.get(e.id)===n&&this.#o.delete(e.id)}this.#p(e),this.#c()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.#m||(n.status=this.#n()?"uploading":"processing",n.progress=this.#n()?0:void 0,n.error=void 0,this.#p(n),this.#c(),this.#s(n))}#a(e){let n=this.#o.get(e);n&&(this.#o.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.#a(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.#e?.querySelector(`[data-attachment-id="${e}"]`);s&&s.remove(),o.status==="ready"&&o.contentPart&&this.#v(o.contentPart),this.#t(),this.#c()}#v(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.#a(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#o.clear(),this.#e&&(this.#e.innerHTML=""),this.#t(),this.#c()}destroy(){if(!this.#m){this.#m=!0;for(let e of this.#o.values())e.abort();this.#o.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#m||this.config.onAttachmentsChange?.(this.getAttachments())}#h(e){if(!this.#e)return;let n=kd(e.file),o=P("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let g=P("img");g.src=e.previewUrl,g.alt=e.file.name,g.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",g.style.width="48px",g.style.height="48px",g.style.objectFit="cover",g.style.borderRadius="8px",o.appendChild(g)}else{let g=P("div");g.style.width="48px",g.style.height="48px",g.style.borderRadius="8px",g.style.backgroundColor="var(--persona-container, #f3f4f6)",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.display="flex",g.style.flexDirection="column",g.style.alignItems="center",g.style.justifyContent="center",g.style.gap="2px",g.style.overflow="hidden";let y=uw(e.file.type),h=yt(y,20,"var(--persona-muted, #6b7280)",1.5);h&&g.appendChild(h);let C=P("span");C.textContent=cf(e.file.type,e.file.name),C.style.fontSize="8px",C.style.fontWeight="600",C.style.color="var(--persona-muted, #6b7280)",C.style.textTransform="uppercase",C.style.lineHeight="1",g.appendChild(C),o.appendChild(g)}let s=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),i=P("div","persona-attachment-progress");i.appendChild(P("div","persona-attachment-progress__bar"));let l=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=se("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);c?l.appendChild(c):l.textContent="\u21BB",l.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.retryAttachment(e.id)}),s.append(i,l),o.appendChild(s);let u=P("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");u.type="button",u.setAttribute("aria-label","Remove attachment"),u.style.position="absolute",u.style.top="-4px",u.style.insetInlineEnd="-4px",u.style.width="18px",u.style.height="18px",u.style.borderRadius="50%",u.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",u.style.border="none",u.style.cursor="pointer",u.style.display="flex",u.style.alignItems="center",u.style.justifyContent="center",u.style.padding="0";let p=yt(lw,10,"var(--persona-text-inverse, #ffffff)",2);p?u.appendChild(p):(u.textContent="\xD7",u.style.color="var(--persona-text-inverse, #ffffff)",u.style.fontSize="14px",u.style.lineHeight="1"),u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(u),this.#e.appendChild(o),this.#S(o,e)}#p(e){let n=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.#S(n,e)}#S(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)}%`:""}}#t(){this.#e&&(this.#e.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 fh=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),gw=(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 hh(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,s=!1,i=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",l=()=>{let g=i();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(y=>Object.freeze({...y}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:g,inputDisabled:t.inputDisabled,sendDisabled:g!=="idle"||t.sendDisabled||t.inputDisabled})},c=()=>(n||(n=l()),n),u=()=>{if(o=!1,s||e.size===0)return;let g=c();for(let y of[...e])try{y(g)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},p=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(u))};return{getState:c,subscribe:g=>(e.add(g),()=>e.delete(g)),setText:g=>{t.text!==g&&(t.text=g,p())},setAttachments:g=>{gw(t.attachments,g)||(t.attachments=[...g],p())},setMentionRefs:g=>{fh(t.mentionRefs,g)||(t.mentionRefs=[...g],p())},setSelectedModelId:g=>{t.selectedModelId!==g&&(t.selectedModelId=g,p())},setActiveModeIds:g=>{fh(t.activeModeIds,g)||(t.activeModeIds=[...g],p())},setQuote:g=>{let y=t.quote;y?.text===g?.text&&y?.messageId===g?.messageId&&y?.sourceLabel===g?.sourceLabel||(t.quote=g?{...g}:void 0,p())},setPendingSubmission:g=>{t.pendingSubmission!==g&&(t.pendingSubmission=g,p())},setPreparing:g=>{t.preparing!==g&&(t.preparing=g,p())},setStreaming:g=>{t.streaming!==g&&(t.streaming=g,p())},setInputDisabled:g=>{t.inputDisabled!==g&&(t.inputDisabled=g,p())},setSendDisabled:g=>{t.sendDisabled!==g&&(t.sendDisabled=g,p())},flush:()=>{o&&u()},destroy:()=>{s=!0,o=!1,e.clear()}}}var Xt=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},yh=(t,e)=>{let n=P("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function bh(t,e={}){let n=Xt(t,"[data-persona-composer-form]"),o=Xt(t,"[data-persona-composer-input]");if(!n||!o){let L=`[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(L);return typeof console<"u"&&console.warn(L),null}let s={header:Xt(t,"[data-persona-composer-header]"),body:Xt(t,"[data-persona-composer-body]"),actionsStart:Xt(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Xt(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Xt(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Xt(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Xt(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=yh("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,u=(I,L,k,R,B)=>{if(L)return L;i.add(I);let O=yh(k,R);return B.appendChild(O),O},p=u("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),g=u("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),y=u("suggestions",s.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),h=u("status",s.status,"persona-widget-composer__status","data-persona-composer-status",t),C=[],E=(I,L)=>I.target===L.target&&I.type===L.type&&I.handler===L.handler,A=Xt(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:l,body:c,actionsStart:p,actionsEnd:g,suggestions:y,status:h,attachmentInput:A,attachmentPreviews:Xt(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Xt(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Xt(t,"[data-persona-composer-submit]")??void 0,micButton:Xt(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(I,L,k,R)=>{I.addEventListener(L,k,R),C.push({target:I,type:L,handler:k,options:R})},removeListener:(I,L,k,R)=>{I.removeEventListener(L,k,R),C=C.filter(B=>!E(B,{target:I,type:L,handler:k}))},destroy:()=>{for(let I of C)I.target.removeEventListener(I.type,I.handler,I.options);C=[]}}}var mw='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',fw=["--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"],Qd="data-persona-menu-focus",hw=new Set(["ArrowDown","ArrowUp","Home","End"]);function vh(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(mw)??t}var yw=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function Ch(t){let e=t.label,n=!1,o=P("div","persona-send-button-wrapper"),s=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Uo} ${Mr}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=Y("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),l=()=>{let S=t.getButtonSize?.()??"";s.style.width=S,s.style.height=S,s.style.minWidth=S,s.style.minHeight=S,s.style.lineHeight="1",s.replaceChildren();let z=se("plus",qn,"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 u=[],p=-1,g=!1,y=()=>{let z=i.getRootNode().activeElement;return z instanceof HTMLElement?z:null},h=()=>{let S=y();for(let z of u){let W=!!S&&vh(z)===S;z.toggleAttribute(Qd,W&&g)}},C=()=>u.filter(S=>S.isConnected||i.contains(S)).map(vh).filter(S=>!yw(S)),E=(S,z)=>{S.forEach((W,ee)=>{W.setAttribute("tabindex",ee===z?"0":"-1")})},A=S=>{let z=C();if(z.length===0)return;let W=(S%z.length+z.length)%z.length;p=W,E(z,W),z[W].focus(),h()},I=()=>o.ownerDocument??document,L=null,k=null,R=null,B=()=>{L&&(I().removeEventListener("focusin",L,!0),L=null)},O=()=>{k&&(i.removeEventListener("focusin",k),k=null),R&&(i.removeEventListener("pointerdown",R,!0),R=null)},V=null,J=()=>(V||(V=dl({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),B()}})),V),_=()=>V?.isOpen===!0,Q=(S=!1)=>{if(_()){V?.close(),s.setAttribute("aria-expanded","false"),B(),O(),p=-1,g=!1;for(let z of u)z.removeAttribute(Qd);S&&s.focus()}},G=(S=0,z=!1)=>{if(n||_())return;g=z,ol(s,i,fw),J().open(),s.setAttribute("aria-expanded","true");let W=C();E(W,-1),A(S<0?W.length-1:S),L=ee=>{let ne=typeof ee.composedPath=="function"?ee.composedPath():[];ne.includes(i)||ne.includes(o)||Q()},I().addEventListener("focusin",L,!0),k=()=>h(),i.addEventListener("focusin",k),R=()=>{g=!1},i.addEventListener("pointerdown",R,!0)},w=S=>{S.preventDefault(),S.stopPropagation(),_()?Q(!0):G(0)},v=S=>{if(S.key==="ArrowDown"||S.key==="Enter"||S.key===" "){S.preventDefault(),g=!0,_()?A(0):G(0,!0);return}S.key==="ArrowUp"&&(S.preventDefault(),g=!0,_()?A(-1):G(-1,!0))},T=S=>{switch(hw.has(S.key)&&(g=!0),S.key){case"ArrowDown":S.preventDefault(),A(p+1);return;case"ArrowUp":S.preventDefault(),A(p-1);return;case"Home":S.preventDefault(),A(0);return;case"End":S.preventDefault(),A(C().length-1);return;case"Escape":S.preventDefault(),S.stopPropagation(),Q(!0);return;case"Tab":Q(!0);return;default:}};return s.addEventListener("click",w),s.addEventListener("keydown",v),i.addEventListener("keydown",T),{trigger:o,triggerButton:s,panel:i,setItems:S=>{for(let W of u)S.includes(W)||W.removeAttribute(Qd);if(u=[...S],!_())return;let z=C();E(z,Math.min(p,z.length-1)),h()},isOpen:_,open:()=>G(0),close:Q,setLabel:S=>{S!==e&&(e=S,c())},applyButtonSize:l,destroy:()=>{n=!0,B(),O(),s.removeEventListener("click",w),s.removeEventListener("keydown",v),i.removeEventListener("keydown",T),V?.destroy(),V=null,o.remove(),i.remove(),u=[]}}}var Kn={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},wh="data-persona-composer-action",Xd="data-persona-composer-disable-when-streaming",bw="core:overflow",vw=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function Cw(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=P("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 Jd(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 Sh=(t,e)=>{!t||typeof console>"u"||console.warn(e)},ww=(t,e)=>e.includes(":")?e:`${t}:${e}`;function Sw(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let u=o.get(c.id);if(u){Sh(e,`[Persona] composer action "${c.id}" is already contributed by ${xh(u)}; the ${xh(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,u,p)=>{let g=p?ww(p,c.id):c.id,y=c.order??Kn.custom;c.placement==="end"&&y>=Kn.send&&(Sh(e,`[Persona] composer action "${g}" ordered at ${y} would render after send; clamped to ${Kn.send-1}.`),y=Kn.send-1),i({id:g,placement:c.placement,presentation:c.presentation??"bar",order:y,sequence:s++,source:u,pluginId:p,action:c})};for(let c of t.configActions??[])l(c,"config");for(let c of t.plugins){if(!c.contributeComposerActions)continue;let u;try{u=c.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,p);continue}for(let p of u??[])l(p,"plugin",c.id)}return n.sort((c,u)=>c.order===u.order?c.sequence-u.sequence:c.order-u.order)}var xh=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",Ah=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,xw=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function Aw(t,e){if(!t||t==="always")return!0;let n=xw(e);return t==="when-text"?n:!n}var jo=t=>t.kind==="custom",Zd=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,Mw=t=>{let e=Zd(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},Ew='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Tw(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(Ew)||o.childNodes.forEach(n)};return n(t),e.trim()}var kw=t=>Tw(t).length===0;function Mh(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(w,v)=>{let T=w.button;if(!T)return;T.setAttribute("role","menuitem"),T.setAttribute("tabindex","-1"),T.className="persona-composer-overflow-menu__item";for(let W of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])T.style[W]="";T.style.lineHeight="1",v.tooltipText?T.setAttribute("title",v.tooltipText):T.removeAttribute("title"),T.replaceChildren();let S=P("span","persona-composer-overflow-menu__icon");if(v.iconName){let W=se(v.iconName,16,"currentColor",1.5);W&&S.appendChild(W)}let z=P("span","persona-composer-overflow-menu__label");z.textContent=v.shortLabel??v.label,T.append(S,z)},l=(w,v)=>{let T=w.button;if(!T)return;if(T.setAttribute("aria-label",v.label),v.pressed===void 0?T.removeAttribute("aria-pressed"):T.setAttribute("aria-pressed",v.pressed?"true":"false"),T.toggleAttribute(Xd,v.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,i(w,v);return}T.removeAttribute("role"),T.removeAttribute("tabindex"),T.removeAttribute("title");let S=s(),z=!!v.shortLabel;if(T.className=ss("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Uo,Mr,z&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),T.style.width=S&&!z?S:"",T.style.height=S??"",T.style.minWidth=S&&!z?S:"",T.style.minHeight=S??"",T.style.fontSize=z?"":"18px",T.style.lineHeight="1",T.style.color=v.iconColor??"",T.style.backgroundColor=v.backgroundColor??"",T.replaceChildren(),v.iconName){let W=se(v.iconName,qn,"currentColor",1.5);W&&T.appendChild(W)}if(z){let W=P("span","persona-composer-action-button__label");W.textContent=v.shortLabel,T.appendChild(W)}else T.firstChild||(T.textContent=v.label);w.tooltip?.destroy(),w.tooltip=Cn({anchor:T,trigger:w.element,text:()=>v.tooltipText??v.label,enabled:!!v.tooltipText})},c=(w,v)=>{let T=w.action,S=Y("button",{attrs:{type:"button"}}),z=S;if(v==="bar"){let ne=P("div","persona-send-button-wrapper");ne.appendChild(S),z=ne}z.setAttribute(wh,w.id);let W={resolved:w,element:z,button:S,owned:!0,managed:!0,busy:!1,visible:!0,mode:v},ee=ne=>{if(ne.preventDefault(),ne.stopPropagation(),W.busy||S.disabled)return;let he=W.resolved.action;W.mode==="menu"&&C?.close(!0);let ve;try{ve=he.onSelect(t.actionContext,ne)}catch(Xe){t.reportError(Xe,{actionId:W.resolved.id});return}!ve||typeof ve.then!="function"||(W.busy=!0,S.setAttribute("aria-busy","true"),ve.catch(Xe=>{t.reportError(Xe,{actionId:W.resolved.id})}).finally(()=>{W.busy=!1,S.removeAttribute("aria-busy")}))};return S.addEventListener("click",ee),W.detach=()=>S.removeEventListener("click",ee),l(W,T),W},u=w=>{let v=w.action,T;try{T=v.render({...t.actionContext,id:w.id,action:v})}catch(S){return t.reportError(S,{actionId:w.id}),null}return T?.element?(T.element.setAttribute(wh,w.id),T.element.toggleAttribute(Xd,v.disableWhenStreaming===!0),{resolved:w,element:T.element,owned:!0,managed:!0,destroy:T.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(w,v)=>{if(w.builtIn){let S=w.builtIn.element;return S?{resolved:w,element:S,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let T=w.action;return T?jo(T)?u(w):c(w,v):null},g=w=>{if(w.detach?.(),w.tooltip?.destroy(),w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0,w.owned){try{w.destroy?.()}catch(v){t.reportError(v,{actionId:w.resolved.id})}w.element.remove()}},y=(w,v)=>{for(let T=0;T<v.length;T++){let S=v[T];if(!S.managed)continue;let z=null;for(let W=T+1;W<v.length;W++){let ee=v[W];if(!ee.managed&&ee.element.parentElement===w){z=ee.element;break}}z?(S.element.parentElement!==w||S.element.nextSibling!==z)&&w.insertBefore(S.element,z):w.lastChild!==S.element&&w.appendChild(S.element)}},h=(w,v)=>{if(w.button){w.button.disabled=v;return}if(!w.owned)return;let T=w.element;T.toggleAttribute("data-disabled",v),T.setAttribute("aria-disabled",v?"true":"false");let S=T instanceof HTMLButtonElement||T instanceof HTMLSelectElement||T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement?T:T.querySelector("button, select, input, textarea");S&&(S.disabled=v)},C=null,E=null,A=null,I=0,L=()=>{let w=t.getOverflow?.();return w?.enabled===!0?w:void 0},k=()=>(C?C.setLabel(t.getOverflowLabel?.()??"More actions"):C=Ch({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),C),R=w=>{E!==w&&(A?.disconnect(),E=w,I=Jd(w),!(typeof ResizeObserver>"u")&&(A=new ResizeObserver(v=>{let S=v[v.length-1]?.contentRect?.width??Jd(w);S!==I&&(I=S,Q())}),A.observe(w)))},B=(w,v)=>{let T=Cw(w.collapseAutoActionsBelow,v);if(T===null)return!1;let S=I||Jd(v);return S>0&&S<T},O=(w,v,T)=>{if(!v)return"bar";if(w.resolved.builtIn){let z=vw(w.resolved.id);return z&&v.includeBuiltIns?.includes(z)?"menu":"bar"}let S=w.resolved.presentation;return S==="overflow"||S==="auto"&&T?"menu":"bar"},V=w=>{let v=w.menuSlot;if(!v)return;if(!kw(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let T=Mw(w.element);if(!T){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=P("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==T&&(w.menuLabel.textContent=T),w.menuLabel.parentElement!==v&&v.appendChild(w.menuLabel)},J=(w,v)=>{if(w.mode===v)return w;let T=w.resolved.action;if(T&&!jo(T)){g(w),e.delete(w.resolved.id);let S=c(w.resolved,v);return e.set(w.resolved.id,S),S}if(v==="menu"){let S=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[pf]:""}});S.appendChild(w.element),uf(Zd(w.element)),w.menuSlot=S;let z=W=>{let ee=Zd(w.element);if(ee.disabled)return;let ne=W.target===ee||ee.contains(W.target);C?.close(!0),ne||ee.click()};S.addEventListener("click",z,!0),w.detachMenuSlot=()=>S.removeEventListener("click",z,!0),w.managed=!0,V(w)}else w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0;return w.mode=v,w},_=(w,v)=>{let T=v.map(S=>S.menuSlot??S.element);for(T.forEach((S,z)=>{let W=w.children[z];W!==S&&(W?w.insertBefore(S,W):w.appendChild(S))});w.children.length>T.length;)w.lastElementChild?.remove()},Q=()=>{if(o)return;let w=t.getBindings();if(!w)return;let v=t.getState(),T=v.phase==="streaming",S=L();S&&R(w.footer);let z=S?B(S,w.footer):!1,W={start:[],end:[]},ee=[];for(let ne of n){let he=e.get(ne.id);if(!he)continue;let ve=ne.action,Xe=ve?Ah(ve.visible,v,!0)&&Aw(ve.visibility,v):!0;if(he.visible!==Xe&&(he.visible=Xe,!Xe&&he.managed&&(he.menuSlot??he.element).remove()),!!Xe){if(he=J(he,O(he,S,z)),ve){let Je=Ah(ve.disabled,v,!1)||ve.disableWhenStreaming===!0&&T;h(he,Je),!jo(ve)&&ve.pressed!==void 0&&he.button?.setAttribute("aria-pressed",ve.pressed?"true":"false")}he.mode==="menu"?(V(he),ee.push(he)):W[ne.placement].push(he)}}if(ee.length>0){let ne=k();_(ne.panel,ee),ne.setItems(ee.map(Je=>Je.menuSlot??Je.element)),ne.applyButtonSize();let he=Number.isFinite(S?.order)?S?.order:Kn.overflow,ve=W.start.findIndex(Je=>Je.resolved.order>he),Xe={resolved:{id:bw,placement:"start",presentation:"bar",order:he,sequence:-1,source:"core"},element:ne.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};W.start.splice(ve<0?W.start.length:ve,0,Xe)}else C&&(C.close(),C.trigger.remove(),C.setItems([]));y(w.actionsStart,W.start),y(w.actionsEnd,W.end)};return{resolve:()=>{if(o)return;let w=Sw(t.collect()),v=new Set(w.map(T=>T.id));for(let[T,S]of e)v.has(T)||(g(S),e.delete(T));for(let T of w){let S=e.get(T.id);if(!S){let ne=p(T,"bar");ne&&e.set(T.id,ne);continue}let z=S.resolved.action,W=T.action;if(!!z!=!!W||z&&W&&jo(z)!==jo(W)||z&&W&&jo(z)&&jo(W)&&z.render!==W.render){g(S),e.delete(T.id);let ne=p(T,S.mode);ne&&e.set(T.id,ne);continue}S.resolved=T,T.builtIn?(S.managed=T.builtIn.managed===!0||S.mode==="menu",T.builtIn.element&&S.mode==="bar"&&(S.element=T.builtIn.element)):W&&!jo(W)?l(S,W):W&&S.element.toggleAttribute(Xd,W.disableWhenStreaming===!0)}n=w,Q()},sync:Q,getResolved:()=>n,getOverflowMenu:()=>C,destroy:()=>{if(!o){o=!0,A?.disconnect(),A=null,E=null;for(let w of e.values())g(w);e.clear(),C?.destroy(),C=null,n=[]}}}}var Pw="core:model",Lw=700,Eh=16,Iw=["--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"],Th=()=>{let t=Y("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=Y("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function kh(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=u=>{let p=t.getSelectedModelId();return u.find(g=>g.id===p)??u[0]},i=()=>{let u=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",g=()=>{let A=t.getModels(),I=A.map(L=>`${L.id}:${L.label}`).join("|");I!==p&&(p=I,u.replaceChildren(...A.map(L=>{let k=Y("option",{attrs:{value:L.id}});return k.textContent=L.label,k}))),u.value=s(A)?.id??""};g(),o=g;let y=()=>{u.value&&t.onSelect(u.value)};u.addEventListener("change",y);let h=A=>A.stopPropagation();u.addEventListener("click",h);let{wrapper:C,chevron:E}=Th();return C.append(u,E),{element:C,destroy:()=>{o===g&&(o=null),u.removeEventListener("change",y),u.removeEventListener("click",h)}}},l=()=>{let u=Y("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"}}),p=P("span","persona-composer-model-picker-label"),g=P("span","persona-composer-model-picker-suffix");u.append(p,g);let y=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),h=new Map,C="",E=null,A=()=>E?.isOpen===!0,I=(v=!1)=>{A()&&(E?.close(),u.setAttribute("aria-expanded","false"),v&&u.focus())},L=v=>{let T=[...h.values()];if(T.length===0)return;let S=(v%T.length+T.length)%T.length;T[S].focus()},k=v=>{if(A())return;E||(E=dl({anchor:u,content:y,placement:"top-start",offset:6,onDismiss:()=>u.setAttribute("aria-expanded","false")})),ol(u,y,Iw),E.open(),u.setAttribute("aria-expanded","true");let S=[...h.keys()].indexOf(s(t.getModels())?.id??"");L(v??(S>=0?S:0))},R=v=>{I(!0),t.onSelect(v)},B=v=>{v.preventDefault(),v.stopPropagation();let T=v.currentTarget.getAttribute("data-persona-model-option");T&&R(T)},O=v=>{let T=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":v.id}});if(v.icon){let ne=se(v.icon,Eh,"currentColor",1.5);if(ne){let he=P("span","persona-composer-model-option-icon");he.appendChild(ne),T.appendChild(he)}}let S=P("span","persona-composer-model-option-body"),z=P("span","persona-composer-model-option-label");if(z.textContent=v.label,S.appendChild(z),v.description){let ne=P("span","persona-composer-model-option-description");ne.textContent=v.description,S.appendChild(ne)}T.appendChild(S);let W=P("span","persona-composer-model-option-check");W.setAttribute("aria-hidden","true");let ee=se("check",Eh,"currentColor",2);return ee&&W.appendChild(ee),T.appendChild(W),T.addEventListener("click",B),T},V=()=>{let v=t.getModels(),T=v.map(W=>`${W.id}:${W.label}:${W.icon??""}:${W.description??""}`).join("|");if(T!==C){C=T;for(let W of h.values())W.removeEventListener("click",B);h.clear(),y.replaceChildren(...v.map(W=>{let ee=O(W);return h.set(W.id,ee),ee}))}let S=s(v);for(let[W,ee]of h)ee.setAttribute("aria-selected",String(W===S?.id));p.textContent=S?.label??"";let z=t.getSuffix?.()??"";g.textContent=z,u.setAttribute("aria-label",[e,[S?.label,z].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let J=v=>{v.preventDefault(),v.stopPropagation(),A()?I(!0):k()},_=v=>{if(v.key==="ArrowDown"){v.preventDefault(),A()?L(0):k(0);return}v.key==="ArrowUp"&&(v.preventDefault(),A()?L(-1):k(-1))},Q=v=>{let T=[...h.values()],S=T.indexOf(v.target?.closest?.(".persona-composer-model-option"));switch(v.key){case"ArrowDown":v.preventDefault(),L(S+1);return;case"ArrowUp":v.preventDefault(),L(S-1);return;case"Home":v.preventDefault(),L(0);return;case"End":v.preventDefault(),L(T.length-1);return;case"Escape":v.preventDefault(),v.stopPropagation(),I(!0);return;case"Tab":I(!0);return;default:}};u.addEventListener("click",J),u.addEventListener("keydown",_),y.addEventListener("keydown",Q);let{wrapper:G,chevron:w}=Th();return G.append(u,w),{element:G,destroy:()=>{o===V&&(o=null),u.removeEventListener("click",J),u.removeEventListener("keydown",_),y.removeEventListener("keydown",Q);for(let v of h.values())v.removeEventListener("click",B);h.clear(),E?.destroy(),E=null,y.remove()}}};return{action:{id:Pw,kind:"custom",placement:"end",order:Lw,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var Hw=":scope > [data-persona-composer-mode]";function Ph(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=p=>{let g=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let E=P("span","persona-mention-chip-icon"),A=se(p.iconName,12,"currentColor",1.5);A&&E.appendChild(A),g.appendChild(E)}let y=P("span","persona-mention-chip-label");y.textContent=p.shortLabel??p.label,g.appendChild(y);let h=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),C=se("x",12,"currentColor",2);return C?h.appendChild(C):h.textContent="\xD7",h.addEventListener("click",E=>{E.preventDefault(),E.stopPropagation(),t.onRemove(p.id)}),g.appendChild(h),g},l=()=>Array.from(e.querySelectorAll(Hw)),c=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let g=()=>{p.remove(),cl(e)},y=e.ownerDocument.defaultView,h=typeof y?.getComputedStyle=="function"?y.getComputedStyle(p).animationName:"";if(!h||h==="none"){g();return}p.addEventListener("animationend",g,{once:!0}),p.addEventListener("animationcancel",g,{once:!0})},u=()=>{for(let p of l())p.remove()};return{element:e,render:(p,g)=>{if(o)return;let y=g.filter(A=>p.includes(A.id)),h=y.map(A=>`${A.id}:${A.shortLabel??A.label}`).join("|");if(h===n)return;n=h;let C=new Map;for(let A of l()){let I=A.getAttribute("data-persona-composer-mode");I&&y.some(k=>k.id===I)&&!A.hasAttribute("data-persona-chip-exit")?C.set(I,A):A.hasAttribute("data-persona-chip-exit")||c(A)}let E=e.firstChild;for(let A of y){let I=C.get(A.id);I||(I=i(A),s.has(A.id)||(I.setAttribute("data-persona-chip-enter",""),I.addEventListener("animationend",()=>I?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(A.id),I!==E&&e.insertBefore(I,E),E=I.nextSibling}cl(e)},destroy:()=>{o=!0,u(),cl(e)}}}var Lh=t=>`core:mode:${t}`;var ep=t=>Math.min(300+t,499),Ih=t=>`core:mode-group:${t}`;function El(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function Rw(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Hh(t,e){return t?.length?t.filter(n=>!El(n.groupId,e)&&!Rw(n.groupId,e)):[]}var Ww=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Rh(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(Ww(s,o)==="single"){let c=n.filter(u=>u.groupId===s.groupId).map(u=>u.id);l=new Set([...l].filter(u=>!c.includes(u)))}l.add(e)}return n.filter(c=>l.has(c.id)).map(c=>c.id)}function Tl(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Wh(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Bh(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var Bw=16;function Dh(t){let e=null;return{action:{id:Ih(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=Y("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=p=>{p.preventDefault(),p.stopPropagation();let y=p.currentTarget.getAttribute("data-persona-composer-mode");!y||t.getActiveIds().includes(y)&&t.getGroup()?.selection==="single"||t.onSelect(y)},c=p=>{let g=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let h=se(p.iconName,Bw,"currentColor",1.5);h&&g.appendChild(h)}let y=P("span","persona-composer-segmented-label");return y.textContent=p.shortLabel??p.label,g.appendChild(y),g.addEventListener("click",l),g},u=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let g=t.getModes(),y=g.map(C=>`${C.id}:${C.shortLabel??C.label}:${C.iconName??""}`).join("|");if(y!==i){i=y;for(let E of s.values())E.removeEventListener("click",l);s.clear();let C=g.map(E=>{let A=c(E);return s.set(E.id,A),A});o.replaceChildren(...C)}let h=t.getActiveIds();for(let[C,E]of s)E.setAttribute("aria-pressed",String(h.includes(C)))};return u(),e=u,{element:o,destroy:()=>{e===u&&(e=null);for(let p of s.values())p.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function Oh(t){let e=Y("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,s=i=>{let l=P("span","persona-composer-quote-bar"),c=P("div","persona-composer-quote-content");if(i.sourceLabel){let y=P("div","persona-composer-quote-source");y.textContent=i.sourceLabel,c.appendChild(y)}let u=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});u.textContent=Sl(i.text),c.appendChild(u);let p=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),g=se("x",12,"currentColor",2);g?p.appendChild(g):p.textContent="\xD7",p.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),t.onDismiss()}),e.replaceChildren(l,c,p)};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 _h(t){let e=Y("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,u,p)=>{let g=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[u]:""}}),y=se(l,12,"currentColor",2);return y?g.appendChild(y):g.textContent=c,g.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),g},i=l=>{let c=Sl(l.text??"",90);if(c)return c;let u=l.contentParts?.length??0;return u>0?u===1?"1 attachment":`${u} attachments`:(l.mentionRefs?.length??0)>0?l.mentionRefs.map(g=>g.label).join(", "):"Queued message"};return{element:e,render:l=>{if(o||l===n)return;if(n=l,!l){e.replaceChildren(),e.style.display="none";return}let c=P("span","persona-composer-pending-badge");c.textContent=t.label??"Sends next";let u=Y("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});u.textContent=i(l),e.replaceChildren(c,u,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 Fh(t){let e=Y("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=Y("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=P("div","persona-message-edit-actions"),i=(c,u,p,g)=>{let y=Y("button",{className:`persona-message-edit-button ${u}`,attrs:{type:"button",[p]:""},text:c});return y.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),g()}),y},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 Nh(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 Vh(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(u=>n.has(u.sourceId)),s=o.length===(t.mentionRefs?.length??0)&&o.length>0,i=new Set(e.modes.map(u=>u.id)),l=(t.activeModeIds??[]).filter(u=>i.has(u)),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 $h(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 zh(t){return t.wrapped||t.text.includes(`
14
+ `)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission)}function Uh(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function qh(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 tp(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 Kh(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var Dw=t=>typeof t?.then=="function";function jh(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 Gh(t,e,n){let o;try{o=t(tp(e),{signal:n})}catch(s){return{status:"error",error:s}}return Dw(o)?Promise.resolve(o).then(s=>n.aborted?{status:"aborted"}:jh(e,s),s=>n.aborted?{status:"aborted"}:{status:"error",error:s}):jh(e,o)}var kl=t=>t?.launcher?.variant??(t?.future?.v5Defaults===!0?"circle":"pill"),Pl={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var Il="16px",Hl="transparent",Ow=(()=>{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})(),Ai={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:Ow,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"}},Ll={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"}},ln={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:Dm,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Il,canvasBackground:Hl,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",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"}}},_w=Ai.colors.gray,Fw={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},Nw={...Ai,colors:{...Ai.colors,gray:_w}},Vw={...Ai,colors:{...Ai.colors,gray:Fw},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var $w=Ll,zw={...Ll,colors:{...Ll.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Ll.typography,fontSize:"14px",lineHeight:"1.5"}};var op=ln,Uw={...ln,launcher:Pl,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...ln.input,borderRadius:"palette.radius.full"},introCard:{...ln.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...ln.suggestion.chip,fontWeight:"400"},card:{...ln.suggestion.card,fontWeight:"400"},list:{...ln.suggestion.list,fontWeight:"400"}},panel:{...ln.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...ln.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...ln.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...ln.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...ln.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...ln.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}};var qw=t=>Ar({future:t}),rp=t=>qw(t)==="v5"?{palette:Vw,semantic:zw,components:Uw}:{palette:Nw,semantic:$w,components:op};function Pt(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."))?Pt(t,o):o}function Qh(t){let e={};function n(o,s){for(let[i,l]of Object.entries(o)){let c=`${s}.${i}`;if(typeof l=="string"){let u=Pt(t,l);u!==void 0&&(e[c]={path:c,value:u,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 jw(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 Xh(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]=Xh(i,s):n[o]=s}return n}function Kw(t,e){return e?Xh(t,e):t}function ys(t,e={}){let n=rp(e.future),o={palette:n.palette,semantic:n.semantic,components:n.components},s={palette:{...o.palette,...t?.palette,colors:{...o.palette.colors,...t?.palette?.colors},spacing:{...o.palette.spacing,...t?.palette?.spacing},typography:{...o.palette.typography,...t?.palette?.typography},shadows:{...o.palette.shadows,...t?.palette?.shadows},borders:{...o.palette.borders,...t?.palette?.borders},radius:{...o.palette.radius,...t?.palette?.radius}},semantic:{...o.semantic,...t?.semantic,colors:{...o.semantic.colors,...t?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...t?.semantic?.spacing},typography:{...o.semantic.typography,...t?.semantic?.typography}},components:Kw(o.components,t?.components)},i=t?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let g of["rowHeight","labelSize","iconSize","indent","bodySurface"])i?.[g]!==void 0&&(s.components[p][g]=i[g]);let l=t?.components?.collapsibleWidget?.surface;l!==void 0&&i?.bodySurface===void 0&&(s.components.activity={...s.components.activity,bodySurface:l});let c=t?.components?.header;c?.padding!==void 0&&c.minimalPadding===void 0&&(s.components.header.minimalPadding=s.components.header.padding);let u=t?.components?.message;if(u?.gap!==void 0&&u.fullscreenGap===void 0&&(s.components.message.fullscreenGap=s.components.message.gap),e.validate!==!1){let p=jw(s);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(g=>g.message).join(", ")}`)}if(e.plugins)for(let p of e.plugins)s=p.transform(s);return s}var np=t=>t.trim()==="0"?"0px":t,Yh="--persona-",Gw=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(u=>{let p=u.endsWith("%"),g=parseFloat(p?u.slice(0,-1):u);return p?g/100*255:g}))}}if(!n||n.some(l=>!Number.isFinite(l)))return;let[o,s,i]=n.map(l=>{let c=Math.max(0,Math.min(255,l))/255;return c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4)});return .2126*o+.7152*s+.0722*i},Yw=.179,kt=(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[Yh+i],s!==void 0)break;s!==void 0&&(t[Yh+n]=s)}};function Jh(t){let e=Qh(t),n={};for(let[H,Ee]of Object.entries(e)){let de=H.replace(/\./g,"-");n[`--persona-${de}`]=Ee.value}kt(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"],kt(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"]]),kt(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"]}`,kt(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"]??Il,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Hl,kt(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"]]),kt(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"],kt(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"],kt(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 u=n["--persona-components-history-railHeader-background"];u&&(n["--persona-history-rail-header-bg"]=u);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let g=n["--persona-components-history-railHeader-minHeight"];g&&(n["--persona-history-rail-header-min-height"]=g);for(let[H,Ee]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let de=n[`--persona-components-history-overlay-${H}`];de&&(n[`--persona-history-overlay-${Ee}`]=de)}for(let[H,Ee]of[["background","bg"],["borderRadius","radius"]]){let de=n[`--persona-components-history-menu-${H}`];de&&(n[`--persona-history-menu-${Ee}`]=de)}let y=t.components?.history?.motion;if(y){let H=In=>{if(In===void 0)return;let Ps=String(In).trim();return/^\d+(\.\d+)?$/.test(Ps)?`${Ps}ms`:Ps},Ee=H(y.enterDurationMs);Ee!==void 0&&(n["--persona-history-enter-ms"]=Ee);let de=H(y.exitDurationMs);de!==void 0&&(n["--persona-history-exit-ms"]=de),y.enterEasing&&(n["--persona-history-enter-easing"]=y.enterEasing),y.exitEasing&&(n["--persona-history-exit-easing"]=y.exitEasing)}let h=n["--persona-components-history-dangerForeground"];h&&(n["--persona-history-danger-fg"]=h),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 H of["scrim","shadow"]){let Ee=n[`--persona-components-history-confirm-${H}`];Ee&&(n[`--persona-history-confirm-${H}`]=Ee)}for(let[H,Ee]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let de=n[`--persona-components-tooltip-${H}`];de&&(n[`--persona-tooltip-${Ee}`]=de)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[H,Ee]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let de=n[`--persona-components-messageActions-${H}`];de&&(n[`--persona-message-action-${Ee}`]=de)}kt(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let C=n["--persona-components-introCard-background"],E=n["--persona-components-introCard-shadow"],A=(!C||C==="transparent"||C==="none")&&(!E||E==="none"),I=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=A&&I==="1.5rem"?"1.5rem 0":I,kt(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"]]),kt(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 L=n["--persona-components-markdown-heading-h1-fontSize"];L&&(n["--persona-md-h1-size"]=L);let k=n["--persona-components-markdown-heading-h1-fontWeight"];k&&(n["--persona-md-h1-weight"]=k);let R=n["--persona-components-markdown-heading-h2-fontSize"];R&&(n["--persona-md-h2-size"]=R);let B=n["--persona-components-markdown-heading-h2-fontWeight"];B&&(n["--persona-md-h2-weight"]=B);let O=n["--persona-components-markdown-prose-fontFamily"];O&&O!=="inherit"&&(n["--persona-md-prose-font-family"]=O),kt(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"]]),kt(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),kt(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),kt(n,[["md-hr-color","components-markdown-hr-color","divider"]]),kt(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"]]);let V=[["container","surface"],["surface","surface"],["border","border"]];for(let[H,Ee]of V){let de=n[`--persona-components-collapsibleWidget-${H}`]??n[`--persona-${Ee}`];de!==void 0&&(n[`--persona-cw-${H}`]=de,n[`--cw-${H}`]=de)}kt(n,[["message-border","components-message-border","border"]]),kt(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-border-width","components-message-assistant-borderWidth"],["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 J=t.components,_=J?.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 Q=J?.labelButton;Q&&(Q.background&&(n["--persona-label-btn-bg"]=Q.background),Q.border&&(n["--persona-label-btn-border"]=Q.border),Q.color&&(n["--persona-label-btn-color"]=Q.color),Q.padding&&(n["--persona-label-btn-padding"]=Q.padding),Q.borderRadius&&(n["--persona-label-btn-radius"]=Q.borderRadius),Q.hoverBackground&&(n["--persona-label-btn-hover-bg"]=Q.hoverBackground),Q.fontSize&&(n["--persona-label-btn-font-size"]=Q.fontSize),Q.gap&&(n["--persona-label-btn-gap"]=Q.gap));let G=J?.toggleGroup;G&&(G.gap&&(n["--persona-toggle-group-gap"]=G.gap),G.borderRadius&&(n["--persona-toggle-group-radius"]=G.borderRadius));let w=J?.artifact;if(w?.toolbar){let H=w.toolbar;H.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=H.iconHoverColor),H.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=H.iconHoverBackground),H.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=H.iconPadding),H.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=H.iconBorderRadius),H.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=H.iconBorder),H.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=np(H.toggleGroupGap)),H.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=H.toggleBorderRadius),H.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=np(H.toggleGroupPadding)),H.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=H.toggleGroupBorder),H.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=H.toggleGroupBorderRadius),H.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Pt(t,H.toggleGroupBackground)??H.toggleGroupBackground),H.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=H.copyBackground),H.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=H.copyBorder),H.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=H.copyColor),H.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=np(H.copyBorderRadius)),H.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=H.copyPadding),H.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=H.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??H.copyMenuBackground),H.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=H.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??H.copyMenuBorder),H.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=H.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??H.copyMenuShadow),H.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=H.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??H.copyMenuBorderRadius),H.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=H.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??H.copyMenuItemHoverBackground),H.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=H.iconBackground),H.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=H.toolbarBorder)}if(w?.tab){let H=w.tab;H.background&&(n["--persona-artifact-tab-bg"]=H.background),H.activeBackground&&(n["--persona-artifact-tab-active-bg"]=H.activeBackground),H.activeBorder&&(n["--persona-artifact-tab-active-border"]=H.activeBorder),H.borderRadius&&(n["--persona-artifact-tab-radius"]=H.borderRadius),H.textColor&&(n["--persona-artifact-tab-color"]=H.textColor),H.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=H.hoverBackground),H.listBackground&&(n["--persona-artifact-tab-list-bg"]=H.listBackground),H.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=H.listBorderColor),H.listPadding&&(n["--persona-artifact-tab-list-padding"]=H.listPadding)}if(w?.pane){let H=w.pane;if(H.toolbarBackground){let Ee=Pt(t,H.toolbarBackground)??H.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ee}}if(w?.card){let H=w.card;H.background&&(n["--persona-artifact-card-bg"]=H.background),H.border&&(n["--persona-artifact-card-border"]=H.border),H.borderRadius&&(n["--persona-artifact-card-radius"]=H.borderRadius),H.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=H.hoverBackground),H.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=H.hoverBorderColor)}if(w?.inline){let H=w.inline;H.background&&(n["--persona-artifact-inline-bg"]=Pt(t,H.background)??H.background),H.border&&(n["--persona-artifact-inline-border"]=H.border),H.borderRadius&&(n["--persona-artifact-inline-radius"]=H.borderRadius),H.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Pt(t,H.chromeBackground)??H.chromeBackground),H.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Pt(t,H.chromeBorder)??H.chromeBorder),H.titleColor&&(n["--persona-artifact-inline-title-color"]=Pt(t,H.titleColor)??H.titleColor),H.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Pt(t,H.mutedColor)??H.mutedColor),H.frameHeight&&(n["--persona-artifact-inline-frame-height"]=H.frameHeight)}let v=J?.code;v&&(v.keywordColor&&(n["--persona-code-keyword-color"]=v.keywordColor),v.stringColor&&(n["--persona-code-string-color"]=v.stringColor),v.commentColor&&(n["--persona-code-comment-color"]=v.commentColor),v.numberColor&&(n["--persona-code-number-color"]=v.numberColor),v.tagColor&&(n["--persona-code-tag-color"]=v.tagColor),v.attrColor&&(n["--persona-code-attr-color"]=v.attrColor),v.propertyColor&&(n["--persona-code-property-color"]=v.propertyColor),v.lineNumberColor&&(n["--persona-code-line-number-color"]=v.lineNumberColor),v.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=v.gutterBorderColor),v.background&&(n["--persona-code-bg"]=Pt(t,v.background)??v.background));let T=n["--persona-surface"],S=n["--persona-container"],z=n["--persona-palette-colors-gray-100"]??"#f3f4f6",W=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ee=n["--persona-palette-colors-gray-300"]??"#d1d5db",ne=!S||S===T,he=Gw(T??n["--persona-background"]),ve=ne&&he!==void 0&&he<Yw,Xe=ve?"rgba(255, 255, 255, 0.08)":z,Je=ve?"rgba(255, 255, 255, 0.12)":W,Wt=ve?"rgba(255, 255, 255, 0.16)":ee,$e=ne?Xe:S,Ce=ne?Je:S;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??$e,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Ce,ne&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??Wt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??$e,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??$e,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??$e,n}var Qw=t=>!!t&&"launcher"in t&&(t.launcher?.sidebarMode===!0||t.launcher?.mountMode==="docked"),Zh=(t,e)=>{if(!e||!Qw(e))return t;let n=e.theme?.components?.panel?.width,o=e.darkTheme?.components?.panel?.width;return(Ei(e)==="dark"?o??n:n)!=null?t:{...t,components:{...t.components,panel:{...t.components.panel,width:Ar(e)==="v5"?"400px":"420px"}}}},Xw={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"}}},Mi={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)"}}}},sp=Xw,Jw={...sp,colors:{...sp.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},Zw=Mi,eS={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",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"}}},components:{...Mi.components,button:{...Mi.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...Mi.components?.eventStream,badge:{...Mi.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},tS=t=>Ar({future:t})==="v5"?{palette:Jw,components:eS}:{palette:sp,components:Zw},ey=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},ip=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",nS=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":ip()},Ei=t=>nS(t),oS=(t,e={})=>ys(t,e),rS=(t,e={})=>{let n=tS(e.future),o=Sr(n.components,t??{})??{};return ys({...o,palette:{...o.palette,colors:Ar(e)==="v5"?Sr(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:e.future})},ho=t=>{let e=Ei(t),n=ey(t?.theme),o=kl(t)==="circle"?Pl:{...op.launcher,...t?.future?.v5Defaults?{offset:"1.5rem"}:{}},s=Sr({components:{launcher:o}},n),i=ey(t?.darkTheme);return Zh(e==="dark"?rS(Sr(s??{},i??{}),{future:t?.future}):oS(s,{future:t?.future}),t)},sS=t=>Jh(t),Ti=(t,e)=>{let n=ho(e),o=sS(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",Ei(e)),t.setAttribute("data-persona-defaults",Ar(e))},Rl=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(ip())});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(ip());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 bb,Check as vb,Copy as Cb}from"lucide";var Ko=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Wl="24px",ap=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",ki=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},ty=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);import{Idiomorph as iS}from"idiomorph";var Bl=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;iS.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 ny=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var lp={index:-1,draft:""};function oy(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 ry(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 sy(){return new Map}function iy(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function ay(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function ly(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:vT,load:aS}=je({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var cy=aS;function cp(t,e=Dt){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 Pi=0,Go=null;function dp(t=document){if(Pi++,Pi===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Go={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,Pi=Math.max(0,Pi-1),Pi===0&&Go)){let n=t.body,o=t.defaultView??window;n.style.overflow=Go.originalOverflow,n.style.position=Go.originalPosition,n.style.top=Go.originalTop,n.style.width=Go.originalWidth,o.scrollTo(0,Go.scrollY),Go=null}}}var Li={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},rt=t=>(t?.launcher?.mountMode??"floating")==="docked",Ii=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",wn=t=>{let e=t?.launcher?.dock,n=xr(t).dockWidth?e?.width:Pt(ho(t),"components.panel.width");return{side:e?.side??Li.side,width:n??Li.width,animate:e?.animate??Li.animate,reveal:e?.reveal??Li.reveal,maxHeight:e?.maxHeight??Li.maxHeight}};import{ArrowRight as lS}from"lucide";var pp=t=>t==="followUp"?"follow-up":t,up=(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"}},dy=new WeakSet,cS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,dS=t=>{cS()||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"})})},gp=t=>{let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:u,chipsConfig:p,session:g,getTextarea:y,eventTarget:h,submitPrompt:C}=t,E=o==="followUp",A=e.behavior,I=()=>{if(g.isStreaming())return;let R={suggestion:{...e},surface:o,source:s,behavior:A},B=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:R,bubbles:!0,composed:!0,cancelable:!0}));if(E&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!B)return;for(let V of u)if(V.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let O=y();if(A==="fill"){O.value=e.prompt,O.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),O.focus();return}if(C){C(e.prompt);return}O.value="",g.sendMessage(e.prompt)},L=()=>{let R=P("button",`persona-suggestion persona-suggestion--${i}`);if(R.type="button",R.disabled=l,R.dataset.suggestionId=e.id,R.dataset.emphasis=e.emphasis,R.dataset.behavior=A,i==="chip"&&(p?.fontWeight&&(R.style.fontWeight=p.fontWeight),p?.paddingX&&(R.style.paddingLeft=p.paddingX,R.style.paddingRight=p.paddingX),p?.paddingY&&(R.style.paddingTop=p.paddingY,R.style.paddingBottom=p.paddingY)),e.icon){let O=se(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);O&&(O.classList.add("persona-suggestion__icon"),e.iconColor&&(O.style.color=e.iconColor),R.appendChild(O))}let B=P("span","persona-suggestion__copy");if(B.appendChild(Y("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&B.appendChild(Y("span",{className:"persona-suggestion__description",text:e.description})),R.appendChild(B),i!=="chip"){let O=yt(lS,16,"currentColor",1.8);O&&(O.classList.add("persona-suggestion__arrow"),R.appendChild(O))}return R.addEventListener("click",I),R},k=null;for(let R of u)if(R.renderSuggestion&&(k=R.renderSuggestion({suggestion:{...e},index:n,surface:o,source:s,variant:i,streaming:l,config:c,defaultRenderer:L,select:I}),k))break;return k??=L(),k.dataset.suggestionId||=e.id,k.dataset.behavior||=A,k.dataset.emphasis||=e.emphasis,k instanceof HTMLButtonElement||k.setAttribute("aria-disabled",l?"true":"false"),k},Hi=t=>{let e=[],n=[],o=null,s=null,i=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},l=()=>{if(s=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){i();return}let g=Math.max(0,t.scrollWidth-t.clientWidth);if(g<=1){i();return}let y=getComputedStyle(t).direction==="rtl",h=Math.min(g,Math.max(0,Math.abs(t.scrollLeft))),C=4,E=h<=C,A=h>=g-C,I=y?!A:!E,L=y?!E:!A;t.toggleAttribute("data-scroll-left",I),t.toggleAttribute("data-scroll-right",L)},c=()=>{if(s!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&l();return}s=requestAnimationFrame(l)};t.addEventListener("scroll",c,{passive:!0});let u=typeof ResizeObserver=="function"?new ResizeObserver(c):null;return u?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",c),u?.disconnect(),s!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(s),s=null},render:(g,y,h,C,E,A)=>{t.replaceChildren(),e.length=0,n.length=0;let I=A?.source??"config",L=A?.surface??(I==="config"?"starter":"followUp"),k=L==="followUp",R=A?.variant??"chip",B=A?.behavior??"send",O=A?.overflow??"wrap",V=A?.config??{},J=A?.plugins??[],_=typeof A?.maxItems=="number"?Math.max(0,Math.floor(A.maxItems)):void 0,Q=k?"followUps":"starters";!dy.has(V)&&V.debug===!0&&R!=="chip"&&V.suggestions?.[Q]?.overflow!==void 0&&(dy.add(V),console.info(`[persona] suggestions.${Q}.overflow applies to the "chip" variant only; the "${R}" variant manages its own stacking.`));let G=W=>W.map(up).filter(ee=>ee!==null).map(ee=>({...ee,behavior:ee.behavior??B})),w=G(g??[]);J.forEach(W=>{W.transformSuggestions&&(w=G(W.transformSuggestions({suggestions:w.map(ee=>({...ee})),surface:L,source:I,config:V})))});let v=_===void 0?w:w.slice(0,_);if(!v.length){t.hidden=!0,o=null,i();return}if(!k&&(C??y.getMessages()).some(ee=>ee.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=pp(L),t.dataset.variant=R,t.dataset.overflow=O;let T=document.createDocumentFragment(),S=y.isStreaming();v.forEach((W,ee)=>{let ne=gp({item:W,index:ee,surface:L,source:I,variant:R,streaming:S,config:V,plugins:J,chipsConfig:E,session:y,getTextarea:()=>h,eventTarget:t,submitPrompt:A?.submitPrompt});T.appendChild(ne),n.push(ne),[...ne instanceof HTMLButtonElement?[ne]:[],...Array.from(ne.querySelectorAll("button"))].forEach(ve=>{e.includes(ve)||(ve.disabled=S,e.push(ve))})}),t.appendChild(T),l(),c();let z=JSON.stringify({normalized:v,surface:L,variant:R,source:I});z!==o&&(o=z,dS(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:v.map(W=>({...W})),surface:L,source:I,variant:R},bubbles:!0,composed:!0})),k&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:v.map(W=>W.prompt)},bubbles:!0,composed:!0})))}}};var cn={"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 pS="persona-header-control",uS="persona-header-control--glyph",gS="persona-header-control--sparse",mS=20,fS={x:[1.4,1.05]},py="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",hS="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Dl=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=fS[e]??[1,1.5],c=!o;t.classList.toggle(uS,c),t.classList.toggle(gS,c&&i!==1);let u=parseFloat(o??"")||mS,p=se(e,`${Math.round(u*i)}px`,"currentColor",l);p?(p.style.display="block",c||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((l/1.5).toFixed(4))})`),t.replaceChildren(p)):s&&(t.textContent=s)},bs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=py,size:c,iconSize:u,color:p,backgroundColor:g,borderWidth:y,borderColor:h,borderRadius:C,paddingX:E,paddingY:A,hidden:I,extraClassName:L,attrs:k}=t,R=P("div",l),B=!!(y||h),O=Y("button",{className:ss(pS,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"persona-bg-transparent hover:persona-bg-gray-100",!B&&"persona-border-none",!C&&"persona-rounded-full",L),attrs:{type:"button","aria-label":e,...k},style:{width:c,height:c,minWidth:c,minHeight:c,display:I?"none":void 0,color:p||Vt.actionIconColor,backgroundColor:g,border:B?`${y||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:C,paddingLeft:E,paddingRight:E,paddingTop:A,paddingBottom:A}});return s?Dl(O,s,{iconSize:u,iconText:i}):i&&(O.textContent=i),R.appendChild(O),Cn({anchor:O,trigger:R,text:()=>O.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:O,wrapper:R}},vs=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=py,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",u=l.closeButtonShowTooltip??!0,{button:p,wrapper:g}=bs({ariaLabel:c,tooltip:u,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:p,wrapper:g}},Cs=(t,e={})=>{let{wrapperClassName:n=hS,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",u=l.showTooltip??!0,{button:p,wrapper:g}=bs({ariaLabel:c,tooltip:u,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:p,wrapper:g}};var Vt={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-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},mp={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)"},yS={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)"},kr=t=>{let{config:e,showClose:n=!0}=t,o=Y("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:Vt.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??Ua,l=s.closeButtonPlacement??"inline",c=s.headerIconHidden??!1,u=s.headerIconName,p=Y("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(u){let O=parseFloat(i)||24,V=se(u,O*.6,"currentColor",1);V?(V.style.width=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,V.style.height=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(V)):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let O=P("img");O.src=e.launcher.iconUrl,O.alt="",O.className="persona-rounded-xl persona-object-cover",O.style.height=i,O.style.width=i,p.replaceChildren(O)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let g=P("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),y=Y("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Vt.titleColor,...mp}}),h=Y("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Vt.subtitleColor,...yS}});g.append(y,h),c?o.append(g):o.append(p,g);let C=s.clearChat??{},E=C.enabled??!0,A=C.placement??"inline",I=null,L=null;if(E){let V=Cs(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});I=V.button,L=V.wrapper,A==="top-right"&&(L.style.right="48px"),A==="inline"&&o.appendChild(L)}let k=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":E&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:B}=vs(e,{showClose:n,wrapperClassName:k});return l!=="top-right"&&o.appendChild(B),{header:o,iconHolder:p,headerTitle:y,headerSubtitle:h,closeButton:R,closeButtonWrapper:B,clearChatButton:I,clearChatButtonWrapper:L}},Ri=(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 bS=t=>{let e=kr({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 vS(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=bs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Ef(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=Tf(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=Of({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 CS=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:i}=t,l=e?.launcher??{},c=P("div","persona-flex persona-items-center persona-justify-between");c.setAttribute("data-persona-theme-zone","header"),c.style.minHeight=Vt.minHeight,c.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",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 u=s?.titleMenu,p,g;if(u){let B=Ff({label:l.title??"Chat Assistant",menuItems:u.menuItems,onSelect:O=>{let V=_=>{_===!1&&B.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:O}}))},J=u.onSelect(O);J instanceof Promise?J.then(V,()=>{}):V(J)},hover:u.hover,className:""});p=B.element,p.style.color=Vt.titleColor,g=p.querySelector(".persona-combo-btn-label")??p}else{if(p=P("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=P("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=Vt.titleColor,Object.assign(g.style,mp),g.textContent=l.title??"Chat Assistant",p.appendChild(g),s?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let O=s.onTitleClick;p.addEventListener("click",V=>{V.target.closest("button")||O()}),p.addEventListener("keydown",V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),O())})}let B=s?.titleRowHover;B&&(p.style.borderRadius=B.borderRadius??"10px",p.style.padding=B.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=B.background??"",p.style.borderColor=B.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}c.appendChild(p);let y="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:C}=vs(e,{showClose:n,wrapperClassName:y});o&&h.addEventListener("click",o);let E=P("div","persona-flex persona-items-center persona-gap-1");u||vS(E,s?.trailingActions,s?.onAction??i);let A=l.clearChat??{},I=null,L=null;if(A.enabled??!0){let B=A.placement??"inline",O=Cs(e,{wrapperClassName:B==="top-right"?"persona-absolute persona-top-4 persona-z-50":y});I=O.button,L=O.wrapper,B==="top-right"?L.style.right="48px":E.appendChild(L)}E.appendChild(C),c.appendChild(E);let k=P("div");k.style.display="none";let R=P("span");return R.style.display="none",{header:c,iconHolder:k,headerTitle:g,headerSubtitle:R,closeButton:h,closeButtonWrapper:C,clearChatButton:I,clearChatButtonWrapper:L}},uy={default:bS,minimal:CS},wS=t=>uy[t]??uy.default,Ol=(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=P("div");c.style.display="none";let u=P("span"),p=P("span"),g=P("button");g.style.display="none";let y=P("div");return y.style.display="none",{header:l,iconHolder:c,headerTitle:u,headerSubtitle:p,closeButton:g,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=wS(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 Wi=t=>{let{config:e}=t,n=Y("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=ll(),s=Y("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":""}}),{textarea:i,attachAutoResize:l}=rl(e);l();let c=sl(e),u=gs(e),p=il(e),g=al(e),y=Y("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(y),p&&(p.previewsContainer.style.gap="8px",y.append(p.previewsContainer),s.append(p.input)),s.append(i);let h=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),C=Y("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),E=Y("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&C.append(p.wrapper),u&&E.append(u.wrapper),E.append(c.wrapper),h.append(C,E),s.append(h),s.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&i.focus()}),e?.statusIndicator?.mode==="transient"?n.append(o,g,s):n.append(o,s,g),{footer:n,suggestions:o,composerForm:s,header:y,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:g,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:h,leftActions:C,rightActions:E,setSendButtonMode:c.setMode}};import{ChevronUp as SS,MessageSquare as xS}from"lucide";var gy=()=>{let t=Y("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=P("span","persona-pill-peek__icon"),n=yt(xS,16,"currentColor",1.5);n&&e.appendChild(n);let o=P("span","persona-pill-peek__text"),s=P("span","persona-pill-peek__caret"),i=yt(SS,16,"currentColor",1.5);return i&&s.appendChild(i),t.append(e,o,s),{root:t,textNode:o}},_l=t=>{let{config:e}=t,n=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ll(),s=al(e);s.style.display="none";let{textarea:i,attachAutoResize:l}=rl(e,{defaultMaxLines:5});l();let c=sl(e),u=gs(e),p=il(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let g=Y("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),y=Y("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&y.append(p.wrapper);let h=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});u&&h.append(u.wrapper),h.append(c.wrapper),g.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&i.focus()}),p&&g.append(p.input),g.append(y,i,h);let C=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(C),p&&C.append(p.previewsContainer),n.append(o,g,s);let E=g;return{footer:n,suggestions:o,composerForm:g,header:C,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:s,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:E,leftActions:y,rightActions:h,setSendButtonMode:c.setMode}};var AS=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}},MS=(t,e)=>{if(!t)return null;let n=AS(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},ES=(t,e)=>{let n=P("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},TS=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},hp=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(":"))},yp=320,by=320,kS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),PS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),LS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),IS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),HS=t=>{if(!t||t.length===0)return null;let e=Y("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Y("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=P("span","persona-mention-chip-icon"),i=se(n.iconName??"at-sign",13,"currentColor",2);i&&s.appendChild(i),o.appendChild(s),o.appendChild(Y("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},RS=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Rd(o.ref,{readonly:!0,render:e}))}return n},my="\uE000",fy="\uE001",WS=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=h=>`${my}${s}:${h}${fy}`,l=e.map((h,C)=>h.kind==="text"?h.text:i(C)).join(""),c=n(l);if(!e.every((h,C)=>h.kind==="text"||c.includes(i(C)))){t.replaceChildren(RS(e,o));return}t.innerHTML=c;let p=new RegExp(`${my}${s}:(\\d+)${fy}`),g=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),y=[];for(let h=g.nextNode();h;h=g.nextNode())y.push(h);for(let h of y){let C=h;for(let E=p.exec(C.data);E;E=p.exec(C.data)){let A=e[Number(E[1])],I=C.splitText(E.index);I.data=I.data.slice(E[0].length),A?.kind==="mention"&&I.parentNode?.insertBefore(Rd(A.ref,{readonly:!0,render:o}),I),C=I}}},BS=(t,e,n)=>{if(t.length===0)return null;try{let o=P("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,u)=>{let p=P("img");p.alt=c.alt?.trim()||`Attached image ${u+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${yp}px`,p.style.maxHeight=`${by}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;s+=1,p.addEventListener("error",()=>{g||(g=!0,s=Math.max(0,s-1),p.remove(),s===0&&l())}),p.addEventListener("load",()=>{g=!0}),TS(c.image)?(p.src=c.image,o.appendChild(p)):(g=!0,s=Math.max(0,s-1),p.remove())}),s===0?(l(),null):o}catch{return n?.(),null}},DS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!hp(o.audio))return;let s=P("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${yp}px`,e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},OS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!hp(o.video))return;let s=P("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${yp}px`,s.style.maxHeight=`${by}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}},_S=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!hp(o.data))return;let s=P("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}},Bi=()=>{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},FS=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Bi};if(e){let s=e(o);if(s!==null)return s}return Bi()},NS=(t,e)=>{let n=P("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=P("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},hy=(t,e,n="div")=>{let o=P(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},Di=(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},yy={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"}},VS=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=yy[n??"bubble"]??yy.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)`)},Fl="custom:",$S=t=>`${Fl}${t}`,vy=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),zS=(t,e,n,o)=>{let s=e.showCopy??!0,i=e.showUpvote??!1,l=e.showDownvote??!1,c=e.showReadAloud??!1,u=(e.showRegenerate??!1)&&o?.canRegenerate===!0,p=(e.showEdit??!1)&&o?.canEdit===!0,g=(e.showQuote??!1)&&o?.canQuote!==!1,y=vy(e,t.role);if(!s&&!i&&!l&&!c&&!u&&!p&&!g&&y.length===0){let R=P("div");return R.style.display="none",R.id=`actions-${t.id}`,R.setAttribute("data-actions-for",t.id),R}let h=e.visibility??"hover",C=e.align??"right",E=e.layout??"pill-inside",A={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[C],I={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[E],L=P("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${A} ${I} ${h==="hover"?"persona-message-actions-hover":""}`);L.id=`actions-${t.id}`,L.setAttribute("data-actions-for",t.id);let k=(R,B,O)=>{let V=_f({icon:R,label:B,size:14,className:"persona-message-action-btn",chromeless:!0});return V.setAttribute("data-action",O),V};s&&L.appendChild(k("copy","Copy message","copy")),c&&L.appendChild(k("volume-2","Read aloud","read-aloud")),i&&L.appendChild(k("thumbs-up","Upvote","upvote")),l&&L.appendChild(k("thumbs-down","Downvote","downvote")),u&&L.appendChild(k("refresh-cw","Regenerate response","regenerate")),p&&L.appendChild(k("pencil","Edit message","edit")),g&&L.appendChild(k("quote","Quote message","quote"));for(let R of y)L.appendChild(k(R.iconName??"ellipsis",R.label,$S(R.id)));return L},bp=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",u=l.avatar,p=l.timestamp,g=u?.show??!1,y=p?.show??!1,h=u?.position??"left",C=p?.position??"below",E=Di(t.role,c),A=P("div",E.join(" "));A.id=`bubble-${t.id}`,A.setAttribute("data-message-id",t.id),A.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let I=rp(i?.widgetConfig?.future).components.message,L=i?.widgetConfig?.theme?.components?.message;VS(A,t.role,c,t.role==="user"?{...I.user,...L?.user,...i?.widgetConfig?.darkTheme?.components?.message?.user}:{...I.assistant,...L?.assistant,...i?.widgetConfig?.darkTheme?.components?.message?.assistant}),c==="flat"?(A.style.backgroundColor="transparent",A.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=kS(t),R=t.content?.trim()??"",O=k.length>0&&R===tl,V=pl(i?.widgetConfig?.features?.streamAnimation),J=i?.widgetConfig?.features?.streamAnimation?.plugins,_=t.role==="assistant"&&V.type!=="none"?mi(V.type,J):null,Q=t.role==="assistant"&&_?.isAnimating?.(t)===!0,G=t.role==="assistant"&&_!==null&&(!!t.streaming||Q);G&&_?.bubbleClass&&A.classList.add(_.bubbleClass);let w=document.createElement("div");w.classList.add("persona-message-content"),t.streaming&&w.classList.add("persona-content-streaming"),G&&_&&(_.containerClass&&w.classList.add(_.containerClass),w.style.setProperty("--persona-stream-step",`${V.speed}ms`),w.style.setProperty("--persona-stream-duration",`${V.duration}ms`));let v=G?ul(t.content??"",V.buffer,_,t,!!t.streaming):t.content??"",T=()=>{let Ce=e({text:v,message:t,streaming:!!t.streaming,raw:t.rawContent});return G&&_?.wrap==="char"?fi(Ce,"char",t.id,{skipTags:_.skipTags}):G&&_?.wrap==="word"?fi(Ce,"word",t.id,{skipTags:_.skipTags}):Ce},S=null;if(O?(S=document.createElement("div"),S.innerHTML=T(),S.style.display="none",w.appendChild(S)):t.contentSegments?.length?WS(w,t.contentSegments,Ce=>e({text:Ce,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):w.innerHTML=T(),G&&_?.useCaret&&!O&&R){let Ce=gl(),H=w.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ee=H[H.length-1];if(Ee?.parentNode)Ee.parentNode.insertBefore(Ce,Ee.nextSibling);else{let de=w.lastElementChild;de?de.appendChild(Ce):w.appendChild(Ce)}}if(y&&C==="inline"&&t.createdAt){let Ce=hy(t,p,"span");Ce.classList.add("persona-timestamp-inline");let H=w.lastElementChild;H?H.appendChild(Ce):w.appendChild(Ce)}if(k.length>0){let Ce=BS(k,!O&&!!R,()=>{O&&S&&(S.style.display="")});Ce?A.appendChild(Ce):O&&S&&(S.style.display="")}let z=PS(t);if(z.length>0){let Ce=DS(z);Ce&&A.appendChild(Ce)}let W=LS(t);if(W.length>0){let Ce=OS(W);Ce&&A.appendChild(Ce)}let ee=IS(t);if(ee.length>0){let Ce=_S(ee);Ce&&A.appendChild(Ce)}let ne=t.contentSegments?.length?null:HS(t.contextMentions);if(ne&&A.appendChild(ne),A.appendChild(w),y&&C==="below"&&t.createdAt){let Ce=hy(t,p);Ce.classList.add("persona-mt-1"),A.appendChild(Ce)}let he=t.role==="assistant"?MS(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Ce=!!(v&&v.trim()),H=V.placeholder==="skeleton",Ee=H&&V.buffer==="line"&&Ce;if(Ce)Ee&&A.appendChild(hi());else if(H)A.appendChild(hi());else{let de=FS("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);de&&A.appendChild(de)}}he&&t.stopReason&&!t.streaming&&(R||(w.style.display="none"),A.appendChild(ES(t.stopReason,he)));let ve=t.role==="assistant"&&!t.streaming&&!t.voiceCaption&&t.content&&t.content.trim()&&o?.enabled!==!1,Xe=i?.actionEligibility,Je=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Xe?.canEdit===!0||o?.showQuote===!0&&Xe?.canQuote===!0||vy(o,"user").length>0);if((ve||Je)&&o){let Ce=zS(t,Je?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,Xe);A.appendChild(Ce)}if(!g||t.role==="system")return A;let Wt=P("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),$e=NS(u,t.role);return h==="right"||h==="left"&&t.role==="user"?Wt.append(A,$e):Wt.append($e,A),Wt};var US=40,qS=(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=se(e.name,US);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(Y("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(Y("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},Cy=(t,e,n={})=>{let o=Y("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let s=P("p","persona-welcome-kicker");s.hidden=!0;let i=P("h2","persona-welcome-title"),l=P("p","persona-welcome-subtitle"),c=Y("div",{className:"persona-welcome-head-text"},s,i),u=Y("div",{className:"persona-welcome-title-row"},o,c);return{host:Y("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)"}},u,l,e),iconHolder:o,kicker:s,title:i,subtitle:l,starterSuggestions:e}},ws=(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)},Vl=(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==="",qS(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-layout",e.layout??"top"),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")},jS="data-persona-welcome-plugin",wy="data-persona-welcome-overlay",Nl="persona-welcome-overlay-active",vp=new WeakMap,Cp=(t,e,n)=>{n.setAttribute(jS,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(wy,""),t.classList.contains(Nl)||(vp.set(t,t.scrollTop),t.classList.add(Nl),t.scrollTop=0)},wp=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(wy),t.classList.contains(Nl)&&(t.classList.remove(Nl),t.scrollTop=vp.get(t)??t.scrollTop,vp.delete(t))},Sy=()=>{let t=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},$l=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",s=Y("div",{className:Di("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(Y("div",{className:"persona-flex"},s)),t.hidden=!1},xy=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Ay=(t,e)=>{if(xy()||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 E=getComputedStyle(o);s=parseFloat(E.rowGap)||0;let A=t.previousElementSibling,I=t.nextElementSibling,k=o.getBoundingClientRect().top+(parseFloat(E.borderTopWidth)||0)+(parseFloat(E.paddingTop)||0)-o.scrollTop;i=Math.max(0,A?n.top-A.getBoundingClientRect().bottom-s:n.top-k),l=Math.max(0,I?I.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let u=getComputedStyle(t),p=parseFloat(u.paddingTop)||0,g=parseFloat(u.paddingBottom)||0,y=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${g}px`,marginTop:`${i}px`,marginBottom:`${l}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-s}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,C=()=>{h||(h=!0,t.style.overflow=c,e(y))};return y.finished.then(C).catch(C),y},My=(t,e,n,o=260)=>{if(e<=1||xy()||typeof t.animate!="function"||!t.isConnected)return null;let s=n==="drop"?-e:e;return t.animate([{transform:`translateY(${s}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var KS="Hello \u{1F44B}",GS="I can answer questions and help you get things done here.",Ey=new WeakSet,$t=(t,e)=>!!t&&t[e]!==void 0,YS=(t,e)=>{!t||t.debug!==!0||!e.length||Ey.has(t)||(Ey.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},zl=(t,e=t?.launcher?.fullHeight===!0&&!t.launcher.sidebarMode&&t.launcher.mountMode!=="docked")=>{let n=t?.welcome,o=t?.copy,s=t?.future?.v5Defaults===!0,i=n?.layout??(s?"centered":"top"),l=$t(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",c=l==="hero"&&!s&&n?.layout===void 0?"on-first-message":$t(n,"dismiss")?n.dismiss:s||l==="hero"?"on-first-message":"never",u=[];$t(n,"title")&&$t(o,"welcomeTitle")&&u.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),$t(n,"subtitle")&&$t(o,"welcomeSubtitle")&&u.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),$t(n,"variant")&&$t(o,"showWelcomeCard")&&u.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),l==="hero"&&$t(n,"message")&&u.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!s&&n?.layout===void 0&&l==="hero"&&$t(n,"dismiss")&&n.dismiss!=="on-first-message"&&u.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(i==="centered"&&e?"center":"bottom"),g=ki(n?.anchorComposerTop)!==null;return $t(n,"anchorComposerTop")&&!g&&u.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&($t(n,"anchorComposerTop")||$t(n,"composerGap"))&&u.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),YS(t,u),{title:$t(n,"title")?n.title:o?.welcomeTitle??(s?"What can I help with?":KS),kicker:n?.kicker??"",subtitle:$t(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(s?"":GS),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:i==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:l,dismiss:c,message:l==="hero"?void 0:n?.message,layout:i,anchor:p,anchorComposerTop:g?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Wl}},Ty=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ss=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var QS="var(--persona-components-panel-maxWidth)",ky="var(--persona-components-panel-height)",XS="var(--persona-components-panel-maxHeight)",Pr=t=>{let e=xr(t),n=e.launcherWidth?t?.launcher?.width:e.legacyLauncherWidth?t?.launcherWidth:void 0,o=t?.launcher?.heightOffset??0,s=o===0?`max(200px, ${ky})`:`max(200px, calc(${ky} - ${o}px))`;return{width:n??Rm,maxWidth:n??QS,height:s,maxHeight:XS}},Py="16px",xp="10px",Ap="14px",Ly=t=>{let e=t?.launcher?.enabled??!0,n=rt(t);if(Ii(t)){let p=t?.launcher?.composerBar??{},g=P("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Dt);let y=P("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",g.appendChild(y);let h=P("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=p.expandedSize??"anchored",h.style.zIndex=String(t?.launcher?.zIndex??Dt),{wrapper:g,panel:y,pillRoot:h}}if(n){let p=P("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=P("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(g),{wrapper:p,panel:g}}if(!e){let p=P("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=P("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=xr(t),C=y.launcherWidth||y.legacyLauncherWidth||t?.theme?.components?.panel?.width!==void 0?Pr(t).width:"100%";return p.style.width=C,g.style.width="100%",p.appendChild(g),{wrapper:p,panel:g}}let s=t?.launcher??{},i=s.position&&cn[s.position]?cn[s.position]:cn["bottom-right"],l=P("div",`persona-widget-wrapper persona-fixed ${i} persona-transition`);l.style.zIndex=String(t?.launcher?.zIndex??Dt);let c=P("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=Pr(t);return c.style.width=u.width,c.style.maxWidth=u.maxWidth,l.appendChild(c),{wrapper:l,panel:c}},Mp=t=>{let e=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":pp(t)}});return e.hidden=!0,e},Iy=(t,e)=>{let n=Mp("starter"),o=Cy(t,n,{flatShadow:rt(t)}),s=zl(t);Vl(o,s),ws(e,o.host,Ss(s,t?.initialMessages));let i=Sy();return $l(i,s.message,t),{welcome:o,greetingHost:i}},JS=(t,e)=>{let n=P("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}=vs(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:Py,iconSize:xp});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 J=Cs(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Py,iconSize:Ap});l=J.button,c=J.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let u=Y("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Y("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"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:g,greetingHost:y}=Iy(t,p),{host:h,title:C,subtitle:E}=g,A=g.starterSuggestions,I=P("div","persona-widget-messages persona-flex persona-flex-col");I.style.gap="var(--persona-components-message-gap, 12px)";let L=Mp("followUp"),k=Ko(t,!0);k&&(I.style.maxWidth=k,I.style.marginLeft="auto",I.style.marginRight="auto",I.style.width="100%"),p.append(h,y,I,L);let R=Y("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),B=_l({config:t}),{root:O,textNode:V}=gy();return n.append(u,s,p,R),c&&n.appendChild(c),{container:n,body:p,messagesWrapper:I,starterSuggestions:A,transcriptSuggestions:L,composerOverlay:R,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,welcomeHost:h,welcomeIconHolder:g.iconHolder,greetingHost:y,introKicker:g.kicker,introTitle:C,introSubtitle:E,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:P("span"),headerTitle:P("span"),headerSubtitle:P("span"),header:u,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:O,peekTextNode:V}},Hy=(t,e=!0)=>{if(Ii(t))return JS(t,e);let n=Y("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?Ol(t,o,{showClose:e}):kr({config:t,showClose:e}),l=Y("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:u}=Iy(t,l),{host:p,title:g,subtitle:y}=c,h=c.starterSuggestions,C=P("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let E=Mp("followUp"),A=Ko(t,!1);A&&(C.style.maxWidth=A,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),l.append(p,u,C,E);let I=Wi({config:t}),L=t?.layout?.showFooter!==!1;s?Ri(n,i,t):(i.header.style.display="none",Ri(n,i,t)),n.append(l);let k=Y("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 L||(I.footer.style.display="none"),n.append(I.footer),n.append(k),{container:n,body:l,messagesWrapper:C,starterSuggestions:h,transcriptSuggestions:E,composerOverlay:k,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,welcomeHost:p,welcomeIconHolder:c.iconHolder,greetingHost:u,introKicker:c.kicker,introTitle:g,introSubtitle:y,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:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode}};var Ep=(t,e)=>{let n=P("button");n.type="button",n.innerHTML=`
15
15
  <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>
16
16
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
17
17
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -19,15 +19,15 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
19
19
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
20
20
  </span>
21
21
  <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>
22
- `,n.addEventListener("click",e);let o=i=>{let l=i.launcher??{},c=rt(i),u=El(i)==="circle";u?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",l.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let p=n.querySelector("[data-role='launcher-title']");if(p){let B=l.title??"Chat Assistant";p.textContent=B,p.setAttribute("title",B)}let g=n.querySelector("[data-role='launcher-subtitle']");if(g){let B=l.subtitle??"Here to help you get answers fast";g.textContent=B,g.setAttribute("title",B)}let y=n.querySelector(".persona-flex-col");y&&(l.textHidden||c||u?y.style.display="none":y.style.display="");let h=n.querySelector("[data-role='launcher-icon']");if(h)if(l.agentIconHidden)h.style.display="none";else{let B=l.agentIconSize??"40px";if(h.style.height=B,h.style.width=B,l.agentIconBackgroundColor?(h.style.backgroundColor=l.agentIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),h.innerHTML="",l.agentIconName){let O=parseFloat(B)||24,V=se(l.agentIconName,O*.6,"var(--persona-text-inverse, #ffffff)",1.5);V?(h.appendChild(V),h.style.display=""):(h.textContent=l.agentIconText??"\u{1F4AC}",h.style.display="")}else l.iconUrl?h.style.display="none":(h.textContent=l.agentIconText??"\u{1F4AC}",h.style.display="")}let C=n.querySelector("[data-role='launcher-image']");if(C){let B=l.agentIconSize??"40px";C.style.height=B,C.style.width=B,l.iconUrl&&!l.agentIconName&&!l.agentIconHidden?(C.src=l.iconUrl,C.style.display="block"):C.style.display="none"}let E=n.querySelector("[data-role='launcher-call-to-action-icon']");if(E){let B=l.callToActionIconSize??"32px";E.style.height=B,E.style.width=B,l.callToActionIconBackgroundColor?(E.style.backgroundColor=l.callToActionIconBackgroundColor,E.classList.remove("persona-bg-persona-primary")):(E.style.backgroundColor="",E.classList.add("persona-bg-persona-primary")),l.callToActionIconColor?(E.style.color=l.callToActionIconColor,E.classList.remove("persona-text-persona-call-to-action")):(E.style.color="",E.classList.add("persona-text-persona-call-to-action"));let O=0;if(l.callToActionIconPadding?(E.style.boxSizing="border-box",E.style.padding=l.callToActionIconPadding,O=(parseFloat(l.callToActionIconPadding)||0)*2):(E.style.boxSizing="",E.style.padding=""),l.callToActionIconHidden||u)E.style.display="none";else if(E.style.display=c?"none":"",E.innerHTML="",l.callToActionIconName){let V=parseFloat(B)||24,J=Math.max(V-O,8),_=se(l.callToActionIconName,J,"currentColor",1.5);_?E.appendChild(_):E.textContent=l.callToActionIconText??"\u2197"}else E.textContent=l.callToActionIconText??"\u2197"}let A=l.position&&ln[l.position]?ln[l.position]:ln["bottom-right"],I="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",L="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?L:`${I} ${A}`,c||(n.style.zIndex=String(l.zIndex??Dt));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",R="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??k,n.style.boxShadow=l.shadow!==void 0?l.shadow.trim()===""?"none":l.shadow:R,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}},QS="teaser-dismissed",Iy=new Set,Ly=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${QS}`},XS=(t,e)=>{if(Iy.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},JS=(t,e)=>{if(Iy.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},ZS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ex=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||rt(t??{})?null:e},Hy=(t,e)=>{let n=P("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},s=null,i=null,l=null,c=null,u=null,p=!1,g=!1,y=!1,h=!1,C=()=>(s?.frequency??"once")==="once"&&o.persistState!==!1,E=()=>{u!==null&&(clearTimeout(u),u=null)},A=()=>{!i||!p||(p=!1,i.hidden=!0)},I=z=>{E(),y=!0,A(),JS(Ly(o),z&&C())},L=z=>{!s||y||I(z==="user"&&p)},k=()=>{u=null,!(!i||y||h)&&(g=!0,p=!0,i.hidden=!1,!(ZS()||typeof i.animate!="function")&&i.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},R=()=>{!s||!i||y||g||h||XS(Ly(o),C())||(E(),u=setTimeout(k,Math.max(0,s.delayMs??0)))},B=()=>{I(C()),e()},O=z=>{z.stopPropagation(),I(C())},J=Ap(t,()=>{L("user"),e()}),_=()=>{E(),c?.removeEventListener("click",B),l?.removeEventListener("click",O),i?.remove(),i=null,c=null,l=null,p=!1},Q=()=>{c=Y("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),c.addEventListener("click",B),l=Y("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),l.addEventListener("click",O),i=Y("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},c,l),n.insertBefore(i,J.element)},G=()=>{let z=o.launcher?.position??"bottom-right",W=ln[z]??ln["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",J.element.style.position="";return}n.className=ss("persona-launcher-surface",W),n.setAttribute("data-teaser",z),n.style.zIndex=String(o.launcher?.zIndex??Dt),J.element.style.position="static"},w=z=>{let W=ex(z);if(s=W,!W){_();return}i||Q(),c.textContent=W.text,l.hidden=W.dismissible===!1,l.setAttribute("aria-label",W.dismissLabel??"Dismiss message"),R()},v=z=>{o=z,J.update(z),w(z),G()},T=(z,W="user")=>{h=z,z&&L(W)},x=()=>{_(),J.destroy(),n.remove()};return n.appendChild(J.element),t&&(w(t),G()),{element:n,launcher:J,get teaser(){return i?{element:i,show:k,dismiss:I}:null},setPanelOpen:T,update:v,destroy:x}};var Ry=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:s}=Ty(t),i=Py(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},u={element:i.header,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper},p={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:u,composer:p,replaceHeader:h=>(u.element.replaceWith(h.header),u.element=h.header,u.iconHolder=h.iconHolder,u.headerTitle=h.headerTitle,u.headerSubtitle=h.headerSubtitle,u.closeButton=h.closeButton,u.closeButtonWrapper=h.closeButtonWrapper,u.clearChatButton=h.clearChatButton,u.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{p.footer.replaceWith(h),p.footer=h}}},Mp=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>Ap(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let s=Hy(t,n);return{instance:s,element:s.element}};var tx=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},nx=(t,e,n)=>`${tx(t)}plugin:${e}:${n}`,Wy=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=>nx(t(),s,l);return{get:l=>{let c=i(l),u=o();if(u)try{return u.getItem(c)}catch{n=!0}return e.get(c)??null},set:(l,c)=>{let u=i(l),p=o();if(p)try{p.setItem(u,c);return}catch{n=!0}e.set(u,c)},remove:l=>{let c=i(l);e.delete(c);let u=o();if(u)try{u.removeItem(c)}catch{n=!0}}}}};var ox=(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(`
23
- `):""},Ep=(t,e,n)=>{hl(t,e,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},Tp=(t,e,n=new Set)=>{e=yl(e,"reasoning");let o=t.reasoning,s=ul("persona-reasoning-bubble",t.id);if(!o)return mo(s,t,e,"reasoning");let i=e?.features?.reasoningDisplay??{},l=i.expandable??rs.expandable,c=l&&n.has(t.id),u=o.status!=="complete",p=ox(t,i.previewMaxLines??rs.previewMaxLines),g=gl({expandable:l,expanded:c,bubbleType:"reasoning"}),y=P("div","persona-flex persona-flex-col persona-text-left"),h=P("span","persona-text-xs persona-text-persona-primary"),C=qo(e,"reasoning")==="row",E=C&&!u?`Thought for ${bi(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",A=e?.reasoning??{},I=String(o.startedAt??Date.now()),L=()=>{let W=P("span","");return W.setAttribute("data-tool-elapsed",I),W.textContent=Qa(o),W},k=A.renderCollapsedSummary?.({message:t,reasoning:o,defaultSummary:E,previewText:p,isActive:u,config:e??{},elapsed:Qa(o),createElapsedElement:L});typeof k=="string"&&k.trim()?(h.textContent=k,y.appendChild(h)):k instanceof HTMLElement?y.appendChild(k):(h.textContent=E,y.appendChild(h));let R=P("span","persona-text-xs persona-text-persona-primary");R.textContent=Um(o),C||y.appendChild(R);let B=i.loadingAnimation??rs.loadingAnimation,O=A.activeTextTemplate,V=A.completeTextTemplate,J=u?O:V,_=k instanceof HTMLElement,Q=(W,ee)=>{h.textContent="";let ne=Xa(W,""),he=0;for(let ve of ne){let Xe=ve.styles.length>0?(()=>{let Je=P("span",ve.styles.map(Wt=>`persona-tool-text-${Wt}`).join(" "));return h.appendChild(Je),Je})():h;if(ve.isDuration&&u)Xe.appendChild(L());else{let Je=ve.isDuration?Qa(o):ve.text;ee?he=ms(Xe,Je,he):Xe.appendChild(document.createTextNode(Je))}}};if(!_&&J)if(R.style.display="none",h.style.display="",u&&B!=="none"){let W=A.loadingAnimationDuration??2e3;h.setAttribute("data-preserve-animation","true"),B==="pulse"?(h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),Q(J,!1)):(h.classList.add(`persona-tool-loading-${B}`),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),B==="shimmer-color"&&(A.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",A.loadingAnimationColor),A.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",A.loadingAnimationSecondaryColor)),Q(J,!0))}else Q(J,!1);else if(!_&&u&&B!=="none"){h.style.display="";let W=A.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),B==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`);else{h.classList.add(`persona-tool-loading-${B}`),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),B==="shimmer-color"&&(A.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",A.loadingAnimationColor),A.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",A.loadingAnimationSecondaryColor));let ee=h.textContent||E;h.textContent="",ms(h,ee,0)}o.status==="complete"&&!C&&(h.style.display="none")}else _||(o.status==="complete"&&!C?h.style.display="none":h.style.display="");if(i.iconName&&!_){let W=P("span","persona-reasoning-header-icon"),ee=se(i.iconName,16,"currentColor",2);ee&&(W.appendChild(ee),g.appendChild(W))}let G="currentColor",w=fs(g,y,{expandable:l,expanded:c,iconColor:G,metaGap:!1}),v=ml({bubble:s,previewKind:"reasoning",expanded:c,isActive:u,previewText:p,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:o,defaultPreview:p,isActive:u,config:e??{}})});if(!l)return s.append(g,v),mo(s,t,e,"reasoning");let T=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");T.style.display=c?"":"none";let x=o.chunks.join(""),z=P("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return z.textContent=x||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),T.appendChild(z),fl({expanded:c,header:g,toggleIcon:w,content:T,collapsedPreview:v,iconColor:G}),s.append(g,v,T),mo(s,t,e,"reasoning")};var By=t=>{if(t==null)return!0;if(typeof t=="string"){if(!t.trim())return!0;try{return By(JSON.parse(t))}catch{return!1}}return typeof t=="object"&&Object.keys(t).length===0},rx=t=>{if(t!==null&&typeof t=="object")return!0;if(typeof t!="string")return!1;try{let e=JSON.parse(t);return e!==null&&typeof e=="object"}catch{return!1}};function Dy(t,e,n){let o=e.toolCall;if(!o)return;let s=n.toolCall??{},i=(c,u)=>{let p=Y("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":c.toLowerCase()},style:{backgroundColor:s.codeBlockBackgroundColor,borderColor:s.codeBlockBorderColor,borderWidth:s.codeBlockBorderColor?"1px":void 0}}),g=Y("div",{className:"persona-tool-detail-label",text:c,style:{color:s.labelTextColor}}),y=ls(u),h=Y("pre",{className:`persona-tool-detail-value${rx(u)?" persona-tool-detail-code":""}`,text:y,attrs:y.length>420||y.split(`
24
- `).length>7?{tabindex:"0","aria-label":`${c} content`}:{},style:{color:s.codeBlockTextColor??s.contentTextColor}}),C=Y("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${c.toLowerCase()}`,title:`Copy ${c.toLowerCase()}`}}),E=se("copy",14,"currentColor",1.7);E&&C.appendChild(E),p.append(g,h,C),t.appendChild(p)};By(o.args)||i("Request",o.args);let l=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");l!==void 0&&(typeof l!="string"||l.trim())&&i("Response",l),o.success===!1&&t.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var kp=new WeakMap;async function Oy(t){let e=t.closest("[data-persona-tool-detail]"),n=e?.querySelector("pre");if(!n)return;let o=`Copy ${e?.getAttribute("data-persona-tool-detail")}`;clearTimeout(kp.get(t));try{await navigator.clipboard.writeText(n.textContent??""),t.dataset.copied="true",t.setAttribute("aria-label","Copied"),t.title="Copied";let s=se("check",14,"currentColor",2);s&&t.replaceChildren(s)}catch{t.setAttribute("aria-label","Copy failed \u2014 try again"),t.title="Copy failed \u2014 try again"}kp.set(t,setTimeout(()=>{delete t.dataset.copied,t.setAttribute("aria-label",o),t.title=o;let s=se("copy",14,"currentColor",1.7);s&&t.replaceChildren(s),kp.delete(t)},1800))}var _y=(t,e=!1)=>t.toggleTextColor||t.headerTextColor||(e?"currentColor":"var(--persona-primary, #171717)"),sx=(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(`
22
+ `,n.addEventListener("click",e);let o=i=>{let l=i.launcher??{},c=rt(i),u=kl(i)==="circle";u?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",l.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let p=n.querySelector("[data-role='launcher-title']");if(p){let B=l.title??"Chat Assistant";p.textContent=B,p.setAttribute("title",B)}let g=n.querySelector("[data-role='launcher-subtitle']");if(g){let B=l.subtitle??"Here to help you get answers fast";g.textContent=B,g.setAttribute("title",B)}let y=n.querySelector(".persona-flex-col");y&&(l.textHidden||c||u?y.style.display="none":y.style.display="");let h=n.querySelector("[data-role='launcher-icon']");if(h)if(l.agentIconHidden)h.style.display="none";else{let B=l.agentIconSize??"40px";if(h.style.height=B,h.style.width=B,l.agentIconBackgroundColor?(h.style.backgroundColor=l.agentIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),h.innerHTML="",l.agentIconName){let O=parseFloat(B)||24,V=se(l.agentIconName,O*.6,"var(--persona-text-inverse, #ffffff)",1.5);V?(h.appendChild(V),h.style.display=""):(h.textContent=l.agentIconText??"\u{1F4AC}",h.style.display="")}else l.iconUrl?h.style.display="none":(h.textContent=l.agentIconText??"\u{1F4AC}",h.style.display="")}let C=n.querySelector("[data-role='launcher-image']");if(C){let B=l.agentIconSize??"40px";C.style.height=B,C.style.width=B,l.iconUrl&&!l.agentIconName&&!l.agentIconHidden?(C.src=l.iconUrl,C.style.display="block"):C.style.display="none"}let E=n.querySelector("[data-role='launcher-call-to-action-icon']");if(E){let B=l.callToActionIconSize??"32px";E.style.height=B,E.style.width=B,l.callToActionIconBackgroundColor?(E.style.backgroundColor=l.callToActionIconBackgroundColor,E.classList.remove("persona-bg-persona-primary")):(E.style.backgroundColor="",E.classList.add("persona-bg-persona-primary")),l.callToActionIconColor?(E.style.color=l.callToActionIconColor,E.classList.remove("persona-text-persona-call-to-action")):(E.style.color="",E.classList.add("persona-text-persona-call-to-action"));let O=0;if(l.callToActionIconPadding?(E.style.boxSizing="border-box",E.style.padding=l.callToActionIconPadding,O=(parseFloat(l.callToActionIconPadding)||0)*2):(E.style.boxSizing="",E.style.padding=""),l.callToActionIconHidden||u)E.style.display="none";else if(E.style.display=c?"none":"",E.innerHTML="",l.callToActionIconName){let V=parseFloat(B)||24,J=Math.max(V-O,8),_=se(l.callToActionIconName,J,"currentColor",1.5);_?E.appendChild(_):E.textContent=l.callToActionIconText??"\u2197"}else E.textContent=l.callToActionIconText??"\u2197"}let A=l.position&&cn[l.position]?cn[l.position]:cn["bottom-right"],I="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",L="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?L:`${I} ${A}`,c||(n.style.zIndex=String(l.zIndex??Dt));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",R="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??k,n.style.boxShadow=l.shadow!==void 0?l.shadow.trim()===""?"none":l.shadow:R,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}},ZS="teaser-dismissed",Wy=new Set,Ry=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${ZS}`},ex=(t,e)=>{if(Wy.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},tx=(t,e)=>{if(Wy.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},nx=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ox=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||rt(t??{})?null:e},By=(t,e)=>{let n=P("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},s=null,i=null,l=null,c=null,u=null,p=!1,g=!1,y=!1,h=!1,C=()=>(s?.frequency??"once")==="once"&&o.persistState!==!1,E=()=>{u!==null&&(clearTimeout(u),u=null)},A=()=>{!i||!p||(p=!1,i.hidden=!0)},I=z=>{E(),y=!0,A(),tx(Ry(o),z&&C())},L=z=>{!s||y||I(z==="user"&&p)},k=()=>{u=null,!(!i||y||h)&&(g=!0,p=!0,i.hidden=!1,!(nx()||typeof i.animate!="function")&&i.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},R=()=>{!s||!i||y||g||h||ex(Ry(o),C())||(E(),u=setTimeout(k,Math.max(0,s.delayMs??0)))},B=()=>{I(C()),e()},O=z=>{z.stopPropagation(),I(C())},J=Ep(t,()=>{L("user"),e()}),_=()=>{E(),c?.removeEventListener("click",B),l?.removeEventListener("click",O),i?.remove(),i=null,c=null,l=null,p=!1},Q=()=>{c=Y("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),c.addEventListener("click",B),l=Y("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),l.addEventListener("click",O),i=Y("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},c,l),n.insertBefore(i,J.element)},G=()=>{let z=o.launcher?.position??"bottom-right",W=cn[z]??cn["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",J.element.style.position="";return}n.className=ss("persona-launcher-surface",W),n.setAttribute("data-teaser",z),n.style.zIndex=String(o.launcher?.zIndex??Dt),J.element.style.position="static"},w=z=>{let W=ox(z);if(s=W,!W){_();return}i||Q(),c.textContent=W.text,l.hidden=W.dismissible===!1,l.setAttribute("aria-label",W.dismissLabel??"Dismiss message"),R()},v=z=>{o=z,J.update(z),w(z),G()},T=(z,W="user")=>{h=z,z&&L(W)},S=()=>{_(),J.destroy(),n.remove()};return n.appendChild(J.element),t&&(w(t),G()),{element:n,launcher:J,get teaser(){return i?{element:i,show:k,dismiss:I}:null},setPanelOpen:T,update:v,destroy:S}};var Dy=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:s}=Ly(t),i=Hy(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},u={element:i.header,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper},p={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:u,composer:p,replaceHeader:h=>(u.element.replaceWith(h.header),u.element=h.header,u.iconHolder=h.iconHolder,u.headerTitle=h.headerTitle,u.headerSubtitle=h.headerSubtitle,u.closeButton=h.closeButton,u.closeButtonWrapper=h.closeButtonWrapper,u.clearChatButton=h.clearChatButton,u.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{p.footer.replaceWith(h),p.footer=h}}},Tp=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>Ep(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let s=By(t,n);return{instance:s,element:s.element}};var rx=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},sx=(t,e,n)=>`${rx(t)}plugin:${e}:${n}`,Oy=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=>sx(t(),s,l);return{get:l=>{let c=i(l),u=o();if(u)try{return u.getItem(c)}catch{n=!0}return e.get(c)??null},set:(l,c)=>{let u=i(l),p=o();if(p)try{p.setItem(u,c);return}catch{n=!0}e.set(u,c)},remove:l=>{let c=i(l);e.delete(c);let u=o();if(u)try{u.removeItem(c)}catch{n=!0}}}}};var ix=(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(`
23
+ `):""},kp=(t,e,n)=>{bl(t,e,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},Pp=(t,e,n=new Set)=>{e=vl(e,"reasoning");let o=t.reasoning,s=ml("persona-reasoning-bubble",t.id);if(!o)return mo(s,t,e,"reasoning");let i=e?.features?.reasoningDisplay??{},l=i.expandable??rs.expandable,c=l&&n.has(t.id),u=o.status!=="complete",p=ix(t,i.previewMaxLines??rs.previewMaxLines),g=fl({expandable:l,expanded:c,bubbleType:"reasoning"}),y=P("div","persona-flex persona-flex-col persona-text-left"),h=P("span","persona-text-xs persona-text-persona-primary"),C=qo(e,"reasoning")==="row",E=C&&!u?`Thought for ${bi(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",A=e?.reasoning??{},I=String(o.startedAt??Date.now()),L=()=>{let W=P("span","");return W.setAttribute("data-tool-elapsed",I),W.textContent=Ja(o),W},k=A.renderCollapsedSummary?.({message:t,reasoning:o,defaultSummary:E,previewText:p,isActive:u,config:e??{},elapsed:Ja(o),createElapsedElement:L});typeof k=="string"&&k.trim()?(h.textContent=k,y.appendChild(h)):k instanceof HTMLElement?y.appendChild(k):(h.textContent=E,y.appendChild(h));let R=P("span","persona-text-xs persona-text-persona-primary");R.textContent=Km(o),C||y.appendChild(R);let B=i.loadingAnimation??rs.loadingAnimation,O=A.activeTextTemplate,V=A.completeTextTemplate,J=u?O:V,_=k instanceof HTMLElement,Q=(W,ee)=>{h.textContent="";let ne=Za(W,""),he=0;for(let ve of ne){let Xe=ve.styles.length>0?(()=>{let Je=P("span",ve.styles.map(Wt=>`persona-tool-text-${Wt}`).join(" "));return h.appendChild(Je),Je})():h;if(ve.isDuration&&u)Xe.appendChild(L());else{let Je=ve.isDuration?Ja(o):ve.text;ee?he=ms(Xe,Je,he):Xe.appendChild(document.createTextNode(Je))}}};if(!_&&J)if(R.style.display="none",h.style.display="",u&&B!=="none"){let W=A.loadingAnimationDuration??2e3;h.setAttribute("data-preserve-animation","true"),B==="pulse"?(h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),Q(J,!1)):(h.classList.add(`persona-tool-loading-${B}`),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),B==="shimmer-color"&&(A.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",A.loadingAnimationColor),A.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",A.loadingAnimationSecondaryColor)),Q(J,!0))}else Q(J,!1);else if(!_&&u&&B!=="none"){h.style.display="";let W=A.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),B==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`);else{h.classList.add(`persona-tool-loading-${B}`),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),B==="shimmer-color"&&(A.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",A.loadingAnimationColor),A.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",A.loadingAnimationSecondaryColor));let ee=h.textContent||E;h.textContent="",ms(h,ee,0)}o.status==="complete"&&!C&&(h.style.display="none")}else _||(o.status==="complete"&&!C?h.style.display="none":h.style.display="");if(i.iconName&&!_){let W=P("span","persona-reasoning-header-icon"),ee=se(i.iconName,16,"currentColor",2);ee&&(W.appendChild(ee),g.appendChild(W))}let G="currentColor",w=fs(g,y,{expandable:l,expanded:c,iconColor:G,metaGap:!1}),v=hl({bubble:s,previewKind:"reasoning",expanded:c,isActive:u,previewText:p,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:o,defaultPreview:p,isActive:u,config:e??{}})});if(!l)return s.append(g,v),mo(s,t,e,"reasoning");let T=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");T.style.display=c?"":"none";let S=o.chunks.join(""),z=P("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return z.textContent=S||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),T.appendChild(z),yl({expanded:c,header:g,toggleIcon:w,content:T,collapsedPreview:v,iconColor:G}),s.append(g,v,T),mo(s,t,e,"reasoning")};var _y=t=>{if(t==null)return!0;if(typeof t=="string"){if(!t.trim())return!0;try{return _y(JSON.parse(t))}catch{return!1}}return typeof t=="object"&&Object.keys(t).length===0},ax=t=>{if(t!==null&&typeof t=="object")return!0;if(typeof t!="string")return!1;try{let e=JSON.parse(t);return e!==null&&typeof e=="object"}catch{return!1}};function Fy(t,e,n){let o=e.toolCall;if(!o)return;let s=n.toolCall??{},i=(c,u)=>{let p=Y("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":c.toLowerCase()},style:{backgroundColor:s.codeBlockBackgroundColor,borderColor:s.codeBlockBorderColor,borderWidth:s.codeBlockBorderColor?"1px":void 0}}),g=Y("div",{className:"persona-tool-detail-label",text:c,style:{color:s.labelTextColor}}),y=ls(u),h=Y("pre",{className:`persona-tool-detail-value${ax(u)?" persona-tool-detail-code":""}`,text:y,attrs:y.length>420||y.split(`
24
+ `).length>7?{tabindex:"0","aria-label":`${c} content`}:{},style:{color:s.codeBlockTextColor??s.contentTextColor}}),C=Y("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${c.toLowerCase()}`,title:`Copy ${c.toLowerCase()}`}}),E=se("copy",14,"currentColor",1.7);E&&C.appendChild(E),p.append(g,h,C),t.appendChild(p)};_y(o.args)||i("Request",o.args);let l=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");l!==void 0&&(typeof l!="string"||l.trim())&&i("Response",l),o.success===!1&&t.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var Lp=new WeakMap;async function Ny(t){let e=t.closest("[data-persona-tool-detail]"),n=e?.querySelector("pre");if(!n)return;let o=`Copy ${e?.getAttribute("data-persona-tool-detail")}`;clearTimeout(Lp.get(t));try{await navigator.clipboard.writeText(n.textContent??""),t.dataset.copied="true",t.setAttribute("aria-label","Copied"),t.title="Copied";let s=se("check",14,"currentColor",2);s&&t.replaceChildren(s)}catch{t.setAttribute("aria-label","Copy failed \u2014 try again"),t.title="Copy failed \u2014 try again"}Lp.set(t,setTimeout(()=>{delete t.dataset.copied,t.setAttribute("aria-label",o),t.title=o;let s=se("copy",14,"currentColor",1.7);s&&t.replaceChildren(s),Lp.delete(t)},1800))}var Vy=(t,e=!1)=>t.toggleTextColor||t.headerTextColor||(e?"currentColor":"var(--persona-primary, #171717)"),lx=(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(`
25
25
  `);let s=ls(n.args).trim();return s?s.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,e).join(`
26
- `):""},Pp=(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)"},ix=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??$o.collapsedMode,i=n?.success===!1?n.error||"Tool failed":sx(t,o?.previewMaxLines??$o.previewMaxLines),l=n?qo(e,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:jm(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",u=e?.toolCall??{},p=l;return s==="tool-name"?p=n.name?.trim()||l:s==="tool-preview"&&i&&(p=i),c&&u.activeTextTemplate?p=Sd(n,u.activeTextTemplate,p):!c&&u.completeTextTemplate&&(p=Sd(n,u.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:i,isActive:c}},Lp=(t,e,n,o)=>{hl(t,e,{stateSet:n,previewKind:"tool",iconColor:_y(o?.toolCall??{},e.classList.contains("persona-activity-row"))})},Ip=(t,e,n=new Set)=>{e=yl(e,"tool");let o=t.toolCall,s=e?.toolCall??{},i=ul("persona-tool-bubble",t.id);if(s.backgroundColor&&(i.style.backgroundColor=s.backgroundColor),s.borderColor&&(i.style.borderColor=s.borderColor),s.borderWidth&&(i.style.borderWidth=s.borderWidth),s.borderRadius&&(i.style.borderRadius=s.borderRadius),i.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:"var(--persona-tool-bubble-shadow)",!o)return mo(i,t,e,"tool");let l=e?.features?.toolCallDisplay??{},c=l.expandable??$o.expandable,u=c&&n.has(t.id),{summary:p,previewText:g,isActive:y}=ix(t,e),h=gl({expandable:c,expanded:u,bubbleType:"tool"});s.headerBackgroundColor&&(h.style.backgroundColor=s.headerBackgroundColor),s.headerPaddingX&&(h.style.paddingLeft=s.headerPaddingX,h.style.paddingRight=s.headerPaddingX),s.headerPaddingY&&(h.style.paddingTop=s.headerPaddingY,h.style.paddingBottom=s.headerPaddingY);let C=P("div","persona-flex persona-flex-col persona-text-left"),E=P("span","persona-text-xs persona-text-persona-primary");s.headerTextColor&&(E.style.color=s.headerTextColor);let A=String(o.startedAt??Date.now()),I=()=>{let v=P("span","");return v.setAttribute("data-tool-elapsed",A),v.textContent=Ya(o),v},L=s.renderCollapsedSummary?.({message:t,toolCall:o,defaultSummary:p,previewText:g,collapsedMode:l.collapsedMode??$o.collapsedMode,isActive:y,config:e??{},elapsed:Ya(o),createElapsedElement:I});typeof L=="string"&&L.trim()?(E.textContent=L,C.appendChild(E)):L instanceof HTMLElement?C.appendChild(L):(E.textContent=p,C.appendChild(E));let k=l.loadingAnimation??$o.loadingAnimation,R=s.activeTextTemplate,B=s.completeTextTemplate,O=y?R:B,V=L instanceof HTMLElement,J=(v,T)=>{E.textContent="";let x=o.name?.trim()||"tool",z=Xa(v,x),W=0;for(let ee of z){let ne=ee.styles.length>0?(()=>{let he=P("span",ee.styles.map(ve=>`persona-tool-text-${ve}`).join(" "));return E.appendChild(he),he})():E;if(ee.isDuration&&y)ne.appendChild(I());else{let he=ee.isDuration?Ya(o):ee.text;T?W=ms(ne,he,W):ne.appendChild(document.createTextNode(he))}}};if(!V)if(y&&k!=="none"){let v=s.loadingAnimationDuration??2e3;if(E.setAttribute("data-preserve-animation","true"),k==="pulse")E.classList.add("persona-tool-loading-pulse"),E.style.setProperty("--persona-tool-anim-duration",`${v}ms`),O&&J(O,!1);else if(E.classList.add(`persona-tool-loading-${k}`),E.style.setProperty("--persona-tool-anim-duration",`${v}ms`),k==="shimmer-color"&&(s.loadingAnimationColor&&E.style.setProperty("--persona-tool-anim-color",s.loadingAnimationColor),s.loadingAnimationSecondaryColor&&E.style.setProperty("--persona-tool-anim-secondary-color",s.loadingAnimationSecondaryColor)),O)J(O,!0);else{let T=E.textContent||p;E.textContent="",ms(E,T,0)}}else O&&J(O,!1);let _=_y(s,qo(e,"tool")==="row"),Q=fs(h,C,{expandable:c,expanded:u,iconColor:_,metaGap:!0}),G=ml({bubble:i,previewKind:"tool",expanded:u,isActive:y,previewText:g,activePreview:l.activePreview,activeMinHeight:l.activeMinHeight,renderPreview:()=>s.renderCollapsedPreview?.({message:t,toolCall:o,defaultPreview:g,isActive:y,config:e??{}})});if(!c)return i.append(h,G),mo(i,t,e,"tool");let w=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(w.style.display=u?"":"none",s.contentBackgroundColor&&(w.style.backgroundColor=s.contentBackgroundColor),s.contentTextColor&&(w.style.color=s.contentTextColor),s.contentPaddingX&&(w.style.paddingLeft=s.contentPaddingX,w.style.paddingRight=s.contentPaddingX),s.contentPaddingY&&(w.style.paddingTop=s.contentPaddingY,w.style.paddingBottom=s.contentPaddingY),e.future?.v5Defaults===!0)Dy(w,t,e);else{if(o.name){let v=P("div","persona-text-xs persona-text-persona-muted persona-italic");s.contentTextColor?v.style.color=s.contentTextColor:s.headerTextColor&&(v.style.color=s.headerTextColor),v.textContent=o.name,w.appendChild(v)}if(o.args!==void 0){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Arguments";let x=P("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");x.style.fontSize="0.75rem",x.style.lineHeight="1rem",Pp(x,s),x.textContent=ls(o.args),v.append(T,x),w.appendChild(v)}if(o.chunks&&o.chunks.length){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Activity";let x=P("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");x.style.fontSize="0.75rem",x.style.lineHeight="1rem",Pp(x,s),x.textContent=o.chunks.join(""),v.append(T,x),w.appendChild(v)}if(o.success===!1&&w.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Result";let x=P("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");x.style.fontSize="0.75rem",x.style.lineHeight="1rem",Pp(x,s),x.textContent=ls(o.result),v.append(T,x),w.appendChild(v)}if(o.status==="complete"&&typeof o.duration=="number"){let v=P("div","persona-text-xs persona-text-persona-muted");s.contentTextColor&&(v.style.color=s.contentTextColor),v.textContent=`Duration: ${o.duration}ms`,w.appendChild(v)}}return fl({expanded:u,header:h,toggleIcon:Q,content:w,collapsedPreview:G,iconColor:_}),i.append(h,G,w),mo(i,t,e,"tool")};var{setLoader:hk,load:ax,provide:yk,getSync:lx}=je({fallbackImport:()=>import("./approval-ui-QAKWNFNM.js")});var Fy=ax;var Ny=lx;var{setLoader:Ck,load:cx}=je({fallbackImport:()=>import("./event-stream-view-FOIJHFQO.js")});var Hp=cx;var Rp=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:Ek,load:dx,provide:Tk,getSync:px}=je({fallbackImport:()=>import("./artifacts-ui-NJGMM27I.js")}),xs=null,$l=new Set,Vy=t=>{if(xs)return xs;xs=t,t.initArtifactsUi({componentRegistry:go});for(let o of Rp)go.has(o)||go.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=is();e?t.__provideMarkdownParsers(e):qa(()=>{let o=is();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Bm());let n=[...$l];$l.clear();for(let o of n)try{o()}catch{}return t};var zl=()=>dx().then(Vy);var yo=()=>{if(xs)return xs;let t=px();return t?Vy(t):null},Wp=t=>xs?()=>{}:($l.add(t),()=>{$l.delete(t)});function zt(t){return t?.features?.artifacts?.enabled===!0}function $y(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"),!zt(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 ux(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 zy=["panel","seamless","detached"];function Bp(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&zy.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Dp(t){return!t||!zt(t)?!1:Bp(t)==="detached"}function Oi(t,e){if(!zt(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"),ux(t),$y(t,e);return}let n=e.features?.artifacts?.layout,o=Bp(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,u]of l){let p=c?.trim();p?t.style.setProperty(u,p):t.style.removeProperty(u)}$y(t,e)}function _i(t,e){for(let c of zy)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"),!zt(e))return;let n=e.features?.artifacts?.layout,o=Bp(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 Uy(t,e){return!e||!zt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var gx=new Set(["__proto__","prototype","constructor"]),mx=new Set(["collapsed","card","panel","inline"]),qy=new Set(["markdown","component"]),fx=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Lr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ql=t=>!gx.has(t),Op=t=>typeof t=="string"&&mx.has(t),Ir=t=>Object.keys(t).length>0;function Gn(t,e,n,o){t.push({path:e,code:n,message:o})}var hx="Ignored because this key is not part of the persisted preference schema.",Ul="Ignored an unsupported value.",yx="Expected collapsed, panel, or inline.",bx='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',jy={kind:"mode",message:Ul},As={kind:"string",message:"Expected a CSS length string."},bo={kind:"boolean"},vx={paneWidth:As,paneMaxWidth:As,paneMinWidth:As,expandedPanelWidth:As,resizableMinWidth:As,resizableMaxWidth:As,expandLauncherPanelWhenOpen:bo,resizable:bo},Cx={kind:"object",message:"Expected a preference object.",children:{showToolCalls:bo,showReasoning:bo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ul},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ul},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ul},expandable:bo,grouped:bo}},reasoningDisplay:{kind:"object",children:{expandable:bo,activePreview:bo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:jy,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:jy,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:qy,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:qy}}},filePreview:{kind:"object",children:{enabled:bo}},layout:{kind:"object",children:vx}}}}};function Ky(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Gn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Gn(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Gn(o,n,"invalid_value",e.message);case"mode":return Op(t)?Ga(t):Gn(o,n,"invalid_value",e.message);case"modeMap":{if(!Lr(t))return Gn(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 u=s?l:zm(l);ql(l)&&(s?s.has(l):fx.test(u))?Op(c)?i[u]=Ga(c):Gn(o,`${n}.${l}`,"invalid_value",yx):Gn(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":bx)}return Ir(i)?i:void 0}case"object":{if(e.bareMode&&Op(t))return Ga(t);if(!Lr(t))return Gn(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))(!ql(c)||!s.includes(c))&&Gn(o,i(c),"unknown_key",hx);let l={};for(let c of s){let u=e.children[c],p=Ky(t[c],u,i(c),o);if(u.deprecated&&t[c]!==void 0&&Gn(o,i(c),"deprecated_key",u.deprecated),p===void 0)continue;let g=u.alias??c,y=l[g];l[g]=Lr(y)&&Lr(p)?{...y,...p}:p}return Ir(l)?l:void 0}}}function wx(t){let e=[];return{preferences:(t===null?void 0:Ky(t,Cx,"",e))??{},issues:e}}function Ms(t){if(Array.isArray(t))return t.map(Ms);if(!Lr(t))return t;let e={};for(let[n,o]of Object.entries(t))ql(n)&&o!==void 0&&(e[n]=Ms(o));return e}function Gy(t,e){let n=Ms(t);for(let[o,s]of Object.entries(e)){if(!ql(o)||s===void 0)continue;let i=n[o];n[o]=Lr(i)&&Lr(s)?Gy(i,s):Ms(s)}return n}function Sx(t){let e={},n;for(let s of t){let i=wx(s).preferences;n=Yy(n,i.artifacts?.display),e=Gy(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function xx(t,e){if(e===void 0)return t===void 0?void 0:Ms(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}:{},...Ir(s)?{byMediaType:s}:{}};return Ir(i)?i:void 0}function Yy(t,e){if(e===void 0)return t===void 0?void 0:Ms(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=xx(n.files,e.files),l={...o?{default:o}:{},...Ir(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return Ir(l)?l:void 0}function Ax(t={},e){let n=Sx(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=Yy(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 _p(t){let e=t.preferences;return!e||!Ir(e)?t:{...t,features:Ax(t.features??{},[e])}}function Mx(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 Ex(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 Tx(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function kx(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function Fp(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 Qy(t,e,n,o,s,i,l=200){let c=Mx(s,200),u=kx(e,n,o,l);u=Math.max(c,u);let p=Ex(i);return p!==null&&(u=Math.min(u,p)),Tx(t,c,u)}var{setLoader:Wk,load:Px,provide:Bk,getSync:Lx}=je({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var Xy=Px;var Jy=Lx;var Np=class{#e=new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.#e.get(e);n&&(n.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.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.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},Vp=new Np;var Zy=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Ix=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),eb=(t,e,n)=>{if(!Zy(t)||!Zy(e)||Ix.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]=eb(t[s],e[s],i)}return o};function tb(t,e){let n=Em(za),o=km(t,e,n),s=Tm(Pm(eb(t,e,""),n,o),o);return Im(Ua(s),Hm(t,e))}var nb=()=>{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 Hx=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},Rx=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},zp=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Hx(t),n=Rx(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}},$p=t=>typeof t=="string"?t:t==null?"":String(t),Fi={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:$p(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=$p(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:$p(n.text)}}},ob=t=>Array.isArray(t)?t.map(e=>String(e)):[],Up=t=>{let e=new Set(ob(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(ob(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((p,g)=>p||g?.({text:l,message:i.message})||null,null):null;if(!c)return null;e.add(i.message.id),o();let u={action:c,message:i.message};t.emit("action:detected",u);for(let p of t.handlers)if(p)try{let g=()=>{t.emit("action:resubmit",u)},y=p(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:g});if(!y)continue;if(y.handled){let h=y.persistMessage!==!1;return{text:y.displayText!==void 0?y.displayText:"",persist:h,resubmit:y.resubmit}}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:n}};var Wx=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}},Bx=t=>t.map(e=>({...e,streaming:!1})),Dx=t=>t.map(e=>({...e,status:"complete"})),rb=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Wx(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?Bx(n.messages):void 0,artifacts:n.artifacts?Dx(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 Ox=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")},sb=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 Ox(t)},_x=async(t,e)=>{let n=await sb(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await sb(`${t}\0${e}`)}`}};var ib=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,u=0,p=null,g=null,y=new Set,h=()=>{if(n||l)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return l=!0,null}},C=()=>{let _=h();if(!_)return p;try{return _.getItem(o)}catch{return l=!0,p}},E=(_,Q)=>{if(c||_===p)return;let G=p;p=_,u+=1;let w={previousToken:G,token:_,source:Q,revision:u};for(let v of y)v(w)},A=_=>{c||_.key!==null&&_.key!==o||E(_.key===null?null:_.newValue??null,"external")},I=(async()=>{let _=await _x(t,e);o=_.storageKey,s=_.leaseKey,i=_.lockName,p=C(),!n&&typeof window<"u"&&window.addEventListener("storage",A)})(),L=_=>new Promise(Q=>setTimeout(Q,_)),k=()=>{let _=h();if(!_)return null;try{let Q=_.getItem(s);if(!Q)return null;let G=JSON.parse(Q);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},R=_=>{let Q=h();if(Q)try{k()?.ownerNonce===_&&Q.removeItem(s)}catch{}},B=new Set,O=_=>c?Promise.reject(new Error("Visitor store destroyed before its first init could start")):_(),V=_=>new Promise(Q=>{let G=setTimeout(w,_);function w(){clearTimeout(G),B.delete(w),window.removeEventListener("storage",v),Q()}function v(T){(T.key===null||T.key===s)&&w()}B.add(w),window.addEventListener("storage",v)}),J=async _=>{let Q=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;!c&&Date.now()<G;){let w=h();if(!w)break;let v=Date.now(),T=k();if(T&&T.expiresAt>v&&T.ownerNonce!==Q){await V(Math.min(T.expiresAt-v,500));continue}try{w.setItem(s,JSON.stringify({ownerNonce:Q,expiresAt:v+1e4}))}catch{l=!0;break}if(await L(20+Math.random()*40),k()?.ownerNonce!==Q){await V(500);continue}g=Q;try{return await O(_)}finally{g=null,R(Q)}}return O(_)};return{ready:I,async get(){return await I,E(C(),"external"),p},async set(_){await I;let Q=h();if(Q)try{Q.setItem(o,_)}catch{l=!0}E(_,"local")},async clear(){await I;let _=h();if(_)try{_.removeItem(o)}catch{l=!0}E(null,"local")},revision(){return u},subscribe(_){return y.add(_),()=>{y.delete(_)}},async withFirstInitLock(_){await I;let Q=globalThis.navigator?.locks;return Q?.request?Q.request(i,()=>O(_)):h()?J(_):O(_)},matches(_,Q,G){return _===t&&Q===e&&G===n},destroy(){c=!0,y.clear(),typeof window<"u"&&window.removeEventListener("storage",A),g&&R(g);for(let _ of[...B])_()}}};var{setLoader:Kk,load:Fx}=je({fallbackImport:()=>import("./history-view-NCFBI5GR.js")});var ab=Fx;var{setLoader:Qk,load:Nx,provide:Xk,getSync:Vx}=je({fallbackImport:()=>import("./history-shell-QDQ44PSE.js")});var lb=Nx;var jl=Vx;var $x=null;function cb(){return $x}import{parse as tP,STR as nP,OBJ as oP}from"partial-json";function db(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=go.get(t.component);if(!i){if(Rp.includes(t.component)){zl().catch(()=>{});let c=P("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 pb(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 qp(t){let e=pb(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 ub(t){let e=pb(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 zx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function gb(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:u=!0,ratingLabels:p=zx}=t,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let y=null,h=document.createElement("div");h.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=o,C.appendChild(E);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,C.appendChild(A),h.appendChild(C);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let V=1;V<=5;V++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-star-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),J.title=p[V-1],J.dataset.rating=String(V),J.innerHTML=`
26
+ `):""},Ip=(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)"},cx=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??$o.collapsedMode,i=n?.success===!1?n.error||"Tool failed":lx(t,o?.previewMaxLines??$o.previewMaxLines),l=n?qo(e,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:Ym(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",u=e?.toolCall??{},p=l;return s==="tool-name"?p=n.name?.trim()||l:s==="tool-preview"&&i&&(p=i),c&&u.activeTextTemplate?p=Ad(n,u.activeTextTemplate,p):!c&&u.completeTextTemplate&&(p=Ad(n,u.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:i,isActive:c}},Hp=(t,e,n,o)=>{bl(t,e,{stateSet:n,previewKind:"tool",iconColor:Vy(o?.toolCall??{},e.classList.contains("persona-activity-row"))})},Rp=(t,e,n=new Set)=>{e=vl(e,"tool");let o=t.toolCall,s=e?.toolCall??{},i=ml("persona-tool-bubble",t.id);if(s.backgroundColor&&(i.style.backgroundColor=s.backgroundColor),s.borderColor&&(i.style.borderColor=s.borderColor),s.borderWidth&&(i.style.borderWidth=s.borderWidth),s.borderRadius&&(i.style.borderRadius=s.borderRadius),i.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:"var(--persona-tool-bubble-shadow)",!o)return mo(i,t,e,"tool");let l=e?.features?.toolCallDisplay??{},c=l.expandable??$o.expandable,u=c&&n.has(t.id),{summary:p,previewText:g,isActive:y}=cx(t,e),h=fl({expandable:c,expanded:u,bubbleType:"tool"});s.headerBackgroundColor&&(h.style.backgroundColor=s.headerBackgroundColor),s.headerPaddingX&&(h.style.paddingLeft=s.headerPaddingX,h.style.paddingRight=s.headerPaddingX),s.headerPaddingY&&(h.style.paddingTop=s.headerPaddingY,h.style.paddingBottom=s.headerPaddingY);let C=P("div","persona-flex persona-flex-col persona-text-left"),E=P("span","persona-text-xs persona-text-persona-primary");s.headerTextColor&&(E.style.color=s.headerTextColor);let A=String(o.startedAt??Date.now()),I=()=>{let v=P("span","");return v.setAttribute("data-tool-elapsed",A),v.textContent=Xa(o),v},L=s.renderCollapsedSummary?.({message:t,toolCall:o,defaultSummary:p,previewText:g,collapsedMode:l.collapsedMode??$o.collapsedMode,isActive:y,config:e??{},elapsed:Xa(o),createElapsedElement:I});typeof L=="string"&&L.trim()?(E.textContent=L,C.appendChild(E)):L instanceof HTMLElement?C.appendChild(L):(E.textContent=p,C.appendChild(E));let k=l.loadingAnimation??$o.loadingAnimation,R=s.activeTextTemplate,B=s.completeTextTemplate,O=y?R:B,V=L instanceof HTMLElement,J=(v,T)=>{E.textContent="";let S=o.name?.trim()||"tool",z=Za(v,S),W=0;for(let ee of z){let ne=ee.styles.length>0?(()=>{let he=P("span",ee.styles.map(ve=>`persona-tool-text-${ve}`).join(" "));return E.appendChild(he),he})():E;if(ee.isDuration&&y)ne.appendChild(I());else{let he=ee.isDuration?Xa(o):ee.text;T?W=ms(ne,he,W):ne.appendChild(document.createTextNode(he))}}};if(!V)if(y&&k!=="none"){let v=s.loadingAnimationDuration??2e3;if(E.setAttribute("data-preserve-animation","true"),k==="pulse")E.classList.add("persona-tool-loading-pulse"),E.style.setProperty("--persona-tool-anim-duration",`${v}ms`),O&&J(O,!1);else if(E.classList.add(`persona-tool-loading-${k}`),E.style.setProperty("--persona-tool-anim-duration",`${v}ms`),k==="shimmer-color"&&(s.loadingAnimationColor&&E.style.setProperty("--persona-tool-anim-color",s.loadingAnimationColor),s.loadingAnimationSecondaryColor&&E.style.setProperty("--persona-tool-anim-secondary-color",s.loadingAnimationSecondaryColor)),O)J(O,!0);else{let T=E.textContent||p;E.textContent="",ms(E,T,0)}}else O&&J(O,!1);let _=Vy(s,qo(e,"tool")==="row"),Q=fs(h,C,{expandable:c,expanded:u,iconColor:_,metaGap:!0}),G=hl({bubble:i,previewKind:"tool",expanded:u,isActive:y,previewText:g,activePreview:l.activePreview,activeMinHeight:l.activeMinHeight,renderPreview:()=>s.renderCollapsedPreview?.({message:t,toolCall:o,defaultPreview:g,isActive:y,config:e??{}})});if(!c)return i.append(h,G),mo(i,t,e,"tool");let w=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(w.style.display=u?"":"none",s.contentBackgroundColor&&(w.style.backgroundColor=s.contentBackgroundColor),s.contentTextColor&&(w.style.color=s.contentTextColor),s.contentPaddingX&&(w.style.paddingLeft=s.contentPaddingX,w.style.paddingRight=s.contentPaddingX),s.contentPaddingY&&(w.style.paddingTop=s.contentPaddingY,w.style.paddingBottom=s.contentPaddingY),e.future?.v5Defaults===!0)Fy(w,t,e);else{if(o.name){let v=P("div","persona-text-xs persona-text-persona-muted persona-italic");s.contentTextColor?v.style.color=s.contentTextColor:s.headerTextColor&&(v.style.color=s.headerTextColor),v.textContent=o.name,w.appendChild(v)}if(o.args!==void 0){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Arguments";let S=P("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",Ip(S,s),S.textContent=ls(o.args),v.append(T,S),w.appendChild(v)}if(o.chunks&&o.chunks.length){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Activity";let S=P("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",Ip(S,s),S.textContent=o.chunks.join(""),v.append(T,S),w.appendChild(v)}if(o.success===!1&&w.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Result";let S=P("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",Ip(S,s),S.textContent=ls(o.result),v.append(T,S),w.appendChild(v)}if(o.status==="complete"&&typeof o.duration=="number"){let v=P("div","persona-text-xs persona-text-persona-muted");s.contentTextColor&&(v.style.color=s.contentTextColor),v.textContent=`Duration: ${o.duration}ms`,w.appendChild(v)}}return yl({expanded:u,header:h,toggleIcon:Q,content:w,collapsedPreview:G,iconColor:_}),i.append(h,G,w),mo(i,t,e,"tool")};var{setLoader:Ck,load:dx,provide:wk,getSync:px}=je({fallbackImport:()=>import("./approval-ui-QAKWNFNM.js")});var $y=dx;var zy=px;var{setLoader:Ak,load:ux}=je({fallbackImport:()=>import("./event-stream-view-FOIJHFQO.js")});var Wp=ux;var Bp=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:Lk,load:gx,provide:Ik,getSync:mx}=je({fallbackImport:()=>import("./artifacts-ui-NJGMM27I.js")}),xs=null,Ul=new Set,Uy=t=>{if(xs)return xs;xs=t,t.initArtifactsUi({componentRegistry:go});for(let o of Bp)go.has(o)||go.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=is();e?t.__provideMarkdownParsers(e):Ka(()=>{let o=is();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>_m());let n=[...Ul];Ul.clear();for(let o of n)try{o()}catch{}return t};var ql=()=>gx().then(Uy);var yo=()=>{if(xs)return xs;let t=mx();return t?Uy(t):null},Dp=t=>xs?()=>{}:(Ul.add(t),()=>{Ul.delete(t)});function zt(t){return t?.features?.artifacts?.enabled===!0}function qy(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"),!zt(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 fx(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 jy=["panel","seamless","detached"];function Op(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&jy.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function _p(t){return!t||!zt(t)?!1:Op(t)==="detached"}function Oi(t,e){if(!zt(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"),fx(t),qy(t,e);return}let n=e.features?.artifacts?.layout,o=Op(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,u]of l){let p=c?.trim();p?t.style.setProperty(u,p):t.style.removeProperty(u)}qy(t,e)}function _i(t,e){for(let c of jy)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"),!zt(e))return;let n=e.features?.artifacts?.layout,o=Op(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 Ky(t,e){return!e||!zt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var hx=new Set(["__proto__","prototype","constructor"]),yx=new Set(["collapsed","card","panel","inline"]),Gy=new Set(["markdown","component"]),bx=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Lr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Kl=t=>!hx.has(t),Fp=t=>typeof t=="string"&&yx.has(t),Ir=t=>Object.keys(t).length>0;function Gn(t,e,n,o){t.push({path:e,code:n,message:o})}var vx="Ignored because this key is not part of the persisted preference schema.",jl="Ignored an unsupported value.",Cx="Expected collapsed, panel, or inline.",wx='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Yy={kind:"mode",message:jl},As={kind:"string",message:"Expected a CSS length string."},bo={kind:"boolean"},Sx={paneWidth:As,paneMaxWidth:As,paneMinWidth:As,expandedPanelWidth:As,resizableMinWidth:As,resizableMaxWidth:As,expandLauncherPanelWhenOpen:bo,resizable:bo},xx={kind:"object",message:"Expected a preference object.",children:{showToolCalls:bo,showReasoning:bo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:jl},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:jl},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:jl},expandable:bo,grouped:bo}},reasoningDisplay:{kind:"object",children:{expandable:bo,activePreview:bo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Yy,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Yy,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Gy,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Gy}}},filePreview:{kind:"object",children:{enabled:bo}},layout:{kind:"object",children:Sx}}}}};function Qy(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Gn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Gn(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Gn(o,n,"invalid_value",e.message);case"mode":return Fp(t)?Qa(t):Gn(o,n,"invalid_value",e.message);case"modeMap":{if(!Lr(t))return Gn(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 u=s?l:jm(l);Kl(l)&&(s?s.has(l):bx.test(u))?Fp(c)?i[u]=Qa(c):Gn(o,`${n}.${l}`,"invalid_value",Cx):Gn(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":wx)}return Ir(i)?i:void 0}case"object":{if(e.bareMode&&Fp(t))return Qa(t);if(!Lr(t))return Gn(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))(!Kl(c)||!s.includes(c))&&Gn(o,i(c),"unknown_key",vx);let l={};for(let c of s){let u=e.children[c],p=Qy(t[c],u,i(c),o);if(u.deprecated&&t[c]!==void 0&&Gn(o,i(c),"deprecated_key",u.deprecated),p===void 0)continue;let g=u.alias??c,y=l[g];l[g]=Lr(y)&&Lr(p)?{...y,...p}:p}return Ir(l)?l:void 0}}}function Ax(t){let e=[];return{preferences:(t===null?void 0:Qy(t,xx,"",e))??{},issues:e}}function Ms(t){if(Array.isArray(t))return t.map(Ms);if(!Lr(t))return t;let e={};for(let[n,o]of Object.entries(t))Kl(n)&&o!==void 0&&(e[n]=Ms(o));return e}function Xy(t,e){let n=Ms(t);for(let[o,s]of Object.entries(e)){if(!Kl(o)||s===void 0)continue;let i=n[o];n[o]=Lr(i)&&Lr(s)?Xy(i,s):Ms(s)}return n}function Mx(t){let e={},n;for(let s of t){let i=Ax(s).preferences;n=Jy(n,i.artifacts?.display),e=Xy(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Ex(t,e){if(e===void 0)return t===void 0?void 0:Ms(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}:{},...Ir(s)?{byMediaType:s}:{}};return Ir(i)?i:void 0}function Jy(t,e){if(e===void 0)return t===void 0?void 0:Ms(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=Ex(n.files,e.files),l={...o?{default:o}:{},...Ir(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return Ir(l)?l:void 0}function Tx(t={},e){let n=Mx(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=Jy(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 Np(t){let e=t.preferences;return!e||!Ir(e)?t:{...t,features:Tx(t.features??{},[e])}}function kx(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 Px(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 Lx(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function Ix(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function Vp(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 Zy(t,e,n,o,s,i,l=200){let c=kx(s,200),u=Ix(e,n,o,l);u=Math.max(c,u);let p=Px(i);return p!==null&&(u=Math.min(u,p)),Lx(t,c,u)}var{setLoader:_k,load:Hx,provide:Fk,getSync:Rx}=je({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var eb=Hx;var tb=Rx;var $p=class{#e=new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.#e.get(e);n&&(n.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.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.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},zp=new $p;var nb=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Wx=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),ob=(t,e,n)=>{if(!nb(t)||!nb(e)||Wx.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]=ob(t[s],e[s],i)}return o};function rb(t,e){let n=Pm(qa),o=Im(t,e,n),s=Lm(Hm(ob(t,e,""),n,o),o);return Wm(ja(s),Bm(t,e))}var sb=()=>{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 Bx=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},Dx=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},qp=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Bx(t),n=Dx(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}},Up=t=>typeof t=="string"?t:t==null?"":String(t),Fi={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Up(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Up(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:Up(n.text)}}},ib=t=>Array.isArray(t)?t.map(e=>String(e)):[],jp=t=>{let e=new Set(ib(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(ib(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((p,g)=>p||g?.({text:l,message:i.message})||null,null):null;if(!c)return null;e.add(i.message.id),o();let u={action:c,message:i.message};t.emit("action:detected",u);for(let p of t.handlers)if(p)try{let g=()=>{t.emit("action:resubmit",u)},y=p(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:g});if(!y)continue;if(y.handled){let h=y.persistMessage!==!1;return{text:y.displayText!==void 0?y.displayText:"",persist:h,resubmit:y.resubmit}}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:n}};var Ox=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}},_x=t=>t.map(e=>({...e,streaming:!1})),Fx=t=>t.map(e=>({...e,status:"complete"})),ab=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Ox(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?_x(n.messages):void 0,artifacts:n.artifacts?Fx(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 Nx=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")},lb=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 Nx(t)},Vx=async(t,e)=>{let n=await lb(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await lb(`${t}\0${e}`)}`}};var cb=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,u=0,p=null,g=null,y=new Set,h=()=>{if(n||l)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return l=!0,null}},C=()=>{let _=h();if(!_)return p;try{return _.getItem(o)}catch{return l=!0,p}},E=(_,Q)=>{if(c||_===p)return;let G=p;p=_,u+=1;let w={previousToken:G,token:_,source:Q,revision:u};for(let v of y)v(w)},A=_=>{c||_.key!==null&&_.key!==o||E(_.key===null?null:_.newValue??null,"external")},I=(async()=>{let _=await Vx(t,e);o=_.storageKey,s=_.leaseKey,i=_.lockName,p=C(),!n&&typeof window<"u"&&window.addEventListener("storage",A)})(),L=_=>new Promise(Q=>setTimeout(Q,_)),k=()=>{let _=h();if(!_)return null;try{let Q=_.getItem(s);if(!Q)return null;let G=JSON.parse(Q);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},R=_=>{let Q=h();if(Q)try{k()?.ownerNonce===_&&Q.removeItem(s)}catch{}},B=new Set,O=_=>c?Promise.reject(new Error("Visitor store destroyed before its first init could start")):_(),V=_=>new Promise(Q=>{let G=setTimeout(w,_);function w(){clearTimeout(G),B.delete(w),window.removeEventListener("storage",v),Q()}function v(T){(T.key===null||T.key===s)&&w()}B.add(w),window.addEventListener("storage",v)}),J=async _=>{let Q=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;!c&&Date.now()<G;){let w=h();if(!w)break;let v=Date.now(),T=k();if(T&&T.expiresAt>v&&T.ownerNonce!==Q){await V(Math.min(T.expiresAt-v,500));continue}try{w.setItem(s,JSON.stringify({ownerNonce:Q,expiresAt:v+1e4}))}catch{l=!0;break}if(await L(20+Math.random()*40),k()?.ownerNonce!==Q){await V(500);continue}g=Q;try{return await O(_)}finally{g=null,R(Q)}}return O(_)};return{ready:I,async get(){return await I,E(C(),"external"),p},async set(_){await I;let Q=h();if(Q)try{Q.setItem(o,_)}catch{l=!0}E(_,"local")},async clear(){await I;let _=h();if(_)try{_.removeItem(o)}catch{l=!0}E(null,"local")},revision(){return u},subscribe(_){return y.add(_),()=>{y.delete(_)}},async withFirstInitLock(_){await I;let Q=globalThis.navigator?.locks;return Q?.request?Q.request(i,()=>O(_)):h()?J(_):O(_)},matches(_,Q,G){return _===t&&Q===e&&G===n},destroy(){c=!0,y.clear(),typeof window<"u"&&window.removeEventListener("storage",A),g&&R(g);for(let _ of[...B])_()}}};var{setLoader:Xk,load:$x}=je({fallbackImport:()=>import("./history-view-NCFBI5GR.js")});var db=$x;var{setLoader:eP,load:zx,provide:tP,getSync:Ux}=je({fallbackImport:()=>import("./history-shell-QDQ44PSE.js")});var pb=zx;var Gl=Ux;var qx=null;function ub(){return qx}import{parse as sP,STR as iP,OBJ as aP}from"partial-json";function gb(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=go.get(t.component);if(!i){if(Bp.includes(t.component)){ql().catch(()=>{});let c=P("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 mb(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 Kp(t){let e=mb(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 fb(t){let e=mb(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 jx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hb(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:u=!0,ratingLabels:p=jx}=t,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let y=null,h=document.createElement("div");h.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=o,C.appendChild(E);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,C.appendChild(A),h.appendChild(C);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let V=1;V<=5;V++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-star-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),J.title=p[V-1],J.dataset.rating=String(V),J.innerHTML=`
27
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
28
28
  <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>
29
29
  </svg>
30
- `,J.addEventListener("click",()=>{y=V,L.forEach((_,Q)=>{let G=Q<V;_.classList.toggle("selected",G),_.setAttribute("aria-checked",Q===V-1?"true":"false")})}),L.push(J),I.appendChild(J)}h.appendChild(I);let k=null;if(u){let V=document.createElement("div");V.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=i,k.rows=3,k.setAttribute("aria-label","Additional comments"),V.appendChild(k),h.appendChild(V)}let R=document.createElement("div");R.className="persona-feedback-actions";let B=document.createElement("button");B.type="button",B.className="persona-feedback-btn persona-feedback-btn-skip",B.textContent=c,B.addEventListener("click",()=>{n?.(),g.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=l,O.addEventListener("click",async()=>{if(y===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let V=k?.value.trim()||void 0;await e(y,V),g.remove()}catch(V){O.disabled=!1,O.textContent=l,console.error("[CSAT Feedback] Failed to submit:",V)}}),R.appendChild(B),R.appendChild(O),h.appendChild(R),g.appendChild(h),g}function mb(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:u=!0,lowLabel:p="Not likely",highLabel:g="Very likely"}=t,y=document.createElement("div");y.className="persona-feedback-container persona-feedback-nps",y.setAttribute("role","dialog"),y.setAttribute("aria-label","Net Promoter Score feedback");let h=null,C=document.createElement("div");C.className="persona-feedback-content";let E=document.createElement("div");E.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=o,E.appendChild(A);let I=document.createElement("p");I.className="persona-feedback-subtitle",I.textContent=s,E.appendChild(I),C.appendChild(E);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=p;let B=document.createElement("span");B.className="persona-feedback-label-high",B.textContent=g,k.appendChild(R),k.appendChild(B);let O=document.createElement("div");O.className="persona-feedback-numbers";let V=[];for(let w=0;w<=10;w++){let v=document.createElement("button");v.type="button",v.className="persona-feedback-rating-btn persona-feedback-number-btn",v.setAttribute("role","radio"),v.setAttribute("aria-checked","false"),v.setAttribute("aria-label",`Rating ${w} out of 10`),v.textContent=String(w),v.dataset.rating=String(w),w<=6?v.classList.add("persona-feedback-detractor"):w<=8?v.classList.add("persona-feedback-passive"):v.classList.add("persona-feedback-promoter"),v.addEventListener("click",()=>{h=w,V.forEach((T,x)=>{T.classList.toggle("selected",x===w),T.setAttribute("aria-checked",x===w?"true":"false")})}),V.push(v),O.appendChild(v)}L.appendChild(k),L.appendChild(O),C.appendChild(L);let J=null;if(u){let w=document.createElement("div");w.className="persona-feedback-comment-container",J=document.createElement("textarea"),J.className="persona-feedback-comment",J.placeholder=i,J.rows=3,J.setAttribute("aria-label","Additional comments"),w.appendChild(J),C.appendChild(w)}let _=document.createElement("div");_.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=c,Q.addEventListener("click",()=>{n?.(),y.remove()});let G=document.createElement("button");return G.type="button",G.className="persona-feedback-btn persona-feedback-btn-submit",G.textContent=l,G.addEventListener("click",async()=>{if(h===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}G.disabled=!0,G.textContent="Submitting...";try{let w=J?.value.trim()||void 0;await e(h,w),y.remove()}catch(w){G.disabled=!1,G.textContent=l,console.error("[NPS Feedback] Failed to submit:",w)}}),_.appendChild(Q),_.appendChild(G),C.appendChild(_),y.appendChild(C),y}var Es="persona-chat-history",Yx=30*1e3,Qx=641,Ts="data-persona-composer-reason",Xx={"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 Jx(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=Xx[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 Kl(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 Zx(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 eA(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var jp=t=>!t||typeof t!="object"?{}:{...t},bb=t=>t.map(e=>({...e,streaming:!1})),vb=(t,e,n)=>{let o=t?.markdown?_m(t.markdown):null,s=Fm(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 u=c.text??"",p=c.message.rawContent??null;if(e){let h=e.process({text:u,raw:p??u,message:c.message,streaming:c.streaming});h!==null&&(u=h.text,h.persist||(c.message.__skipPersist=!0),h.resubmit&&!c.streaming&&n&&n())}let g=is()!==null,y;if(t?.postprocessMessage){let h=t.postprocessMessage({...c,text:u,raw:p??c.text??""});y=s?s(h):h}else if(o){let h=c.streaming?Uf(u):u,C=o(h);y=s&&g?s(C):C}else y=ja(u);return y};return c=>{try{return l(c)}catch(u){return i||(i=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",u)),ja(c.text??"")}}};function Cb(t){let e=P("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=se(n,o,s,i);if(l&&e.appendChild(l),t?.label){let c=P("span","persona-drop-overlay-label");c.textContent=t.label,e.appendChild(c)}return e}var tA=(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},nA=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:tA(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),wb=(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=Ua(e),s=new Set,i=new Set,l=Of((r,a)=>{It.delete(r);let d=Array.from(ce.querySelectorAll("[data-message-id]")).find(m=>m.dataset.messageId===r);d&&(a==="tool"?Lp(r,d,s,o):Ep(r,d,i))}),c=new Map,u=()=>{af({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};u();let p=o.features;o=_p(o);let g=Vp.getForInstance(o.plugins),y=Mf(t),h=[],C=!1,E=Wy(()=>o),A=null,I=null,L=null,k=!1,R=null,B=r=>{A=r,r.initApprovalUi({webMcpToolTitle:Ka});let a=r.createBuiltInApprovalPlugin(c);I=a.plugin,L=a.teardown},O=()=>{if(A)return A;let r=Ny();return r?(B(r),r):(Fy().then(a=>{k||A||(B(a),R?.())}).catch(()=>{}),null)},V=!1,J=!1,_=null,Q=(r,a,d,m)=>{if(!r.querySelector("[data-tv-form]"))return;let f=Jy();if(f){f.enhanceWithForms(r,a,d,m);return}Xy().then(()=>{V||J||!_||(J=!0,_())}).catch(()=>{})};o.components&&go.registerAll(o.components);let G=nb(),v=o.persistState===!1?null:o.storageAdapter??rb(),T=!!o.clientToken&&typeof o.reconnectStream!="function",x={},z=null,W,ee=new Promise(r=>{W=r}),ne=()=>{},he=new Promise(r=>{ne=r}),ve,Xe=!1,Je=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&&(Xe=!0),d}return a}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}return r};if(v?.load)try{let r=v.load();if(r&&typeof r.then=="function")z=r.then(a=>Je(a??{messages:[],metadata:{}}));else{let d=Je(r??{messages:[],metadata:{}});d.metadata&&(x=jp(d.metadata)),d.messages?.length&&(o={...o,initialMessages:d.messages}),d.artifacts?.length&&(o={...o,initialArtifacts:d.artifacts,initialSelectedArtifactId:d.selectedArtifactId??null}),ve=d.draft}}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",r)}else if(o.onStateLoaded)try{let r=Je({messages:[],metadata:{}});r.messages?.length&&(o={...o,initialMessages:r.messages})}catch(r){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",r)}z||W();let Wt=()=>x,$e=r=>{x=r({...x})??{},Ur()},Ce=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zp],H=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Fi.message,Fi.messageAndClick],Me=Up({parsers:Ce,handlers:H,getSessionMetadata:Wt,updateSessionMetadata:$e,emit:G.emit,documentRef:typeof document<"u"?document:null});Me.syncFromMetadata();let de=o.launcher?.enabled??!0,In=o.launcher?.autoExpand??!1,Ps=o.autoFocusInput??!1,Zp=In,eu=de,tu=o.layout?.header?.layout,Yl=!1,Ae=()=>Ii(o),Ve=()=>de||Ae(),Se=Ae()?!1:de?In:!0,Ls=!1,Hr=null,nu=()=>{Ls=!0,Hr&&clearTimeout(Hr),Hr=setTimeout(()=>{Ls&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Ls=!1)},1e4)},Xt=vb(o,Me,nu),Is=o.features?.showReasoning??!0,Hs=o.features?.showToolCalls??!0,Jt=o.features?.showEventStreamToggle??!1,Vi=o.features?.scrollToBottom??{},vo=o.features?.scrollBehavior??{},$i=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Rb=`${$i()}event-stream`,Rr=null,ou=o.features?.eventStream?.maxEvents??2e3,Lt=null,wn=null,Yn=null,ru=!1,Ot=null,Sn=!1,Co=null,Ql=0,su=(r,a)=>{Lt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:r,timestamp:Date.now(),payload:JSON.stringify(a)})},Xl=(r,a)=>{wn?.processEvent(r,a),Lt?su(r,a):Yn&&(Yn.length>=ou&&Yn.shift(),Yn.push({type:r,payload:a}))},zi=()=>{Lt||!Jt||(Yn??=[],Hp().then(r=>{if(ru||Lt||!Jt)return;Rr=new r.EventStreamStore(Rb),Lt=new r.EventStreamBuffer(ou,Rr),wn=wn??new r.ThroughputTracker,Rr.open().then(()=>Lt?.restore()).catch(d=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",d)});let a=Yn??[];Yn=null;for(let d of a)wn?.processEvent(d.type,d.payload),su(d.type,d.payload)}).catch(()=>{}))};Jt&&zi();let Rs=!1,Ui=null,qi=()=>{},ji=()=>{},iu=()=>{},au=()=>{},Ki=()=>{},Wb=()=>Sn||Rs&&Ui==="panel",Wr={onCopy:r=>{G.emit("message:copy",r),S?.isClientTokenMode()&&S.submitMessageFeedback(r.id,"copy").catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",a)}),o.messageActions?.onCopy?.(r)},onFeedback:r=>{G.emit("message:feedback",r),S?.isClientTokenMode()&&S.submitMessageFeedback(r.messageId,r.type).catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",a)}),o.messageActions?.onFeedback?.(r)}},AA=o.statusIndicator??{},Jl=(r,a=o.statusIndicator??{})=>r==="idle"?a.idleText??gt.idle:r==="connecting"?a.connectingText??gt.connecting:r==="connected"?a.connectedText??gt.connected:r==="error"?a.errorText??gt.error:r==="paused"?a.pausedText??gt.paused:r==="resuming"?a.resumingText??gt.resuming:gt[r];function Ws(r,a,d,m){if(!Ae()&&(d.mode==="transient"||r.classList.contains("persona-mb-2"))&&(vd(r,Ut,d),ui(r,d,m)),!r.hasAttribute(Ts))if(m==="idle"&&d.idleLink){r.textContent="";let f=document.createElement("a");f.href=d.idleLink,f.target="_blank",f.rel="noopener noreferrer",f.textContent=a,f.style.color="inherit",f.style.textDecoration="none",r.appendChild(f)}else r.textContent=a}let Zt=Ry({config:o,showClose:Ve()}),{wrapper:Pe,panel:le,pillRoot:St}=Zt.shell,Re=Zt.panelElements,{container:re,body:j,messagesWrapper:ce,starterSuggestions:Zl,transcriptSuggestions:Bs,suggestions:wo,textarea:Z,sendButton:pe,composerForm:Ut,statusText:We,welcomeHost:xt,welcomeIconHolder:Bb,greetingHost:en,introKicker:Db,introTitle:Ob,introSubtitle:_b,closeButton:xe,iconHolder:at,headerTitle:So,headerSubtitle:Yo,header:Ke,footer:Le,actionsRow:Fb}=Re,ec=Re.leftActions,Gi=Re.rightActions,Hn=Re.sendButtonWrapper,lu=Re.setSendButtonMode,te=Re.micButton,tn=Re.micButtonWrapper,st=Re.attachmentButton,qt=Re.attachmentButtonWrapper,et=Re.attachmentInput,jt=Re.attachmentPreviewsContainer;re.classList.add("persona-relative"),j.classList.add("persona-relative");let Nb=12,Ds=()=>Vi.label??"",Vb=()=>Vi.iconName??"arrow-down",$b=()=>Vi.enabled!==!1,nn=()=>vo.mode??"anchor-top",xo=()=>nn()==="follow"||nn()==="anchor-top"&&Ys,Os=()=>vo.anchorTopOffset??16,zb=()=>vo.restorePosition??"bottom",cu=()=>vo.pauseOnInteraction===!0,du=()=>vo.showActivityWhilePinned!==!1,pu=()=>vo.announce===!0,tc=()=>vo.scrollbar??"on-scroll",ft=P("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");ft.type="button",ft.style.display="none",ft.setAttribute("data-persona-scroll-to-bottom","true");let _s=P("span","persona-flex persona-items-center"),nc=P("span",""),Qo=P("span","");Qo.setAttribute("data-persona-scroll-to-bottom-count",""),Qo.style.display="none",ft.append(_s,nc,Qo),re.appendChild(ft);let cn=P("div","persona-stream-anchor-spacer");cn.setAttribute("aria-hidden","true"),cn.setAttribute("data-persona-anchor-spacer",""),cn.style.flexShrink="0",cn.style.pointerEvents="none",cn.style.height="0px",cn.style.display="none",j.appendChild(cn);let Qn=P("div","persona-sr-only");Qn.setAttribute("aria-live","polite"),Qn.setAttribute("aria-atomic","true"),Qn.setAttribute("role","status"),Qn.setAttribute("data-persona-live-region",""),Object.assign(Qn.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"}),re.appendChild(Qn);let Fs=null,Yi=null,Ns=r=>{!pu()||!r||(Yi=r,Fs===null&&(Fs=setTimeout(()=>{Fs=null,Yi&&pu()&&(Qn.textContent=Yi),Yi=null},400)))},Vs=()=>{let r=t.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&r.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(de||rt(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!rt(o)},Xo=()=>Vl(o,Vs()),Qi="empty",Xi=0,oc=()=>Xi||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Jo=()=>{let a=Le.style.display==="none"?0:Le.offsetHeight;ft.style.bottom=`${a+oc()+Nb}px`};Jo();let rc=()=>{Fr||(Le.style.marginBottom=Xi>0?`${Xi}px`:"")},Ji=()=>{let r=sp(o,Ae()),a=Xo();t.setAttribute("data-persona-welcome-fullscreen",String(Vs())),t.setAttribute("data-persona-welcome-layout",a.layout??"top"),t.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom");let m=Le.style.display==="none"?0:Le.offsetHeight,f=a.anchor==="center"&&Qi==="empty"?ki(a.anchorComposerTop)??ki("44%"):null,b=f!==null&&a.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,D=b?getComputedStyle(j):null,$=parseFloat(t.style.getPropertyValue("--persona-composer-overlay-height"))||0,F=parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,q=Math.max(0,(parseFloat(D?.paddingBottom??"")||0)-(r==="overlay"?$+F:0)),K=b?j.getBoundingClientRect().top-re.getBoundingClientRect().top:0,X=!b||xt.hidden?0:(xt.querySelector("[data-persona-welcome-plugin]")??xt).offsetHeight,ae=f===null||Ae()?0:b?Math.max(0,Math.round((re.clientHeight-K-X-q-m)/2)):Jh({columnHeight:re.clientHeight,footerHeight:m,fraction:f});t.style.setProperty("--persona-composer-overlay-height",`${m}px`),t.style.setProperty("--persona-composer-lift",`${r==="overlay"?ae:0}px`),Xi=r==="block"?ae:0,rc(),Jo()},uu=()=>{let r=!!Ds();ft.setAttribute("aria-label",Ds()||"Jump to latest"),ft.title=Ds(),ft.setAttribute("data-persona-scroll-to-bottom-has-label",r?"true":"false"),_s.innerHTML="";let a=se(Vb(),"14px","currentColor",2);a?(_s.appendChild(a),_s.style.display=""):_s.style.display="none",nc.textContent=Ds(),nc.style.display=r?"":"none"};uu();let _e=null,lt=null,ie=gh(),Ub=r=>{try{re.dispatchEvent(new CustomEvent("persona:composer:state",{detail:r,bubbles:!0,composed:!0}))}catch{}};ie.subscribe(Ub);let Rn=()=>{ie.setText(Z?.value??"")},Zo=()=>{ie.setMentionRefs(lt?.getMentionRefs()??[])},qb=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}),gu=r=>{let a=Object.freeze(r.map(qb));ie.setAttachments(a);try{o.attachments?.onChange?.(a)}catch(d){console.error("[AgentWidget] attachments.onChange failed:",d)}Dc()};ie.setSelectedModelId(o.composer?.selectedModelId);let $s=()=>o.composer?.modes??[],Br=()=>Ph($s(),o.composer?.modeGroups);{let r=Ml(o.composer?.defaultActiveModeIds??[],$s());r.length&&ie.setActiveModeIds(r)}function mu(r){if(ie.getState().selectedModelId!==r){ie.setSelectedModelId(r),Ao?.repaint();try{o.composer?.onModelChange?.(r)}catch(a){console.error("[AgentWidget] composer.onModelChange failed:",a)}}}function Zi(r){ie.setActiveModeIds(r),Xn?.render(r,Br()),Dr.forEach(a=>a.repaint()),xn?.resolve(),Ea(),An()}function sc(r){Zi(Lh(ie.getState().activeModeIds,r,$s(),o.composer?.modeGroups))}let Ao=null,ic=null,Xn=null,Dr=new Map,Mo=null;function Wn(r){ie.setQuote(r),Mo?.render(ie.getState().quote),An(),sg()}let fu=!1;function ac(){let r=o.composer?.streamingSubmitBehavior??"block";return r!=="interrupt"?r:o.clientToken?"interrupt":(!fu&&o.debug===!0&&(fu=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Eo=null;function Or(r){ie.setPendingSubmission(r),Eo?.render(ie.getState().pendingSubmission),An()}let jb=r=>{let a=Dr.get(r);if(a)return a;let d=Rh({groupId:r,getGroup:()=>o.composer?.modeGroups?.find(m=>m.id===r),getModes:()=>$s().filter(m=>m.groupId===r),getActiveIds:()=>ie.getState().activeModeIds,onSelect:m=>sc(m)});return Dr.set(r,d),d},Kb=()=>{let r=[],a=ie.getState().activeModeIds,d=new Set;if($s().forEach((m,f)=>{if(Al(m.groupId,o.composer?.modeGroups)){let b=m.groupId;if(d.has(b))return;d.add(b);let D=jb(b);D.action.order=Jd(f),D.action.label=o.composer?.modeGroups?.find($=>$.id===b)?.label??b,r.push(D.action);return}r.push({id:Th(m.id),kind:"button",placement:"start",order:Jd(f),presentation:m.presentation??"auto",label:m.label,shortLabel:m.shortLabel,iconName:m.iconName,pressed:a.includes(m.id),onSelect:()=>sc(m.id)})}),o.composer?.models?.length&&!g.some(m=>m.renderComposer)){let m=o.composer?.modelPicker?.presentation??"native";(!Ao||ic!==m)&&(ic=m,Ao=Mh({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ie.getState().selectedModelId,onSelect:f=>mu(f),presentation:m,getSuffix:()=>o.composer?.modelPicker?.suffix})),r.push(Ao.action)}return r},lc=null,hu=g.find(r=>r.renderHeader);if(hu?.renderHeader){let r=hu.renderHeader({config:o,defaultRenderer:()=>{let a=kr({config:o,showClose:Ve()});return Ri(re,a,o),a.header},onClose:()=>Ge(!1,"user")});if(r){let a=Ke;a&&(a.replaceWith(r),Ke=r,Zt.header.element=r)}}let yu=()=>{Ot&&(j.style.display="none",Le.parentNode?.insertBefore(Ot.element,Le),Ot.update())},cc=()=>{if(!Lt){zi();return}if(Sn=!0,Ot?yu():Hp().then(a=>{Ot||!Sn||!Lt||(Ot=a.createEventStreamView({buffer:Lt,getFullHistory:()=>Lt.getAllFromStore(),onClose:()=>_r(),config:o,plugins:g,getThroughput:()=>wn?.getMetric()??{status:"idle"},renderIconByName:se}),yu())}).catch(()=>{_r()}),Ne){Ne.style.boxShadow=`inset 0 0 0 1.5px ${Vt.actionIconColor}`;let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(d=>d&&Ne.classList.add(d))}let r=()=>{if(!Sn)return;let a=Date.now();a-Ql>=200&&(Ot?.update(),Ql=a),Co=requestAnimationFrame(r)};Ql=0,Co=requestAnimationFrame(r),Ht(),G.emit("eventStream:opened",{timestamp:Date.now()})},_r=()=>{if(Sn){if(Sn=!1,Ot&&Ot.element.remove(),j.style.display="",Ne){Ne.style.boxShadow="";let r=o.features?.eventStream?.classNames?.toggleButtonActive;r&&r.split(/\s+/).forEach(a=>a&&Ne.classList.remove(a))}Co!==null&&(cancelAnimationFrame(Co),Co=null),Ht(),G.emit("eventStream:closed",{timestamp:Date.now()})}},Ne=null;if(Jt){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:"");Ne=P("button",a),Ne.style.width="28px",Ne.style.height="28px",Ne.style.color=Vt.actionIconColor,Ne.type="button",Ne.setAttribute("aria-label","Event Stream"),Ne.title="Event Stream";let d=yt(fb,"18px","currentColor",1.5);d&&Ne.appendChild(d);let m=Re.clearChatButtonWrapper,f=Re.closeButtonWrapper,b=m||f;b&&b.parentNode===Ke?Ke.insertBefore(Ne,b):Ke.appendChild(Ne),Ne.addEventListener("click",()=>{Sn?_r():cc()})}let bu=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=P("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 f=r.querySelector("[data-persona-composer-form]");f?.parentNode?f.parentNode.insertBefore(d,f):r.insertBefore(d,r.firstChild)}if(!(r.querySelector("[data-persona-composer-attachment-input]")??r.querySelector('input[type="file"]'))){let f=P("input");f.type="file",f.setAttribute("data-persona-composer-attachment-input",""),f.accept=(a.allowedTypes??us).join(","),f.multiple=(a.maxFiles??4)>1,f.style.display="none",f.setAttribute("aria-label",a.buttonTooltipText??"Attach files"),r.appendChild(f)}},Fr=!1,vu=r=>{let a=g.find(f=>f.renderComposer);if(!a?.renderComposer)return null;let d=o.composer,m=C?S.isStreaming():!1;return a.renderComposer({config:o,defaultRenderer:r,requestRender:()=>fm(),storage:E(a.id),onSubmit:f=>{!S||S.isStreaming()||Wa(f.trim(),{consumeDraft:!1})},streaming:m,disabled:m,openAttachmentPicker:()=>{_n()||et?.click()},models:d?.models,selectedModelId:ie.getState().selectedModelId??d?.selectedModelId,onModelChange:f=>mu(f),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{lc?.()}:void 0})},Cu=vu(()=>Wi({config:o}).footer);Cu&&(Zt.replaceComposer(Cu),Le=Zt.composer.footer,Fr=!0);let Be=null,Gb=r=>{Ut=r.form,Z=r.input,Hn=r.sendButton?r.sendButton.parentElement:null,r.sendButton&&(pe=r.sendButton),r.micButton&&(te=r.micButton,tn=r.micButton.parentElement),r.found.status&&(We=r.found.status),r.found.suggestions&&(wo=r.found.suggestions),r.attachmentButton&&(st=r.attachmentButton,qt=r.attachmentButton.parentElement),et=r.attachmentInput??null,jt=r.attachmentPreviews??null,r.found.actionsRow&&(Fb=r.found.actionsRow),ec=r.found.actionsStart,Gi=r.found.actionsEnd};function dc(){let r=Z;if(!r)return;let a=o.composer?.inputAttributes,d=!a?.ariaLabel&&!(r instanceof HTMLTextAreaElement)?r.getAttribute("aria-label"):null;mf(r,a),d&&r.setAttribute("aria-label",d),gf(r,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:kd(r)}),pf(r,df(o.composer?.maxLines,Ae()?5:3))}let wu=r=>{Be=fh(r,{debug:o.debug===!0}),Be&&Gb(Be),dc()};bu(Le),wu(Le),Rn();let zs=Ko(o,Ae());zs&&(ce.style.maxWidth=zs,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",en.style.maxWidth=zs,en.style.marginLeft="auto",en.style.marginRight="auto",en.style.width="100%",Zl.style.maxWidth=zs,Bs.style.maxWidth=zs,Bs.style.marginLeft="auto",Bs.style.marginRight="auto",Bs.style.width="100%");let Su=()=>{let r=Ko(o,Ae());if(!(!r||Ae()))for(let a of[Ut,wo,jt,We])a&&(a.style.maxWidth=r,a.style.marginLeft="auto",a.style.marginRight="auto",a.style.width="100%")};Su();let xu=()=>{!o.attachments?.enabled||!et||!jt||(_e?_e.remountPreviews(jt):(_e=xi.fromConfig(o.attachments,gu),_e.setPreviewsContainer(jt)),Be?.addListener(et,"change",r=>{let a=r.target;_e?.handleFileSelect(a.files),a.value=""}),re.querySelector(".persona-attachment-drop-overlay")||re.appendChild(Cb(o.attachments.dropOverlay)))};xu();let Yb=()=>lt?.prefetch(),pc=()=>{if(!o.contextMentions?.enabled||!Z)return;let r=Fd();if(!r){let m=Z;vl().then(()=>{lt||Z!==m||!m.isConnected||(pc(),xn?.resolve())},()=>{});return}let a=Be?.header??null,d=a?Ld(a):void 0;if(lt=r.createContextMentionOrchestrator({deps:{loadContextMentions:wf,loadContextMentionsInline:Sf,renderLucideIcon:se,createMentionButton:yf},config:o,textarea:Z,anchor:Ut??Z,getMessages:()=>S.getMessages(),liveRegionHost:re,chipRow:d}),lt&&!d){let m=Z;m.parentElement?.insertBefore(lt.contextRow,m)}};pc();let xn=null,Qb={getState:()=>ie.getState(),getValue:()=>Z?.value??"",setValue:r=>{Z&&(Z.value=r,Z.dispatchEvent(new Event("input",{bubbles:!0})),Rn())},submit:()=>{Cf(Be?.form??null)},openAttachmentPicker:()=>{_n()||et?.click()},toggleVoice:()=>{lc?.()},requestRender:()=>xn?.resolve()},Xb=()=>{let r=[];return(lt?.affordanceButtons??[]).forEach((d,m)=>{r.push({id:`core:mention-${m}`,placement:"start",order:Kn.mention+m,element:d,managed:!0})}),qt&&r.push({id:"core:attachment",placement:"start",order:Kn.attachment,element:qt}),tn&&r.push({id:"core:mic",placement:"end",order:Kn.mic,element:tn}),Hn&&r.push({id:"core:send",placement:"end",order:Kn.send,element:Hn}),r},Au=()=>{xn?.destroy(),xn=Sh({getBindings:()=>Be,collect:()=>({builtIns:Xb(),configActions:[...Kb(),...o.composer?.actions??[]],plugins:g,contributionContext:{config:o,getState:()=>ie.getState(),requestRender:()=>xn?.resolve()},debug:o.debug===!0}),actionContext:Qb,getState:()=>ie.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(r,a)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${a.actionId}" failed:`,r)}}),xn.resolve()};Au();let uc=()=>{if(Xn?.destroy(),Xn=null,!Br().length)return;let r=Be?.header;r&&(Xn=Eh({row:Ld(r),onRemove:a=>sc(a),initialIds:ie.getState().activeModeIds}),Xn.render(ie.getState().activeModeIds,Br()))};uc();let Mu=()=>{Mo?.destroy(),Mo=null,Eo?.destroy(),Eo=null;let r=Be?.header;r&&(Mo=Wh({onDismiss:()=>Wn(void 0)}),r.appendChild(Mo.element),Mo.render(ie.getState().quote),ac()==="defer-one"&&(Eo=Bh({onEdit:()=>Kv(),onRemove:()=>Or(void 0)}),r.appendChild(Eo.element),Eo.render(ie.getState().pendingSubmission)))};Mu();let gc=Vh(),Jb=()=>{let r=Be?.header?.querySelector(bf);if(r)return r.childElementCount>0;let a=ie.getState();return a.mentionRefs.length>0||Ml(a.activeModeIds,Br()).length>0};function An(){let r=ie.getState(),a=gc.observe($h(Z),r.text);Le.toggleAttribute("data-persona-composer-compact",Nh({text:r.text,wrapped:a,hasAttachments:r.attachments.length>0,hasChips:Jb(),hasQuote:r.quote!==void 0,hasPendingSubmission:r.pendingSubmission!==void 0}))}function Eu(){o.composer?.layout==="single-row"&&!Ae()?Le.setAttribute("data-persona-composer-layout","single-row"):Le.removeAttribute("data-persona-composer-layout")}Eu(),ie.subscribe(()=>{xn?.sync(),Dc(),xa(),An(),sg()}),xa();let Tu=!1,Zb=r=>{if(Tu||o.debug!==!0)return;let a=["messages","composer"].filter(d=>r[d]);a.length&&(Tu=!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??{};Zb(r);let a=m=>{switch(m){case"body-top":return j.querySelector("[data-persona-intro-card]");case"messages":return ce;case"footer-top":return wo;case"composer":return Ut;case"footer-bottom":return We;default:return null}},d=(m,f)=>{switch(m){case"header-left":case"header-center":case"header-right":if(m==="header-left")Ke.insertBefore(f,Ke.firstChild);else if(m==="header-right")Ke.appendChild(f);else{let b=Ke.querySelector(".persona-flex-col");b?b.parentNode?.insertBefore(f,b.nextSibling):Ke.appendChild(f)}break;case"body-top":{let b=j.querySelector("[data-persona-intro-card]");b?b.replaceWith(f):j.insertBefore(f,j.firstChild);break}case"body-bottom":j.appendChild(f);break;case"footer-top":wo.replaceWith(f);break;case"footer-bottom":We.replaceWith(f);break;default:break}};for(let[m,f]of Object.entries(r))if(f)try{let b=f({config:o,defaultContent:()=>a(m)});b&&d(m,b)}catch(b){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${m}":`,b)}})(),ce.addEventListener("click",r=>{let a=r.target;if(!(a instanceof Element))return;let d=a.closest("button[data-persona-copy-tool-detail]");d&&(r.preventDefault(),r.stopPropagation(),Oy(d))});let mc=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 f=m.getAttribute("data-message-id");if(!f)return;Io(),Kr();let b=d.getAttribute("data-bubble-type");if(m.classList.contains("persona-activity-row")){l.manual(f);let D=m.parentElement?.closest("[data-persona-tool-group]");D?.dataset.messageId&&l.manual(D.dataset.messageId)}if(b==="reasoning")i.has(f)?i.delete(f):i.add(f),Ep(f,m,i);else if(b==="tool")s.has(f)?s.delete(f):s.add(f),Lp(f,m,s,o);else if(b==="approval"&&A){let $=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",F=c.get(f)??$;c.set(f,!F),A.updateApprovalDetailsUI(f,m,o,c)}It.delete(f)};ce.addEventListener("pointerdown",r=>{r.target.closest('button[data-expand-header="true"]')&&(r.preventDefault(),mc(r))}),ce.addEventListener("click",r=>{r.detail===0&&r.target.closest(".persona-activity-row")&&mc(r)}),ce.addEventListener("keydown",r=>{let a=r.target;(r.key==="Enter"||r.key===" ")&&a.closest('button[data-expand-header="true"]')&&(r.preventDefault(),mc(r))}),ce.addEventListener("copy",r=>{let{clipboardData:a}=r;if(!a)return;let d=ce.getRootNode(),m=typeof d.getSelection=="function"?d.getSelection():window.getSelection();if(!m||m.isCollapsed)return;let f=m.toString(),b=Zh(f);!b||b===f||(a.setData("text/plain",b),r.preventDefault())});let fc=new Map,ku=null,Pu="idle",ev={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},tv=(r,a)=>{let{icon:d,label:m}=ev[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 f=se(d,14,"currentColor",2);f&&(r.innerHTML="",r.appendChild(f))},Lu=()=>{ce.querySelectorAll('[data-action="read-aloud"]').forEach(a=>{let m=a.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;tv(a,m&&m===ku?Pu:"idle")})};ce.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 f=m.getAttribute("data-actions-for");if(!f)return;let b=d.getAttribute("data-action");if(b==="copy"){let $=S.getMessages().find(F=>F.id===f);if($&&Wr.onCopy){let F=$.content||"";navigator.clipboard.writeText(F).then(()=>{d.classList.add("persona-message-action-success");let q=yt(hb,14,"currentColor",2);q&&(d.innerHTML="",d.appendChild(q)),setTimeout(()=>{d.classList.remove("persona-message-action-success");let K=yt(yb,14,"currentColor",2);K&&(d.innerHTML="",d.appendChild(K))},2e3)}).catch(q=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",q)}),Wr.onCopy($)}}else if(b==="read-aloud")S.toggleReadAloud(f);else if(b==="upvote"||b==="downvote"){let $=(fc.get(f)??null)===b,F=b==="upvote"?"thumbs-up":"thumbs-down";if($){fc.delete(f),d.classList.remove("persona-message-action-active");let q=se(F,14,"currentColor",2);q&&(d.innerHTML="",d.appendChild(q))}else{let q=b==="upvote"?"downvote":"upvote",K=m.querySelector(`[data-action="${q}"]`);if(K){K.classList.remove("persona-message-action-active");let De=se(q==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);De&&(K.innerHTML="",K.appendChild(De))}fc.set(f,b),d.classList.add("persona-message-action-active");let X=se(F,14,"currentColor",2);X&&(X.setAttribute("fill","currentColor"),d.innerHTML="",d.appendChild(X)),d.classList.remove("persona-message-action-pop"),d.offsetWidth,d.classList.add("persona-message-action-pop");let He=S.getMessages().find(Fe=>Fe.id===f);He&&Wr.onFeedback&&Wr.onFeedback({type:b,messageId:He.id,message:He})}}else if(b==="regenerate")ea?.regenerate(f);else if(b==="edit")ea?.edit(f);else if(b==="quote")ea?.quote(f);else if(b?.startsWith(Ol)){let D=b.slice(Ol.length),$=o.messageActions?.custom?.find(q=>q.id===D),F=S.getMessages().find(q=>q.id===f);if(!$||!F)return;try{$.onSelect(F)}catch(q){console.error(`[AgentWidget] messageActions.custom "${D}" onSelect failed:`,q)}}});let ea=null;ce.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 f=m.getAttribute("data-message-id");if(!f)return;let b=d.getAttribute("data-approval-action");if(!b)return;let D=b==="approve"?"approved":"denied",F=S.getMessages().find(K=>K.id===f);if(!F?.approval)return;let q=m.querySelector("[data-approval-buttons]");q&&q.querySelectorAll("button").forEach(X=>{X.disabled=!0,X.style.opacity="0.5",X.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?S.resolveWebMcpApproval(f,D):S.resolveApproval(F.approval,D)});let Ee=null,Iu=!1,Us=null,er=()=>{},qs="none",ta=null,dn={artifacts:[],selectedId:null},Jn=!1,Mn=!1,js=!1,Nr=!1,Hu=()=>Nr||dn.artifacts.some(r=>as(o.features?.artifacts,r)==="panel"),na=()=>dn.artifacts.length>0&&!Jn&&Hu(),pn={current:null},hc=(r,a)=>{let d=S.getArtifactById(a),m=d?.markdown,f=d?.title||"artifact",b=d?.file,D=d?.artifactType??"markdown";if(!m){let q=r.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(q){let X=S.getMessages().find(ae=>ae.id===q);if(X?.rawContent)try{let ae=JSON.parse(X.rawContent);m=ae?.props?.markdown,f=ae?.props?.title||f,ae?.props?.file&&typeof ae.props.file=="object"&&(b=ae.props.file),!d&&typeof ae?.props?.artifactType=="string"&&(D=ae.props.artifactType)}catch{}}}return{markdown:m,title:f,file:b,artifactType:D}};ce.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:b,title:D,file:$}=hc(d,m);if(!b)return;let F=yo();F&&F.triggerArtifactDownload(F.downloadInfoFor({title:D,markdown:b,file:$}))}),ce.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 f=d.closest("[data-artifact-inline]"),b=f?null:d.closest("[data-open-artifact]"),D=f?f.getAttribute("data-artifact-inline"):b?.getAttribute("data-open-artifact")??null,F=(f?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Fe=>Fe.id===m);if(!F)return;let{markdown:q,title:K,file:X,artifactType:ae}=hc(d,D??""),He={artifactId:D,title:K,artifactType:ae,markdown:q,file:X};try{Promise.resolve(F.onClick(He)).catch(()=>{})}catch{}}),ce.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 f=S.getArtifactById(m),b=yo();if(!b)return;let D="";if(f)D=b.artifactCopyText(f);else{let{markdown:$,file:F,artifactType:q}=hc(d,m);q==="markdown"&&(D=b.artifactCopyText({id:m,artifactType:"markdown",status:"complete",markdown:$??"",...F?{file:F}:{}}))}D&&navigator.clipboard.writeText(D).then(()=>{let $=yt(hb,16,"currentColor",2);$&&(d.replaceChildren($),setTimeout(()=>{let F=yt(yb,16,"currentColor",2);F&&d.replaceChildren(F)},1500))}).catch(()=>{})}),ce.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||(Jn=!1,Nr=!0,Mn=!0,js=!0,S.selectArtifact(m),En())}),ce.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(),Jn=!1,Nr=!0,S.selectArtifact(m),En())}),ce.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 Ks=Re.composerOverlay,yc=r=>{vl().catch(()=>{}),Zm(r,o,Ks)},Ru=null,nv={mount:t,overlay:Ks,sessionRef:pn,config:()=>o},oa=!1,Wu=r=>a=>{let d=a.target,m=d?.closest?.("[data-persona-ask-sheet-for]");if(!m||!(r==="click"?!!d?.closest("[data-ask-user-action]"):a.key==="Enter"&&!!d?.matches?.('[data-ask-free-text-input="true"]')))return;let b=$=>{Ru??=$.createAskUserSheetHandlers(nv),Ru[r](a)},D=Fd();if(D){b(D);return}oa||(oa=!0,vl().then($=>{oa=!1,m.isConnected&&b($)},()=>{oa=!1}))};Ks.addEventListener("click",Wu("click")),Ks.addEventListener("keydown",Wu("keydown"));let Bu=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=Ks.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),b=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];b&&(r.preventDefault(),b.click())};document.addEventListener("keydown",Bu);let Zn=null,ot=null,Gs=null,ra=null,sa=()=>{},Du=!1,ia="",aa="";function bc(){ra?.(),ra=null}let ov=()=>{let r=tt?.railShell?tt.railHost:null,a=r?.isConnected?r:null,d=a?a.getBoundingClientRect().width:0;return d<=0?200:d+360},Ou=()=>{if(!Zn||!ot)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){ot.style.removeProperty("position"),ot.style.removeProperty("left"),ot.style.removeProperty("top"),ot.style.removeProperty("bottom"),ot.style.removeProperty("width"),ot.style.removeProperty("z-index");return}let m=Zn.firstElementChild;if(!m||m===ot)return;let f=10;ot.style.position="absolute",ot.style.top="0",ot.style.bottom="0",ot.style.width=`${f}px`,ot.style.zIndex="5";let b=Fp(Zn,a),D=m.offsetWidth+b/2-f/2;ot.style.left=`${Math.max(0,D)}px`},la=()=>{},_u=()=>{let r=t.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,d=o.launcher?.mobileBreakpoint??640;return!a||r.innerWidth>d?!1:de||rt(o)},ca=()=>!zt(o)||!na()||t.classList.contains("persona-artifact-narrow-host")||_u()||(t.ownerDocument.defaultView??window).innerWidth<Qx?"none":Dp(o)?"detached":"welded",En=()=>{if(!Ee||!zt(o))return;Oi(t,o),_i(t,o),la();let r=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,a=le.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",a>0&&a<=r);let d=na();Ee.setVisible(d),Ee.update(dn),Jn?(Ee.setMobileOpen(!1),Ee.element.classList.add("persona-hidden"),Ee.backdrop?.classList.add("persona-hidden"),Mn=!1,js=!1):dn.artifacts.length>0&&Hu()?(Ee.element.classList.remove("persona-hidden"),Ee.setMobileOpen(!0)):(Ee.setMobileOpen(!1),Ee.element.classList.add("persona-hidden"),Ee.backdrop?.classList.add("persona-hidden"),Mn=!1,js=!1);let m=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ee.setExpandToggleVisible(m),Ee.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ee.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Ee.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ee.setTabFade(o.features?.artifacts?.layout?.tabFade),Ee.setRenderTabBar(o.features?.artifacts?.renderTabBar),!m&&!js&&(Mn=!1),Mn!==Du){let b=Ee.element;Mn?(ia=b.style.width,aa=b.style.maxWidth,b.style.removeProperty("width"),b.style.removeProperty("max-width")):(ia&&(b.style.width=ia),aa&&(b.style.maxWidth=aa),ia="",aa=""),Du=Mn}t.classList.toggle("persona-artifact-expanded",Mn),Ee.setExpanded(Mn);let f=ca();f!==qs&&(qs=f,er()),sa()};if(zt(o)){le.style.position="relative";let r=P("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),a=P("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");r.appendChild(re),Zn=a,a.appendChild(r),le.appendChild(a);let d=f=>{Iu||Ee||(Ee=f.createArtifactPane(o,{onSelect:b=>pn.current?.selectArtifact(b),onDismiss:()=>{Jn=!0,En()},onToggleExpand:()=>{let b=!Mn,D=dn.selectedId??dn.artifacts[dn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:D,expanded:b})!==!0&&(Mn=b,b||(js=!1),En())}}),Ee.element.classList.add("persona-hidden"),a.appendChild(Ee.element),Ee.backdrop&&le.appendChild(Ee.backdrop),sa(),En())},m=yo();m?d(m):(Wp(()=>{let f=yo();f&&d(f)}),zl().catch(()=>{})),sa=()=>{if(!Zn||!Ee)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Gs?.(),Gs=null,bc(),ot&&(ot.remove(),ot=null),Ee.element.style.removeProperty("width"),Ee.element.style.removeProperty("maxWidth");return}if(!ot){let b=P("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");b.setAttribute("role","separator"),b.setAttribute("aria-orientation","vertical"),b.setAttribute("aria-label","Resize artifacts panel"),b.tabIndex=0;let D=t.ownerDocument,$=D.defaultView??window,F=q=>{if(!Ee||q.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||$.innerWidth<=640)return;q.preventDefault(),bc();let K=q.clientX,X=Ee.element.getBoundingClientRect().width,ae=o.features?.artifacts?.layout,He=De=>{let Gt=Zn.getBoundingClientRect().width,nt=t.classList.contains("persona-artifact-welded-split"),it=Fp(Zn,$),Ft=nt?0:b.getBoundingClientRect().width||6,pt=X-(De.clientX-K),ze=Qy(pt,Gt,it,Ft,ae?.resizableMinWidth,ae?.resizableMaxWidth,ov());Ee.element.style.width=`${ze}px`,Ee.element.style.maxWidth="none",Ou()},Fe=()=>{D.removeEventListener("pointermove",He),D.removeEventListener("pointerup",Fe),D.removeEventListener("pointercancel",Fe),ra=null;try{b.releasePointerCapture(q.pointerId)}catch{}};ra=Fe,D.addEventListener("pointermove",He),D.addEventListener("pointerup",Fe),D.addEventListener("pointercancel",Fe);try{b.setPointerCapture(q.pointerId)}catch{}};b.addEventListener("pointerdown",F),ot=b,Zn.insertBefore(b,Ee.element),Gs=()=>{b.removeEventListener("pointerdown",F)}}if(ot){let b=na();ot.classList.toggle("persona-hidden",!b),Ou()}},la=()=>{if(!de||!Ee||(o.launcher?.sidebarMode??!1)||rt(o)&&Cn(o).reveal==="emerge")return;let b=t.ownerDocument.defaultView??window,D=o.launcher?.mobileFullscreen??!0,$=o.launcher?.mobileBreakpoint??640;if(D&&b.innerWidth<=$||!Uy(o,de))return;let F=Pr(o).width,q=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";na()?(le.style.width=q,le.style.maxWidth=q):(le.style.width=F,le.style.maxWidth=F)},typeof ResizeObserver<"u"&&(Us=new ResizeObserver(()=>{En()}),Us.observe(le))}else le.appendChild(re);Ae()&&St&&(Re.peekBanner&&St.appendChild(Re.peekBanner),St.appendChild(Le)),t.appendChild(Pe),St&&t.appendChild(St);let vc=()=>{let r=_u()||Ae()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!rt(o);if(ce.style.gap=r?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",ce.style.setProperty("--persona-transcript-gap",ce.style.gap),Ae()){le.style.width="100%",le.style.maxWidth="100%";let ge=o.launcher?.composerBar??{},we=Pe.dataset.state==="expanded",be=ge.expandedSize??"anchored";if(!(we&&be!=="fullscreen")){re.style.background="",re.style.border="",re.style.borderRadius="",re.style.overflow="",re.style.boxShadow="";return}let ht=o.theme?.components?.panel,Yt=ho(o),co=(po,wr)=>po==null||po===""?wr:Pt(Yt,po)??po,yd="1px solid var(--persona-border)",Cr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",bd="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";re.style.background="var(--persona-surface, #ffffff)",re.style.border=co(ht?.border,yd),re.style.borderRadius=co(ht?.borderRadius,bd),re.style.boxShadow=co(ht?.shadow,Cr),re.style.overflow="hidden";return}let a=rt(o),d=o.launcher?.sidebarMode??!1,m=a||d||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,b=o.launcher?.detachedPanel===!0,D=o.theme?.components?.panel,$=o.darkTheme?.components?.panel,F=Ei(o)==="dark"?Sr(D??{},$??{}):D,q=ho(o),K=(ge,we)=>ge==null||ge===""?we:Pt(q,ge)??ge,X=t.ownerDocument.defaultView??window,ae=o.launcher?.mobileFullscreen??!0,He=o.launcher?.mobileBreakpoint??640,Fe=X.innerWidth<=He,De=ae&&Fe&&de,Gt=a&&ae&&Fe,nt=o.launcher?.position??"bottom-left",it=nt==="bottom-left"||nt==="top-left",Ft=o.launcher?.zIndex??Dt,pt=(ge,we,be)=>`var(--persona-components-panel-modes-${ge}-${we}, ${be})`,ze=F?.modes?.floating,Vn=K(ze?.border??F?.border,pt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),$n=K(ze?.shadow??F?.shadow,pt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),hn=K(ze?.borderRadius??F?.borderRadius,pt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),yn=b&&!De&&!Gt,Fo=De||Gt?"mobile":yn?"floating":a?"docked":d?"sidebar":f?"inline":"floating",zn=F?.modes?.[Fo];yn?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let kn=yn?Vn:d||De?"none":Vn,No=yn?$n:De?"none":d?it?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":f?"none":$n;a&&!De&&!yn&&(No="none",kn="none");let pi=yn?hn:d||De?"0":hn,vr=K(zn?.border??F?.border,pt(Fo,"border",kn)),M=K(zn?.shadow??F?.shadow,pt(Fo,"shadow",No)),me=K(zn?.borderRadius??F?.borderRadius,pt(Fo,"borderRadius",pi)),fe=ca(),U=fe==="detached",Ue=fe==="welded";t.classList.toggle("persona-artifact-detached-split",U),t.classList.toggle("persona-artifact-welded-split",Ue);let mt="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)))))",Ye=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&zt(o)&&Dp(o)&&f&&!a;t.classList.toggle("persona-artifact-chat-flush",Ye);let ut=U||Ye?"none":M,Ct=U?Vn:Ue?"none":vr,ue=U?hn:me;Ye&&(Ct="none",ue="0");let Qe=zn?.borderRadius!=null&&zn.borderRadius!==""||F?.borderRadius!=null&&F.borderRadius!=="",ye=Ye&&!Qe?"0":me,wt=j.scrollTop;t.style.cssText="",Pe.style.cssText="",le.style.cssText="",re.style.cssText="",j.style.cssText="",Fr||(Le.style.cssText=""),Sn&&(j.style.display="none"),(m||f)&&(t.style.minWidth="0");let bn=()=>{if(wt<=0)return;(j.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(j.scrollTop===wt)return;let we=j.scrollHeight-j.clientHeight;we<=0||(j.scrollTop=Math.min(wt,we))})};if(De){Pe.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"),Pe.style.cssText=`
30
+ `,J.addEventListener("click",()=>{y=V,L.forEach((_,Q)=>{let G=Q<V;_.classList.toggle("selected",G),_.setAttribute("aria-checked",Q===V-1?"true":"false")})}),L.push(J),I.appendChild(J)}h.appendChild(I);let k=null;if(u){let V=document.createElement("div");V.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=i,k.rows=3,k.setAttribute("aria-label","Additional comments"),V.appendChild(k),h.appendChild(V)}let R=document.createElement("div");R.className="persona-feedback-actions";let B=document.createElement("button");B.type="button",B.className="persona-feedback-btn persona-feedback-btn-skip",B.textContent=c,B.addEventListener("click",()=>{n?.(),g.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=l,O.addEventListener("click",async()=>{if(y===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let V=k?.value.trim()||void 0;await e(y,V),g.remove()}catch(V){O.disabled=!1,O.textContent=l,console.error("[CSAT Feedback] Failed to submit:",V)}}),R.appendChild(B),R.appendChild(O),h.appendChild(R),g.appendChild(h),g}function yb(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:u=!0,lowLabel:p="Not likely",highLabel:g="Very likely"}=t,y=document.createElement("div");y.className="persona-feedback-container persona-feedback-nps",y.setAttribute("role","dialog"),y.setAttribute("aria-label","Net Promoter Score feedback");let h=null,C=document.createElement("div");C.className="persona-feedback-content";let E=document.createElement("div");E.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=o,E.appendChild(A);let I=document.createElement("p");I.className="persona-feedback-subtitle",I.textContent=s,E.appendChild(I),C.appendChild(E);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=p;let B=document.createElement("span");B.className="persona-feedback-label-high",B.textContent=g,k.appendChild(R),k.appendChild(B);let O=document.createElement("div");O.className="persona-feedback-numbers";let V=[];for(let w=0;w<=10;w++){let v=document.createElement("button");v.type="button",v.className="persona-feedback-rating-btn persona-feedback-number-btn",v.setAttribute("role","radio"),v.setAttribute("aria-checked","false"),v.setAttribute("aria-label",`Rating ${w} out of 10`),v.textContent=String(w),v.dataset.rating=String(w),w<=6?v.classList.add("persona-feedback-detractor"):w<=8?v.classList.add("persona-feedback-passive"):v.classList.add("persona-feedback-promoter"),v.addEventListener("click",()=>{h=w,V.forEach((T,S)=>{T.classList.toggle("selected",S===w),T.setAttribute("aria-checked",S===w?"true":"false")})}),V.push(v),O.appendChild(v)}L.appendChild(k),L.appendChild(O),C.appendChild(L);let J=null;if(u){let w=document.createElement("div");w.className="persona-feedback-comment-container",J=document.createElement("textarea"),J.className="persona-feedback-comment",J.placeholder=i,J.rows=3,J.setAttribute("aria-label","Additional comments"),w.appendChild(J),C.appendChild(w)}let _=document.createElement("div");_.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=c,Q.addEventListener("click",()=>{n?.(),y.remove()});let G=document.createElement("button");return G.type="button",G.className="persona-feedback-btn persona-feedback-btn-submit",G.textContent=l,G.addEventListener("click",async()=>{if(h===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}G.disabled=!0,G.textContent="Submitting...";try{let w=J?.value.trim()||void 0;await e(h,w),y.remove()}catch(w){G.disabled=!1,G.textContent=l,console.error("[NPS Feedback] Failed to submit:",w)}}),_.appendChild(Q),_.appendChild(G),C.appendChild(_),y.appendChild(C),y}var Es="persona-chat-history",Jx=30*1e3,Zx="Tap the mic to resume your voice call",eA=641,Ts="data-persona-composer-reason",Ni="data-persona-composer-notice",tA={"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 nA(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=tA[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 Yl(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 oA(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 rA(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Gp=t=>!t||typeof t!="object"?{}:{...t},wb=t=>t.map(e=>({...e,streaming:!1})),Sb=(t,e,n)=>{let o=t?.markdown?Vm(t.markdown):null,s=$m(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 u=c.text??"",p=c.message.rawContent??null;if(e){let h=e.process({text:u,raw:p??u,message:c.message,streaming:c.streaming});h!==null&&(u=h.text,h.persist||(c.message.__skipPersist=!0),h.resubmit&&!c.streaming&&n&&n())}let g=is()!==null,y;if(t?.postprocessMessage){let h=t.postprocessMessage({...c,text:u,raw:p??c.text??""});y=s?s(h):h}else if(o){let h=c.streaming?Kf(u):u,C=o(h);y=s&&g?s(C):C}else y=Ga(u);return y};return c=>{try{return l(c)}catch(u){return i||(i=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",u)),Ga(c.text??"")}}};function xb(t){let e=P("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=se(n,o,s,i);if(l&&e.appendChild(l),t?.label){let c=P("span","persona-drop-overlay-label");c.textContent=t.label,e.appendChild(c)}return e}var sA=(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},iA=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:sA(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Ab=(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=ja(e),s=new Set,i=new Set,l=Nf((r,a)=>{It.delete(r);let d=Array.from(ce.querySelectorAll("[data-message-id]")).find(m=>m.dataset.messageId===r);d&&(a==="tool"?Hp(r,d,s,o):kp(r,d,i))}),c=new Map,u=()=>{df({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};u();let p=o.features;o=Np(o);let g=zp.getForInstance(o.plugins),y=kf(t),h=[],C=!1,E=Oy(()=>o),A=null,I=null,L=null,k=!1,R=null,B=r=>{A=r,r.initApprovalUi({webMcpToolTitle:Ya});let a=r.createBuiltInApprovalPlugin(c);I=a.plugin,L=a.teardown},O=()=>{if(A)return A;let r=zy();return r?(B(r),r):($y().then(a=>{k||A||(B(a),R?.())}).catch(()=>{}),null)},V=!1,J=!1,_=null,Q=(r,a,d,m)=>{if(!r.querySelector("[data-tv-form]"))return;let f=tb();if(f){f.enhanceWithForms(r,a,d,m);return}eb().then(()=>{V||J||!_||(J=!0,_())}).catch(()=>{})};o.components&&go.registerAll(o.components);let G=sb(),v=o.persistState===!1?null:o.storageAdapter??ab(),T=!!o.clientToken&&typeof o.reconnectStream!="function",S={},z=null,W,ee=new Promise(r=>{W=r}),ne=()=>{},he=new Promise(r=>{ne=r}),ve,Xe=!1,Je=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&&(Xe=!0),d}return a}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}return r};if(v?.load)try{let r=v.load();if(r&&typeof r.then=="function")z=r.then(a=>Je(a??{messages:[],metadata:{}}));else{let d=Je(r??{messages:[],metadata:{}});d.metadata&&(S=Gp(d.metadata)),d.messages?.length&&(o={...o,initialMessages:d.messages}),d.artifacts?.length&&(o={...o,initialArtifacts:d.artifacts,initialSelectedArtifactId:d.selectedArtifactId??null}),ve=d.draft}}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",r)}else if(o.onStateLoaded)try{let r=Je({messages:[],metadata:{}});r.messages?.length&&(o={...o,initialMessages:r.messages})}catch(r){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",r)}z||W();let Wt=()=>S,$e=r=>{S=r({...S})??{},Ur()},Ce=o.actionParsers&&o.actionParsers.length?o.actionParsers:[qp],H=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Fi.message,Fi.messageAndClick],Ee=jp({parsers:Ce,handlers:H,getSessionMetadata:Wt,updateSessionMetadata:$e,emit:G.emit,documentRef:typeof document<"u"?document:null});Ee.syncFromMetadata();let de=o.launcher?.enabled??!0,In=o.launcher?.autoExpand??!1,Ps=o.autoFocusInput??!1,tu=In,nu=de,ou=o.layout?.header?.layout,Xl=!1,Me=()=>Ii(o),Ve=()=>de||Me(),xe=Me()?!1:de?In:!0,Ls=!1,Hr=null,ru=()=>{Ls=!0,Hr&&clearTimeout(Hr),Hr=setTimeout(()=>{Ls&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Ls=!1)},1e4)},Jt=Sb(o,Ee,ru),Is=o.features?.showReasoning??!0,Hs=o.features?.showToolCalls??!0,Zt=o.features?.showEventStreamToggle??!1,$i=o.features?.scrollToBottom??{},vo=o.features?.scrollBehavior??{},zi=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Db=`${zi()}event-stream`,Rr=null,su=o.features?.eventStream?.maxEvents??2e3,Lt=null,Sn=null,Yn=null,iu=!1,_t=null,xn=!1,Co=null,Jl=0,au=(r,a)=>{Lt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:r,timestamp:Date.now(),payload:JSON.stringify(a)})},Zl=(r,a)=>{Sn?.processEvent(r,a),Lt?au(r,a):Yn&&(Yn.length>=su&&Yn.shift(),Yn.push({type:r,payload:a}))},Ui=()=>{Lt||!Zt||(Yn??=[],Wp().then(r=>{if(iu||Lt||!Zt)return;Rr=new r.EventStreamStore(Db),Lt=new r.EventStreamBuffer(su,Rr),Sn=Sn??new r.ThroughputTracker,Rr.open().then(()=>Lt?.restore()).catch(d=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",d)});let a=Yn??[];Yn=null;for(let d of a)Sn?.processEvent(d.type,d.payload),au(d.type,d.payload)}).catch(()=>{}))};Zt&&Ui();let Rs=!1,qi=null,ji=()=>{},Ki=()=>{},lu=()=>{},cu=()=>{},Gi=()=>{},Ob=()=>xn||Rs&&qi==="panel",Wr={onCopy:r=>{G.emit("message:copy",r),x?.isClientTokenMode()&&x.submitMessageFeedback(r.id,"copy").catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",a)}),o.messageActions?.onCopy?.(r)},onFeedback:r=>{G.emit("message:feedback",r),x?.isClientTokenMode()&&x.submitMessageFeedback(r.messageId,r.type).catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",a)}),o.messageActions?.onFeedback?.(r)}},kA=o.statusIndicator??{},ec=(r,a=o.statusIndicator??{})=>r==="idle"?a.idleText??gt.idle:r==="connecting"?a.connectingText??gt.connecting:r==="connected"?a.connectedText??gt.connected:r==="error"?a.errorText??gt.error:r==="paused"?a.pausedText??gt.paused:r==="resuming"?a.resumingText??gt.resuming:gt[r];function Ws(r,a,d,m){if(!Me()&&(d.mode==="transient"||r.classList.contains("persona-mb-2"))&&(wd(r,Ut,d),ui(r,d,m)),!(r.hasAttribute(Ts)||r.hasAttribute(Ni)))if(m==="idle"&&d.idleLink){r.textContent="";let f=document.createElement("a");f.href=d.idleLink,f.target="_blank",f.rel="noopener noreferrer",f.textContent=a,f.style.color="inherit",f.style.textDecoration="none",r.appendChild(f)}else r.textContent=a}let en=Dy({config:o,showClose:Ve()}),{wrapper:Le,panel:le,pillRoot:St}=en.shell,We=en.panelElements,{container:re,body:j,messagesWrapper:ce,starterSuggestions:tc,transcriptSuggestions:Bs,suggestions:wo,textarea:Z,sendButton:pe,composerForm:Ut,statusText:Re,welcomeHost:xt,welcomeIconHolder:_b,greetingHost:tn,introKicker:Fb,introTitle:Nb,introSubtitle:Vb,closeButton:Ae,iconHolder:at,headerTitle:So,headerSubtitle:Yo,header:Ke,footer:Ie,actionsRow:$b}=We,nc=We.leftActions,Yi=We.rightActions,Hn=We.sendButtonWrapper,du=We.setSendButtonMode,te=We.micButton,nn=We.micButtonWrapper,st=We.attachmentButton,qt=We.attachmentButtonWrapper,et=We.attachmentInput,jt=We.attachmentPreviewsContainer;re.classList.add("persona-relative"),j.classList.add("persona-relative");let zb=12,Ds=()=>$i.label??"",Ub=()=>$i.iconName??"arrow-down",qb=()=>$i.enabled!==!1,on=()=>vo.mode??"anchor-top",xo=()=>on()==="follow"||on()==="anchor-top"&&Ys,Os=()=>vo.anchorTopOffset??16,jb=()=>vo.restorePosition??"bottom",pu=()=>vo.pauseOnInteraction===!0,uu=()=>vo.showActivityWhilePinned!==!1,gu=()=>vo.announce===!0,oc=()=>vo.scrollbar??"on-scroll",ft=P("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");ft.type="button",ft.style.display="none",ft.setAttribute("data-persona-scroll-to-bottom","true");let _s=P("span","persona-flex persona-items-center"),rc=P("span",""),Qo=P("span","");Qo.setAttribute("data-persona-scroll-to-bottom-count",""),Qo.style.display="none",ft.append(_s,rc,Qo),re.appendChild(ft);let dn=P("div","persona-stream-anchor-spacer");dn.setAttribute("aria-hidden","true"),dn.setAttribute("data-persona-anchor-spacer",""),dn.style.flexShrink="0",dn.style.pointerEvents="none",dn.style.height="0px",dn.style.display="none",j.appendChild(dn);let Qn=P("div","persona-sr-only");Qn.setAttribute("aria-live","polite"),Qn.setAttribute("aria-atomic","true"),Qn.setAttribute("role","status"),Qn.setAttribute("data-persona-live-region",""),Object.assign(Qn.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"}),re.appendChild(Qn);let Fs=null,Qi=null,Ns=r=>{!gu()||!r||(Qi=r,Fs===null&&(Fs=setTimeout(()=>{Fs=null,Qi&&gu()&&(Qn.textContent=Qi),Qi=null},400)))},Vs=()=>{let r=t.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&r.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(de||rt(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!rt(o)},Xo=()=>zl(o,Vs()),Xi="empty",Ji=0,sc=()=>Ji||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Jo=()=>{let a=Ie.style.display==="none"?0:Ie.offsetHeight;ft.style.bottom=`${a+sc()+zb}px`};Jo();let ic=()=>{Fr||(Ie.style.marginBottom=Ji>0?`${Ji}px`:"")},Zi=()=>{let r=ap(o,Me()),a=Xo();t.setAttribute("data-persona-welcome-fullscreen",String(Vs())),t.setAttribute("data-persona-welcome-layout",a.layout??"top"),t.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom");let m=Ie.style.display==="none"?0:Ie.offsetHeight,f=a.anchor==="center"&&Xi==="empty"?ki(a.anchorComposerTop)??ki("44%"):null,b=f!==null&&a.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,D=b?getComputedStyle(j):null,$=parseFloat(t.style.getPropertyValue("--persona-composer-overlay-height"))||0,F=parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,q=Math.max(0,(parseFloat(D?.paddingBottom??"")||0)-(r==="overlay"?$+F:0)),K=b?j.getBoundingClientRect().top-re.getBoundingClientRect().top:0,X=!b||xt.hidden?0:(xt.querySelector("[data-persona-welcome-plugin]")??xt).offsetHeight,ae=f===null||Me()?0:b?Math.max(0,Math.round((re.clientHeight-K-X-q-m)/2)):ty({columnHeight:re.clientHeight,footerHeight:m,fraction:f});t.style.setProperty("--persona-composer-overlay-height",`${m}px`),t.style.setProperty("--persona-composer-lift",`${r==="overlay"?ae:0}px`),Ji=r==="block"?ae:0,ic(),Jo()},mu=()=>{let r=!!Ds();ft.setAttribute("aria-label",Ds()||"Jump to latest"),ft.title=Ds(),ft.setAttribute("data-persona-scroll-to-bottom-has-label",r?"true":"false"),_s.innerHTML="";let a=se(Ub(),"14px","currentColor",2);a?(_s.appendChild(a),_s.style.display=""):_s.style.display="none",rc.textContent=Ds(),rc.style.display=r?"":"none"};mu();let _e=null,lt=null,ie=hh(),Kb=r=>{try{re.dispatchEvent(new CustomEvent("persona:composer:state",{detail:r,bubbles:!0,composed:!0}))}catch{}};ie.subscribe(Kb);let Rn=()=>{ie.setText(Z?.value??"")},Zo=()=>{ie.setMentionRefs(lt?.getMentionRefs()??[])},Gb=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}),fu=r=>{let a=Object.freeze(r.map(Gb));ie.setAttachments(a);try{o.attachments?.onChange?.(a)}catch(d){console.error("[AgentWidget] attachments.onChange failed:",d)}Fc()};ie.setSelectedModelId(o.composer?.selectedModelId);let $s=()=>o.composer?.modes??[],Br=()=>Hh($s(),o.composer?.modeGroups);{let r=Tl(o.composer?.defaultActiveModeIds??[],$s());r.length&&ie.setActiveModeIds(r)}function hu(r){if(ie.getState().selectedModelId!==r){ie.setSelectedModelId(r),Ao?.repaint();try{o.composer?.onModelChange?.(r)}catch(a){console.error("[AgentWidget] composer.onModelChange failed:",a)}}}function ea(r){ie.setActiveModeIds(r),Xn?.render(r,Br()),Dr.forEach(a=>a.repaint()),An?.resolve(),Ta(),Mn()}function ac(r){ea(Rh(ie.getState().activeModeIds,r,$s(),o.composer?.modeGroups))}let Ao=null,lc=null,Xn=null,Dr=new Map,Mo=null;function Wn(r){ie.setQuote(r),Mo?.render(ie.getState().quote),Mn(),cg()}let yu=!1;function cc(){let r=o.composer?.streamingSubmitBehavior??"block";return r!=="interrupt"?r:o.clientToken?"interrupt":(!yu&&o.debug===!0&&(yu=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Eo=null;function Or(r){ie.setPendingSubmission(r),Eo?.render(ie.getState().pendingSubmission),Mn()}let Yb=r=>{let a=Dr.get(r);if(a)return a;let d=Dh({groupId:r,getGroup:()=>o.composer?.modeGroups?.find(m=>m.id===r),getModes:()=>$s().filter(m=>m.groupId===r),getActiveIds:()=>ie.getState().activeModeIds,onSelect:m=>ac(m)});return Dr.set(r,d),d},Qb=()=>{let r=[],a=ie.getState().activeModeIds,d=new Set;if($s().forEach((m,f)=>{if(El(m.groupId,o.composer?.modeGroups)){let b=m.groupId;if(d.has(b))return;d.add(b);let D=Yb(b);D.action.order=ep(f),D.action.label=o.composer?.modeGroups?.find($=>$.id===b)?.label??b,r.push(D.action);return}r.push({id:Lh(m.id),kind:"button",placement:"start",order:ep(f),presentation:m.presentation??"auto",label:m.label,shortLabel:m.shortLabel,iconName:m.iconName,pressed:a.includes(m.id),onSelect:()=>ac(m.id)})}),o.composer?.models?.length&&!g.some(m=>m.renderComposer)){let m=o.composer?.modelPicker?.presentation??"native";(!Ao||lc!==m)&&(lc=m,Ao=kh({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ie.getState().selectedModelId,onSelect:f=>hu(f),presentation:m,getSuffix:()=>o.composer?.modelPicker?.suffix})),r.push(Ao.action)}return r},dc=null,bu=g.find(r=>r.renderHeader);if(bu?.renderHeader){let r=bu.renderHeader({config:o,defaultRenderer:()=>{let a=kr({config:o,showClose:Ve()});return Ri(re,a,o),a.header},onClose:()=>Ge(!1,"user")});if(r){let a=Ke;a&&(a.replaceWith(r),Ke=r,en.header.element=r)}}let vu=()=>{_t&&(j.style.display="none",Ie.parentNode?.insertBefore(_t.element,Ie),_t.update())},pc=()=>{if(!Lt){Ui();return}if(xn=!0,_t?vu():Wp().then(a=>{_t||!xn||!Lt||(_t=a.createEventStreamView({buffer:Lt,getFullHistory:()=>Lt.getAllFromStore(),onClose:()=>_r(),config:o,plugins:g,getThroughput:()=>Sn?.getMetric()??{status:"idle"},renderIconByName:se}),vu())}).catch(()=>{_r()}),Ne){Ne.style.boxShadow=`inset 0 0 0 1.5px ${Vt.actionIconColor}`;let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(d=>d&&Ne.classList.add(d))}let r=()=>{if(!xn)return;let a=Date.now();a-Jl>=200&&(_t?.update(),Jl=a),Co=requestAnimationFrame(r)};Jl=0,Co=requestAnimationFrame(r),Ht(),G.emit("eventStream:opened",{timestamp:Date.now()})},_r=()=>{if(xn){if(xn=!1,_t&&_t.element.remove(),j.style.display="",Ne){Ne.style.boxShadow="";let r=o.features?.eventStream?.classNames?.toggleButtonActive;r&&r.split(/\s+/).forEach(a=>a&&Ne.classList.remove(a))}Co!==null&&(cancelAnimationFrame(Co),Co=null),Ht(),G.emit("eventStream:closed",{timestamp:Date.now()})}},Ne=null;if(Zt){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:"");Ne=P("button",a),Ne.style.width="28px",Ne.style.height="28px",Ne.style.color=Vt.actionIconColor,Ne.type="button",Ne.setAttribute("aria-label","Event Stream"),Ne.title="Event Stream";let d=yt(bb,"18px","currentColor",1.5);d&&Ne.appendChild(d);let m=We.clearChatButtonWrapper,f=We.closeButtonWrapper,b=m||f;b&&b.parentNode===Ke?Ke.insertBefore(Ne,b):Ke.appendChild(Ne),Ne.addEventListener("click",()=>{xn?_r():pc()})}let Cu=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=P("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 f=r.querySelector("[data-persona-composer-form]");f?.parentNode?f.parentNode.insertBefore(d,f):r.insertBefore(d,r.firstChild)}if(!(r.querySelector("[data-persona-composer-attachment-input]")??r.querySelector('input[type="file"]'))){let f=P("input");f.type="file",f.setAttribute("data-persona-composer-attachment-input",""),f.accept=(a.allowedTypes??us).join(","),f.multiple=(a.maxFiles??4)>1,f.style.display="none",f.setAttribute("aria-label",a.buttonTooltipText??"Attach files"),r.appendChild(f)}},Fr=!1,wu=r=>{let a=g.find(f=>f.renderComposer);if(!a?.renderComposer)return null;let d=o.composer,m=C?x.isStreaming():!1;return a.renderComposer({config:o,defaultRenderer:r,requestRender:()=>bm(),storage:E(a.id),onSubmit:f=>{!x||x.isStreaming()||Da(f.trim(),{consumeDraft:!1})},streaming:m,disabled:m,openAttachmentPicker:()=>{_n()||et?.click()},models:d?.models,selectedModelId:ie.getState().selectedModelId??d?.selectedModelId,onModelChange:f=>hu(f),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{dc?.()}:void 0})},Su=wu(()=>Wi({config:o}).footer);Su&&(en.replaceComposer(Su),Ie=en.composer.footer,Fr=!0);let Be=null,Xb=r=>{Ut=r.form,Z=r.input,Hn=r.sendButton?r.sendButton.parentElement:null,r.sendButton&&(pe=r.sendButton),r.micButton&&(te=r.micButton,nn=r.micButton.parentElement),r.found.status&&(Re=r.found.status),r.found.suggestions&&(wo=r.found.suggestions),r.attachmentButton&&(st=r.attachmentButton,qt=r.attachmentButton.parentElement),et=r.attachmentInput??null,jt=r.attachmentPreviews??null,r.found.actionsRow&&($b=r.found.actionsRow),nc=r.found.actionsStart,Yi=r.found.actionsEnd};function uc(){let r=Z;if(!r)return;let a=o.composer?.inputAttributes,d=!a?.ariaLabel&&!(r instanceof HTMLTextAreaElement)?r.getAttribute("aria-label"):null;yf(r,a),d&&r.setAttribute("aria-label",d),hf(r,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Ld(r)}),mf(r,gf(o.composer?.maxLines,Me()?5:3))}let xu=r=>{Be=bh(r,{debug:o.debug===!0}),Be&&Xb(Be),uc()};Cu(Ie),xu(Ie),Rn();let zs=Ko(o,Me());zs&&(ce.style.maxWidth=zs,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",tn.style.maxWidth=zs,tn.style.marginLeft="auto",tn.style.marginRight="auto",tn.style.width="100%",tc.style.maxWidth=zs,Bs.style.maxWidth=zs,Bs.style.marginLeft="auto",Bs.style.marginRight="auto",Bs.style.width="100%");let Au=()=>{let r=Ko(o,Me());if(!(!r||Me()))for(let a of[Ut,wo,jt,Re])a&&(a.style.maxWidth=r,a.style.marginLeft="auto",a.style.marginRight="auto",a.style.width="100%")};Au();let Mu=()=>{!o.attachments?.enabled||!et||!jt||(_e?_e.remountPreviews(jt):(_e=xi.fromConfig(o.attachments,fu),_e.setPreviewsContainer(jt)),Be?.addListener(et,"change",r=>{let a=r.target;_e?.handleFileSelect(a.files),a.value=""}),re.querySelector(".persona-attachment-drop-overlay")||re.appendChild(xb(o.attachments.dropOverlay)))};Mu();let Jb=()=>lt?.prefetch(),gc=()=>{if(!o.contextMentions?.enabled||!Z)return;let r=Vd();if(!r){let m=Z;wl().then(()=>{lt||Z!==m||!m.isConnected||(gc(),An?.resolve())},()=>{});return}let a=Be?.header??null,d=a?Hd(a):void 0;if(lt=r.createContextMentionOrchestrator({deps:{loadContextMentions:Af,loadContextMentionsInline:Mf,renderLucideIcon:se,createMentionButton:Cf},config:o,textarea:Z,anchor:Ut??Z,getMessages:()=>x.getMessages(),liveRegionHost:re,chipRow:d}),lt&&!d){let m=Z;m.parentElement?.insertBefore(lt.contextRow,m)}};gc();let An=null,Zb={getState:()=>ie.getState(),getValue:()=>Z?.value??"",setValue:r=>{Z&&(Z.value=r,Z.dispatchEvent(new Event("input",{bubbles:!0})),Rn())},submit:()=>{xf(Be?.form??null)},openAttachmentPicker:()=>{_n()||et?.click()},toggleVoice:()=>{dc?.()},requestRender:()=>An?.resolve()},ev=()=>{let r=[];return(lt?.affordanceButtons??[]).forEach((d,m)=>{r.push({id:`core:mention-${m}`,placement:"start",order:Kn.mention+m,element:d,managed:!0})}),qt&&r.push({id:"core:attachment",placement:"start",order:Kn.attachment,element:qt}),nn&&r.push({id:"core:mic",placement:"end",order:Kn.mic,element:nn}),Hn&&r.push({id:"core:send",placement:"end",order:Kn.send,element:Hn}),r},Eu=()=>{An?.destroy(),An=Mh({getBindings:()=>Be,collect:()=>({builtIns:ev(),configActions:[...Qb(),...o.composer?.actions??[]],plugins:g,contributionContext:{config:o,getState:()=>ie.getState(),requestRender:()=>An?.resolve()},debug:o.debug===!0}),actionContext:Zb,getState:()=>ie.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(r,a)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${a.actionId}" failed:`,r)}}),An.resolve()};Eu();let mc=()=>{if(Xn?.destroy(),Xn=null,!Br().length)return;let r=Be?.header;r&&(Xn=Ph({row:Hd(r),onRemove:a=>ac(a),initialIds:ie.getState().activeModeIds}),Xn.render(ie.getState().activeModeIds,Br()))};mc();let Tu=()=>{Mo?.destroy(),Mo=null,Eo?.destroy(),Eo=null;let r=Be?.header;r&&(Mo=Oh({onDismiss:()=>Wn(void 0)}),r.appendChild(Mo.element),Mo.render(ie.getState().quote),cc()==="defer-one"&&(Eo=_h({onEdit:()=>Qv(),onRemove:()=>Or(void 0)}),r.appendChild(Eo.element),Eo.render(ie.getState().pendingSubmission)))};Tu();let fc=Uh(),tv=()=>{let r=Be?.header?.querySelector(wf);if(r)return r.childElementCount>0;let a=ie.getState();return a.mentionRefs.length>0||Tl(a.activeModeIds,Br()).length>0};function Mn(){let r=ie.getState(),a=fc.observe(qh(Z),r.text);Ie.toggleAttribute("data-persona-composer-compact",zh({text:r.text,wrapped:a,hasAttachments:r.attachments.length>0,hasChips:tv(),hasQuote:r.quote!==void 0,hasPendingSubmission:r.pendingSubmission!==void 0}))}function ku(){o.composer?.layout==="single-row"&&!Me()?Ie.setAttribute("data-persona-composer-layout","single-row"):Ie.removeAttribute("data-persona-composer-layout")}ku(),ie.subscribe(()=>{An?.sync(),Fc(),Aa(),Mn(),cg()}),Aa();let Pu=!1,nv=r=>{if(Pu||o.debug!==!0)return;let a=["messages","composer"].filter(d=>r[d]);a.length&&(Pu=!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??{};nv(r);let a=m=>{switch(m){case"body-top":return j.querySelector("[data-persona-intro-card]");case"messages":return ce;case"footer-top":return wo;case"composer":return Ut;case"footer-bottom":return Re;default:return null}},d=(m,f)=>{switch(m){case"header-left":case"header-center":case"header-right":if(m==="header-left")Ke.insertBefore(f,Ke.firstChild);else if(m==="header-right")Ke.appendChild(f);else{let b=Ke.querySelector(".persona-flex-col");b?b.parentNode?.insertBefore(f,b.nextSibling):Ke.appendChild(f)}break;case"body-top":{let b=j.querySelector("[data-persona-intro-card]");b?b.replaceWith(f):j.insertBefore(f,j.firstChild);break}case"body-bottom":j.appendChild(f);break;case"footer-top":wo.replaceWith(f);break;case"footer-bottom":Re.replaceWith(f);break;default:break}};for(let[m,f]of Object.entries(r))if(f)try{let b=f({config:o,defaultContent:()=>a(m)});b&&d(m,b)}catch(b){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${m}":`,b)}})(),ce.addEventListener("click",r=>{let a=r.target;if(!(a instanceof Element))return;let d=a.closest("button[data-persona-copy-tool-detail]");d&&(r.preventDefault(),r.stopPropagation(),Ny(d))});let hc=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 f=m.getAttribute("data-message-id");if(!f)return;Io(),Kr();let b=d.getAttribute("data-bubble-type");if(m.classList.contains("persona-activity-row")){l.manual(f);let D=m.parentElement?.closest("[data-persona-tool-group]");D?.dataset.messageId&&l.manual(D.dataset.messageId)}if(b==="reasoning")i.has(f)?i.delete(f):i.add(f),kp(f,m,i);else if(b==="tool")s.has(f)?s.delete(f):s.add(f),Hp(f,m,s,o);else if(b==="approval"&&A){let $=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",F=c.get(f)??$;c.set(f,!F),A.updateApprovalDetailsUI(f,m,o,c)}It.delete(f)};ce.addEventListener("pointerdown",r=>{r.target.closest('button[data-expand-header="true"]')&&(r.preventDefault(),hc(r))}),ce.addEventListener("click",r=>{r.detail===0&&r.target.closest(".persona-activity-row")&&hc(r)}),ce.addEventListener("keydown",r=>{let a=r.target;(r.key==="Enter"||r.key===" ")&&a.closest('button[data-expand-header="true"]')&&(r.preventDefault(),hc(r))}),ce.addEventListener("copy",r=>{let{clipboardData:a}=r;if(!a)return;let d=ce.getRootNode(),m=typeof d.getSelection=="function"?d.getSelection():window.getSelection();if(!m||m.isCollapsed)return;let f=m.toString(),b=ny(f);!b||b===f||(a.setData("text/plain",b),r.preventDefault())});let yc=new Map,Lu=null,Iu="idle",ov={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},rv=(r,a)=>{let{icon:d,label:m}=ov[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 f=se(d,14,"currentColor",2);f&&(r.innerHTML="",r.appendChild(f))},Hu=()=>{ce.querySelectorAll('[data-action="read-aloud"]').forEach(a=>{let m=a.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;rv(a,m&&m===Lu?Iu:"idle")})};ce.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 f=m.getAttribute("data-actions-for");if(!f)return;let b=d.getAttribute("data-action");if(b==="copy"){let $=x.getMessages().find(F=>F.id===f);if($&&Wr.onCopy){let F=$.content||"";navigator.clipboard.writeText(F).then(()=>{d.classList.add("persona-message-action-success");let q=yt(vb,14,"currentColor",2);q&&(d.innerHTML="",d.appendChild(q)),setTimeout(()=>{d.classList.remove("persona-message-action-success");let K=yt(Cb,14,"currentColor",2);K&&(d.innerHTML="",d.appendChild(K))},2e3)}).catch(q=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",q)}),Wr.onCopy($)}}else if(b==="read-aloud")x.toggleReadAloud(f);else if(b==="upvote"||b==="downvote"){let $=(yc.get(f)??null)===b,F=b==="upvote"?"thumbs-up":"thumbs-down";if($){yc.delete(f),d.classList.remove("persona-message-action-active");let q=se(F,14,"currentColor",2);q&&(d.innerHTML="",d.appendChild(q))}else{let q=b==="upvote"?"downvote":"upvote",K=m.querySelector(`[data-action="${q}"]`);if(K){K.classList.remove("persona-message-action-active");let De=se(q==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);De&&(K.innerHTML="",K.appendChild(De))}yc.set(f,b),d.classList.add("persona-message-action-active");let X=se(F,14,"currentColor",2);X&&(X.setAttribute("fill","currentColor"),d.innerHTML="",d.appendChild(X)),d.classList.remove("persona-message-action-pop"),d.offsetWidth,d.classList.add("persona-message-action-pop");let He=x.getMessages().find(Fe=>Fe.id===f);He&&Wr.onFeedback&&Wr.onFeedback({type:b,messageId:He.id,message:He})}}else if(b==="regenerate")ta?.regenerate(f);else if(b==="edit")ta?.edit(f);else if(b==="quote")ta?.quote(f);else if(b?.startsWith(Fl)){let D=b.slice(Fl.length),$=o.messageActions?.custom?.find(q=>q.id===D),F=x.getMessages().find(q=>q.id===f);if(!$||!F)return;try{$.onSelect(F)}catch(q){console.error(`[AgentWidget] messageActions.custom "${D}" onSelect failed:`,q)}}});let ta=null;ce.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 f=m.getAttribute("data-message-id");if(!f)return;let b=d.getAttribute("data-approval-action");if(!b)return;let D=b==="approve"?"approved":"denied",F=x.getMessages().find(K=>K.id===f);if(!F?.approval)return;let q=m.querySelector("[data-approval-buttons]");q&&q.querySelectorAll("button").forEach(X=>{X.disabled=!0,X.style.opacity="0.5",X.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?x.resolveWebMcpApproval(f,D):x.resolveApproval(F.approval,D)});let Te=null,Ru=!1,Us=null,er=()=>{},qs="none",na=null,pn={artifacts:[],selectedId:null},Jn=!1,En=!1,js=!1,Nr=!1,Wu=()=>Nr||pn.artifacts.some(r=>as(o.features?.artifacts,r)==="panel"),oa=()=>pn.artifacts.length>0&&!Jn&&Wu(),un={current:null},bc=(r,a)=>{let d=x.getArtifactById(a),m=d?.markdown,f=d?.title||"artifact",b=d?.file,D=d?.artifactType??"markdown";if(!m){let q=r.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(q){let X=x.getMessages().find(ae=>ae.id===q);if(X?.rawContent)try{let ae=JSON.parse(X.rawContent);m=ae?.props?.markdown,f=ae?.props?.title||f,ae?.props?.file&&typeof ae.props.file=="object"&&(b=ae.props.file),!d&&typeof ae?.props?.artifactType=="string"&&(D=ae.props.artifactType)}catch{}}}return{markdown:m,title:f,file:b,artifactType:D}};ce.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:b,title:D,file:$}=bc(d,m);if(!b)return;let F=yo();F&&F.triggerArtifactDownload(F.downloadInfoFor({title:D,markdown:b,file:$}))}),ce.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 f=d.closest("[data-artifact-inline]"),b=f?null:d.closest("[data-open-artifact]"),D=f?f.getAttribute("data-artifact-inline"):b?.getAttribute("data-open-artifact")??null,F=(f?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Fe=>Fe.id===m);if(!F)return;let{markdown:q,title:K,file:X,artifactType:ae}=bc(d,D??""),He={artifactId:D,title:K,artifactType:ae,markdown:q,file:X};try{Promise.resolve(F.onClick(He)).catch(()=>{})}catch{}}),ce.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 f=x.getArtifactById(m),b=yo();if(!b)return;let D="";if(f)D=b.artifactCopyText(f);else{let{markdown:$,file:F,artifactType:q}=bc(d,m);q==="markdown"&&(D=b.artifactCopyText({id:m,artifactType:"markdown",status:"complete",markdown:$??"",...F?{file:F}:{}}))}D&&navigator.clipboard.writeText(D).then(()=>{let $=yt(vb,16,"currentColor",2);$&&(d.replaceChildren($),setTimeout(()=>{let F=yt(Cb,16,"currentColor",2);F&&d.replaceChildren(F)},1500))}).catch(()=>{})}),ce.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||(Jn=!1,Nr=!0,En=!0,js=!0,x.selectArtifact(m),Tn())}),ce.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(),Jn=!1,Nr=!0,x.selectArtifact(m),Tn())}),ce.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 Ks=We.composerOverlay,vc=r=>{wl().catch(()=>{}),nf(r,o,Ks)},Bu=null,sv={mount:t,overlay:Ks,sessionRef:un,config:()=>o},ra=!1,Du=r=>a=>{let d=a.target,m=d?.closest?.("[data-persona-ask-sheet-for]");if(!m||!(r==="click"?!!d?.closest("[data-ask-user-action]"):a.key==="Enter"&&!!d?.matches?.('[data-ask-free-text-input="true"]')))return;let b=$=>{Bu??=$.createAskUserSheetHandlers(sv),Bu[r](a)},D=Vd();if(D){b(D);return}ra||(ra=!0,wl().then($=>{ra=!1,m.isConnected&&b($)},()=>{ra=!1}))};Ks.addEventListener("click",Du("click")),Ks.addEventListener("keydown",Du("keydown"));let Ou=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=Ks.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),b=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];b&&(r.preventDefault(),b.click())};document.addEventListener("keydown",Ou);let Zn=null,ot=null,Gs=null,sa=null,ia=()=>{},_u=!1,aa="",la="";function Cc(){sa?.(),sa=null}let iv=()=>{let r=tt?.railShell?tt.railHost:null,a=r?.isConnected?r:null,d=a?a.getBoundingClientRect().width:0;return d<=0?200:d+360},Fu=()=>{if(!Zn||!ot)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){ot.style.removeProperty("position"),ot.style.removeProperty("left"),ot.style.removeProperty("top"),ot.style.removeProperty("bottom"),ot.style.removeProperty("width"),ot.style.removeProperty("z-index");return}let m=Zn.firstElementChild;if(!m||m===ot)return;let f=10;ot.style.position="absolute",ot.style.top="0",ot.style.bottom="0",ot.style.width=`${f}px`,ot.style.zIndex="5";let b=Vp(Zn,a),D=m.offsetWidth+b/2-f/2;ot.style.left=`${Math.max(0,D)}px`},ca=()=>{},Nu=()=>{let r=t.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,d=o.launcher?.mobileBreakpoint??640;return!a||r.innerWidth>d?!1:de||rt(o)},da=()=>!zt(o)||!oa()||t.classList.contains("persona-artifact-narrow-host")||Nu()||(t.ownerDocument.defaultView??window).innerWidth<eA?"none":_p(o)?"detached":"welded",Tn=()=>{if(!Te||!zt(o))return;Oi(t,o),_i(t,o),ca();let r=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,a=le.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",a>0&&a<=r);let d=oa();Te.setVisible(d),Te.update(pn),Jn?(Te.setMobileOpen(!1),Te.element.classList.add("persona-hidden"),Te.backdrop?.classList.add("persona-hidden"),En=!1,js=!1):pn.artifacts.length>0&&Wu()?(Te.element.classList.remove("persona-hidden"),Te.setMobileOpen(!0)):(Te.setMobileOpen(!1),Te.element.classList.add("persona-hidden"),Te.backdrop?.classList.add("persona-hidden"),En=!1,js=!1);let m=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Te.setExpandToggleVisible(m),Te.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Te.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Te.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Te.setTabFade(o.features?.artifacts?.layout?.tabFade),Te.setRenderTabBar(o.features?.artifacts?.renderTabBar),!m&&!js&&(En=!1),En!==_u){let b=Te.element;En?(aa=b.style.width,la=b.style.maxWidth,b.style.removeProperty("width"),b.style.removeProperty("max-width")):(aa&&(b.style.width=aa),la&&(b.style.maxWidth=la),aa="",la=""),_u=En}t.classList.toggle("persona-artifact-expanded",En),Te.setExpanded(En);let f=da();f!==qs&&(qs=f,er()),ia()};if(zt(o)){le.style.position="relative";let r=P("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),a=P("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");r.appendChild(re),Zn=a,a.appendChild(r),le.appendChild(a);let d=f=>{Ru||Te||(Te=f.createArtifactPane(o,{onSelect:b=>un.current?.selectArtifact(b),onDismiss:()=>{Jn=!0,Tn()},onToggleExpand:()=>{let b=!En,D=pn.selectedId??pn.artifacts[pn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:D,expanded:b})!==!0&&(En=b,b||(js=!1),Tn())}}),Te.element.classList.add("persona-hidden"),a.appendChild(Te.element),Te.backdrop&&le.appendChild(Te.backdrop),ia(),Tn())},m=yo();m?d(m):(Dp(()=>{let f=yo();f&&d(f)}),ql().catch(()=>{})),ia=()=>{if(!Zn||!Te)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Gs?.(),Gs=null,Cc(),ot&&(ot.remove(),ot=null),Te.element.style.removeProperty("width"),Te.element.style.removeProperty("maxWidth");return}if(!ot){let b=P("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");b.setAttribute("role","separator"),b.setAttribute("aria-orientation","vertical"),b.setAttribute("aria-label","Resize artifacts panel"),b.tabIndex=0;let D=t.ownerDocument,$=D.defaultView??window,F=q=>{if(!Te||q.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||$.innerWidth<=640)return;q.preventDefault(),Cc();let K=q.clientX,X=Te.element.getBoundingClientRect().width,ae=o.features?.artifacts?.layout,He=De=>{let Yt=Zn.getBoundingClientRect().width,nt=t.classList.contains("persona-artifact-welded-split"),it=Vp(Zn,$),Nt=nt?0:b.getBoundingClientRect().width||6,pt=X-(De.clientX-K),ze=Zy(pt,Yt,it,Nt,ae?.resizableMinWidth,ae?.resizableMaxWidth,iv());Te.element.style.width=`${ze}px`,Te.element.style.maxWidth="none",Fu()},Fe=()=>{D.removeEventListener("pointermove",He),D.removeEventListener("pointerup",Fe),D.removeEventListener("pointercancel",Fe),sa=null;try{b.releasePointerCapture(q.pointerId)}catch{}};sa=Fe,D.addEventListener("pointermove",He),D.addEventListener("pointerup",Fe),D.addEventListener("pointercancel",Fe);try{b.setPointerCapture(q.pointerId)}catch{}};b.addEventListener("pointerdown",F),ot=b,Zn.insertBefore(b,Te.element),Gs=()=>{b.removeEventListener("pointerdown",F)}}if(ot){let b=oa();ot.classList.toggle("persona-hidden",!b),Fu()}},ca=()=>{if(!de||!Te||(o.launcher?.sidebarMode??!1)||rt(o)&&wn(o).reveal==="emerge")return;let b=t.ownerDocument.defaultView??window,D=o.launcher?.mobileFullscreen??!0,$=o.launcher?.mobileBreakpoint??640;if(D&&b.innerWidth<=$||!Ky(o,de))return;let F=Pr(o).width,q=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";oa()?(le.style.width=q,le.style.maxWidth=q):(le.style.width=F,le.style.maxWidth=F)},typeof ResizeObserver<"u"&&(Us=new ResizeObserver(()=>{Tn()}),Us.observe(le))}else le.appendChild(re);Me()&&St&&(We.peekBanner&&St.appendChild(We.peekBanner),St.appendChild(Ie)),t.appendChild(Le),St&&t.appendChild(St);let wc=()=>{let r=Nu()||Me()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!rt(o);if(ce.style.gap=r?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",ce.style.setProperty("--persona-transcript-gap",ce.style.gap),Me()){le.style.width="100%",le.style.maxWidth="100%";let ge=o.launcher?.composerBar??{},Se=Le.dataset.state==="expanded",be=ge.expandedSize??"anchored";if(!(Se&&be!=="fullscreen")){re.style.background="",re.style.border="",re.style.borderRadius="",re.style.overflow="",re.style.boxShadow="";return}let ht=o.theme?.components?.panel,Qt=ho(o),co=(po,wr)=>po==null||po===""?wr:Pt(Qt,po)??po,vd="1px solid var(--persona-border)",Cr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Cd="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";re.style.background="var(--persona-surface, #ffffff)",re.style.border=co(ht?.border,vd),re.style.borderRadius=co(ht?.borderRadius,Cd),re.style.boxShadow=co(ht?.shadow,Cr),re.style.overflow="hidden";return}let a=rt(o),d=o.launcher?.sidebarMode??!1,m=a||d||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,b=o.launcher?.detachedPanel===!0,D=o.theme?.components?.panel,$=o.darkTheme?.components?.panel,F=Ei(o)==="dark"?Sr(D??{},$??{}):D,q=ho(o),K=(ge,Se)=>ge==null||ge===""?Se:Pt(q,ge)??ge,X=t.ownerDocument.defaultView??window,ae=o.launcher?.mobileFullscreen??!0,He=o.launcher?.mobileBreakpoint??640,Fe=X.innerWidth<=He,De=ae&&Fe&&de,Yt=a&&ae&&Fe,nt=o.launcher?.position??"bottom-left",it=nt==="bottom-left"||nt==="top-left",Nt=o.launcher?.zIndex??Dt,pt=(ge,Se,be)=>`var(--persona-components-panel-modes-${ge}-${Se}, ${be})`,ze=F?.modes?.floating,Vn=K(ze?.border??F?.border,pt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),$n=K(ze?.shadow??F?.shadow,pt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),yn=K(ze?.borderRadius??F?.borderRadius,pt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),bn=b&&!De&&!Yt,Fo=De||Yt?"mobile":bn?"floating":a?"docked":d?"sidebar":f?"inline":"floating",zn=F?.modes?.[Fo];bn?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let kn=bn?Vn:d||De?"none":Vn,No=bn?$n:De?"none":d?it?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":f?"none":$n;a&&!De&&!bn&&(No="none",kn="none");let pi=bn?yn:d||De?"0":yn,vr=K(zn?.border??F?.border,pt(Fo,"border",kn)),M=K(zn?.shadow??F?.shadow,pt(Fo,"shadow",No)),me=K(zn?.borderRadius??F?.borderRadius,pt(Fo,"borderRadius",pi)),fe=da(),U=fe==="detached",Ue=fe==="welded";t.classList.toggle("persona-artifact-detached-split",U),t.classList.toggle("persona-artifact-welded-split",Ue);let mt="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)))))",Ye=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&zt(o)&&_p(o)&&f&&!a;t.classList.toggle("persona-artifact-chat-flush",Ye);let ut=U||Ye?"none":M,Ct=U?Vn:Ue?"none":vr,ue=U?yn:me;Ye&&(Ct="none",ue="0");let Qe=zn?.borderRadius!=null&&zn.borderRadius!==""||F?.borderRadius!=null&&F.borderRadius!=="",ye=Ye&&!Qe?"0":me,wt=j.scrollTop;t.style.cssText="",Le.style.cssText="",le.style.cssText="",re.style.cssText="",j.style.cssText="",Fr||(Ie.style.cssText=""),xn&&(j.style.display="none"),(m||f)&&(t.style.minWidth="0");let vn=()=>{if(wt<=0)return;(j.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(j.scrollTop===wt)return;let Se=j.scrollHeight-j.clientHeight;Se<=0||(j.scrollTop=Math.min(wt,Se))})};if(De){Le.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"),Le.style.cssText=`
31
31
  position: fixed !important;
32
32
  inset: 0 !important;
33
33
  width: 100% !important;
@@ -37,7 +37,7 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
37
37
  padding: 0 !important;
38
38
  display: flex !important;
39
39
  flex-direction: column !important;
40
- z-index: ${Ft} !important;
40
+ z-index: ${Nt} !important;
41
41
  background-color: var(--persona-surface, #ffffff) !important;
42
42
  `,le.style.cssText=`
43
43
  position: relative !important;
@@ -63,7 +63,7 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
63
63
  overflow: hidden !important;
64
64
  border-radius: 0 !important;
65
65
  border: none !important;
66
- `,j.style.flex="1 1 0%",j.style.minHeight="0",j.style.overflowY="auto",Le.style.flexShrink="0",rc(),Yl=!0,bn();return}let Mt=Pr(o);if(!d&&!a)f&&m?(le.style.width="100%",le.style.maxWidth="100%"):(le.style.width=Mt.width,le.style.maxWidth=Mt.maxWidth);else if(a)if(Cn(o).reveal==="emerge"&&!b){let we=Cn(o).width;le.style.width=we,le.style.maxWidth=we}else le.style.width="100%",le.style.maxWidth="100%";if(la(),le.style.boxShadow=ut,le.style.borderRadius=ye,U?le.style.border="none":Ue&&(le.style.border=vr),re.style.border=Ct,re.style.borderRadius=ue,re.style.boxShadow=U&&!Ye?mt:"",Ye&&(re.style.background="transparent",j.style.background="transparent",Le.style.background="transparent",Le.style.borderTop="none"),Ue){let ge=o.features?.artifacts?.layout;ta=ge?.unifiedSplitOuterRadius?.trim()||ge?.paneBorderRadius?.trim()||me}else ta=null;let qe=zn?.border!=null||F?.border!=null;if(a&&!De&&!yn&&!U&&!Ue&&!qe&&(re.style.border="none",Cn(o).side==="right"?re.style.borderLeft="1px solid var(--persona-border)":re.style.borderRight="1px solid var(--persona-border)"),a&&!De&&Ue&&!qe&&(Cn(o).side==="right"?le.style.borderLeft="1px solid var(--persona-border)":le.style.borderRight="1px solid var(--persona-border)"),m&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",f&&(t.style.width="100%"),Pe.style.display="flex",Pe.style.flexDirection="column",Pe.style.flex="1 1 0%",Pe.style.minHeight="0",Pe.style.maxHeight="100%",Pe.style.height="100%",f&&(Pe.style.overflow="hidden"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",U||(le.style.overflow="hidden"),re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.overflow="hidden",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.overflowY="auto",Le.style.flexShrink="0"),f&&(yn||U||Ye)&&!a&&(Ye||(Pe.style.padding="var(--persona-panel-inset)"),Pe.style.background="var(--persona-panel-canvas-bg)"),Pe.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"),!d&&!f&&!a&&(ln[nt]??ln["bottom-right"]).split(" ").forEach(we=>Pe.classList.add(we)),d){let ge=xr(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":Pt(ho(o),"components.panel.width")??"420px";b?Pe.style.cssText=`
66
+ `,j.style.flex="1 1 0%",j.style.minHeight="0",j.style.overflowY="auto",Ie.style.flexShrink="0",ic(),Xl=!0,vn();return}let Mt=Pr(o);if(!d&&!a)f&&m?(le.style.width="100%",le.style.maxWidth="100%"):(le.style.width=Mt.width,le.style.maxWidth=Mt.maxWidth);else if(a)if(wn(o).reveal==="emerge"&&!b){let Se=wn(o).width;le.style.width=Se,le.style.maxWidth=Se}else le.style.width="100%",le.style.maxWidth="100%";if(ca(),le.style.boxShadow=ut,le.style.borderRadius=ye,U?le.style.border="none":Ue&&(le.style.border=vr),re.style.border=Ct,re.style.borderRadius=ue,re.style.boxShadow=U&&!Ye?mt:"",Ye&&(re.style.background="transparent",j.style.background="transparent",Ie.style.background="transparent",Ie.style.borderTop="none"),Ue){let ge=o.features?.artifacts?.layout;na=ge?.unifiedSplitOuterRadius?.trim()||ge?.paneBorderRadius?.trim()||me}else na=null;let qe=zn?.border!=null||F?.border!=null;if(a&&!De&&!bn&&!U&&!Ue&&!qe&&(re.style.border="none",wn(o).side==="right"?re.style.borderLeft="1px solid var(--persona-border)":re.style.borderRight="1px solid var(--persona-border)"),a&&!De&&Ue&&!qe&&(wn(o).side==="right"?le.style.borderLeft="1px solid var(--persona-border)":le.style.borderRight="1px solid var(--persona-border)"),m&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",f&&(t.style.width="100%"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.height="100%",f&&(Le.style.overflow="hidden"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",U||(le.style.overflow="hidden"),re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.overflow="hidden",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.overflowY="auto",Ie.style.flexShrink="0"),f&&(bn||U||Ye)&&!a&&(Ye||(Le.style.padding="var(--persona-panel-inset)"),Le.style.background="var(--persona-panel-canvas-bg)"),Le.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"),!d&&!f&&!a&&(cn[nt]??cn["bottom-right"]).split(" ").forEach(Se=>Le.classList.add(Se)),d){let ge=xr(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":Pt(ho(o),"components.panel.width")??"420px";b?Le.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: var(--persona-panel-inset) !important;
69
69
  bottom: var(--persona-panel-inset) !important;
@@ -74,9 +74,9 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
74
74
  padding: 0 !important;
75
75
  display: flex !important;
76
76
  flex-direction: column !important;
77
- z-index: ${Ft} !important;
77
+ z-index: ${Nt} !important;
78
78
  ${it?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
79
- `:Pe.style.cssText=`
79
+ `:Le.style.cssText=`
80
80
  position: fixed !important;
81
81
  top: 0 !important;
82
82
  bottom: 0 !important;
@@ -87,7 +87,7 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
87
87
  padding: 0 !important;
88
88
  display: flex !important;
89
89
  flex-direction: column !important;
90
- z-index: ${Ft} !important;
90
+ z-index: ${Nt} !important;
91
91
  ${it?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
92
92
  `,le.style.cssText=`
93
93
  position: relative !important;
@@ -116,12 +116,12 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
116
116
  border: ${Ct} !important;
117
117
  ${U&&!Ye?`box-shadow: ${mt} !important;`:""}
118
118
  ${Ye?"background: transparent !important;":""}
119
- `,Fr||(Le.style.cssText=`
119
+ `,Fr||(Ie.style.cssText=`
120
120
  flex-shrink: 0 !important;
121
121
  border-top: none !important;
122
122
  padding: 8px 16px 12px 16px !important;
123
123
  ${Ye?"background: transparent !important;":""}
124
- `)}if(!f&&!a){let ge="max-height: -moz-available !important; max-height: stretch !important;",we=d?"":"padding-top: 1.25em !important;",be=d?"":`z-index: ${o.launcher?.zIndex??Dt} !important;`;Pe.style.cssText+=ge+we+be}rc(),bn()},Cc=()=>{t.style.setProperty("--persona-content-max-width",Ko(o,Ae()))},Fu=!1;function Nu(){o.layout?.topFade&&j.scrollTop>1?j.setAttribute("data-persona-top-fade","true"):j.removeAttribute("data-persona-top-fade")}let wc=()=>{Nu();let r=sp(o,Ae());Ae()&&o.composer?.placement&&o.debug===!0&&!Fu&&(Fu=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let a=Xo();t.setAttribute("data-persona-composer-placement",r),t.setAttribute("data-persona-conversation-state",Qi),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",a.composerGap??Hl),Ji()},Vu=()=>{if(Ae())return;let r=rt(o),a=o.launcher?.sidebarMode??!1;if(r||a||(o.launcher?.fullHeight??!1)||!de)return;let m=t.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640;if(f&&m.innerWidth<=b)return;let D=Pr(o);le.style.height=D.height,le.style.maxHeight=D.maxHeight};vc(),Ti(t,o),Oi(t,o),_i(t,o),Cc(),wc(),er=()=>{vc(),Vu(),Ti(t,o),Oi(t,o),_i(t,o),Cc(),wc(),ta?t.style.setProperty("--persona-artifact-welded-outer-radius",ta):t.style.removeProperty("--persona-artifact-welded-outer-radius"),ji(),qi()};let oe=[];oe.push(()=>{Iu=!0}),oe.push(()=>{h.forEach(r=>r()),y.destroy()}),oe.push(()=>{document.removeEventListener("keydown",Bu)}),oe.push(()=>{Fs!==null&&clearTimeout(Fs)});let Bn=null,Dn=null;oe.push(()=>{Bn?.(),Bn=null,Dn?.(),Dn=null}),Us&&oe.push(()=>{Us?.disconnect(),Us=null}),oe.push(()=>{Gs?.(),Gs=null,bc(),ot&&(ot.remove(),ot=null),Ee?.element.style.removeProperty("width"),Ee?.element.style.removeProperty("maxWidth"),Ee?.destroy()}),Jt&&oe.push(()=>{ru=!0,Yn=null,Co!==null&&(cancelAnimationFrame(Co),Co=null),Ot?.destroy(),Ot=null,Lt?.destroy(),Lt=null,Rr=null});let tr=null,$u=()=>{tr&&(tr(),tr=null),o.colorScheme==="auto"&&(tr=Il(()=>{Ti(t,o)}))};$u(),oe.push(()=>{tr&&(tr(),tr=null)}),oe.push(()=>{k=!0,L?.()}),oe.push(()=>{V=!0});let zu=!1;oe.push(()=>{zu=!0});let Sc=(r,a)=>{let d=mi(r,a);return d||!Hf.includes(r)?d:(iy().then(m=>{if(zu)return;Rd(m.wipe),Rd(m.glyphCycle);let f=mi(r,a);f&&yi(f,t)}).catch(()=>{}),null)},da=o.features?.streamAnimation;if(da?.type&&da.type!=="none"){let r=Sc(da.type,da.plugins);r&&yi(r,t),oe.push(()=>Rf(t))}let eo=Hi(wo),Uu=Hi(Zl),qu=Hi(Bs),nr=[eo,Uu,qu];oe.push(()=>{nr.forEach(r=>r.destroy())});let or=null,S,rr=null,ju=!1,Ku=0,Gu=null,Yu=r=>r.reduce((a,d)=>d.role==="user"?a+1:a,0),Qu=r=>{for(let a=r.length-1;a>=0;a--)if(Ja(r[a]))return r[a].id??null;return null},Xu=!1,rv=()=>{Xu||o.debug!==!0||(Xu=!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".'))},Ju=!1,Zu=!1,eg=(r,a)=>{Ju||o.debug!==!0||!a.enabled||a.expose||ju||Zu&&(S.isStreaming()||r.some(Ja)||(Ju=!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.")))},sr=r=>{if(!S)return;let a=r??S.getMessages(),d=X=>{X.render([],S,Z,a)},m=X=>{nr.forEach(ae=>{ae!==X&&d(ae)})};rr&&(Yu(a)>Ku||Qu(a)!==Gu)&&(rr=null);let f=ds(o);eg(a,f);let b=f.enabled?ef(a):null,D=rr??b,$=rr?"host":"agent";if(D){let X=o.suggestions?.followUps,ae=X?.placement??(X?"auto":"composer"),Fe=(ae==="auto"?Ae()?"composer":"after-message":ae)==="after-message"?qu:eo;m(Fe),Fe.render(D,S,Z,a,o.suggestionChipsConfig,{source:$,surface:"followUp",variant:X?.variant??"chip",behavior:X?.behavior??"send",overflow:X?.overflow??"wrap",maxItems:X?.maxItems??4,config:o,plugins:g,submitPrompt:Ra});return}if(a.some(X=>X.role==="user")){nr.forEach(d);return}let F=o.future?.v5Defaults===!0,q=Vs(),K=o.suggestions?.starters??(F?{}:void 0);if(K){let X=Ss(Xo(),a),ae=K.placement??"auto",He=ae==="auto"?X?"welcome":"composer":ae;if(He==="welcome"&&!X){rv(),nr.forEach(d);return}let Fe=He==="welcome"?Uu:eo;m(Fe),Fe.render(K.items??o.suggestionChips,S,Z,a,o.suggestionChipsConfig,{surface:"starter",variant:K.variant??(F&&!q?"chip":"card"),behavior:K.behavior??"send",overflow:K.overflow??"wrap",maxItems:K.maxItems??(F&&!q?3:4),config:o,plugins:g,submitPrompt:Ra});return}m(eo),eo.render(o.suggestionChips,S,Z,a,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:g,submitPrompt:Ra})},tg=()=>{rr&&(rr=null,sr())},sv=r=>{let a=Array.isArray(r)?[...r]:[];if(!a.length){tg();return}let d=S?S.getMessages():[];rr=a,ju=!0,Ku=Yu(d),Gu=Qu(d),sr(d)},on=!1,It=ny(),Vr=new Map,ir=new Map,To=new Map,ar=null,ko=null;function lr(){if(!ar)return;let r=ar;ar=null,ko?.destroy(),ko=null,It.delete(r),re.querySelector(`#wrapper-${r}`)?.removeAttribute("data-preserve-runtime"),S&&un(ce,S.getMessages(),Xt)}let cr=0,iv=is()!==null,rn=Tf(),sn=0,Po=null,Kt=!1,pa=!1,Lo=0,vt=null,dr=null,xc=!1,$r=!1,pr=null,Ys=!0,ua=!1,zr=null,ga=!1,Io=()=>{ga=!0,dv()},Ac=null,av=4,to=24,lv=80,cv=1e3,no=null,ng=()=>{t.setAttribute("data-persona-scrollbar",tc()),tc()!=="on-scroll"&&(no!==null&&clearTimeout(no),no=null,j.removeAttribute("data-persona-scrollbar-visible"))},dv=()=>{tc()==="on-scroll"&&(j.setAttribute("data-persona-scrollbar-visible",""),no!==null&&clearTimeout(no),no=setTimeout(()=>{no=null,Er(j,to)&&j.removeAttribute("data-persona-scrollbar-visible")},cv))};ng(),oe.push(()=>{no!==null&&clearTimeout(no)});let Mc=new Map,Ec=!1,ma=null,Ie={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};An();let og=o.voiceRecognition?.autoResume??!1,oo=r=>{G.emit("voice:state",{active:Ie.active,source:r,timestamp:Date.now()})},Tn=()=>{$e(r=>({...r,voiceState:{active:Ie.active,timestamp:Date.now(),manuallyDeactivated:Ie.manuallyDeactivated}}))},pv=()=>{if(o.voiceRecognition?.enabled===!1)return;let r=jp(x.voiceState),a=!!r.active,d=Number(r.timestamp??0);Ie.manuallyDeactivated=!!r.manuallyDeactivated,a&&Date.now()-d<Yx&&setTimeout(()=>{Ie.active||(Ie.manuallyDeactivated=!1,Nt(o.voiceRecognition?.provider)?S.toggleVoice().then(()=>{Ie.active=S.isVoiceActive(),oo("restore"),S.isVoiceActive()&&ns()}):Oa("restore"))},1e3)},uv=()=>S?bb(S.getMessages()).filter(r=>!r.__skipPersist):[],fa=null,rg=(r,a)=>{typeof console<"u"&&console.error(r,a)},ha=(r,a)=>{let d=()=>{try{let D=r();return!D||typeof D.then!="function"?null:Promise.resolve(D).catch($=>{rg(a,$)})}catch(D){return rg(a,D),null}},m=fa,f=m?m.then(()=>d()??void 0):d();if(!f)return;let b=f.finally(()=>{fa===b&&(fa=null)});fa=b};function Ur(r){if(!v?.save)return;let a=r?bb(r):S?uv():[],d=T&&S?.getResumableHandle();d&&(x={...x,durableResume:{executionId:d.executionId,after:d.lastEventId}});let m={messages:a,metadata:x,artifacts:dn.artifacts,selectedArtifactId:dn.selectedId,...ur?{draft:ur}:{}};ha(()=>v.save(m),"[AgentWidget] Failed to persist state:")}let ur,ya=()=>!v?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Qs=Fh({write:()=>{if(!ya())return;let r=ie.getState(),a=Oh({text:r.text,mentionRefs:r.mentionRefs,contentSegments:od(),selectedModelId:r.selectedModelId,activeModeIds:r.activeModeIds,quote:r.quote});JSON.stringify(a)!==JSON.stringify(ur)&&(ur=a,Ur())}});function sg(){ya()&&Qs.schedule()}function Tc(){Qs.flush()}function ig(r){if(!ya())return;let a=_h(r,{mentionSourceIds:(o.contextMentions?.sources??[]).map(d=>d.id),modelIds:(o.composer?.models??[]).map(d=>d.id),modes:o.composer?.modes??[]});a&&(ur=r,Z&&!Z.value&&(Z.value=a.text,Z.dispatchEvent(new Event("input",{bubbles:!0})),Rn()),a.selectedModelId&&(ie.setSelectedModelId(a.selectedModelId),Ao?.repaint()),Zi(a.activeModeIds??[]),a.quote&&Wn(a.quote),Qs.cancel())}function ba(){Qs.cancel(),ur&&(ur=void 0,ya()&&Ur())}let qr=null,ag=()=>Pe.querySelector("#persona-scroll-container")||j,jr=()=>{qr!==null&&(cancelAnimationFrame(qr),qr=null),Kt=!1},lg=()=>{Po!==null&&(cancelAnimationFrame(Po),Po=null),pa=!1,jr()},gv=()=>on&&Pc()&&(nn()!=="anchor-top"||du()),kc=()=>{let r=Ds()||"Jump to latest",a=gv();ft.toggleAttribute("data-persona-scroll-to-bottom-streaming",a),Lo>0?(Qo.textContent=String(Lo),Qo.style.display="",ft.setAttribute("aria-label",`${r} (${Lo} new)`)):(Qo.textContent="",Qo.style.display="none",ft.setAttribute("aria-label",a?`${r} (response streaming below)`:r))},cg=()=>{Lo!==0&&(Lo=0,kc())},mv=()=>{let r=vt?.spacerHeight??0;return r<=0?Er(j,to):wa(r)-j.scrollTop-j.clientHeight<=to},Pc=()=>xo()?!rn.isFollowing():!mv(),Lc=()=>!!S&&S.getMessages().length>0,Ht=()=>{if(!$b()||Wb()){ft.parentNode&&ft.remove(),ft.style.display="none";return}ft.parentNode!==re&&re.appendChild(ft),Jo();let a=uo(j)>0&&Pc()&&Lc();a?kc():cg(),ft.style.display=a?"":"none"},Kr=()=>{rn.pause()&&(lg(),Ht())},On=()=>{rn.resume(),cg(),Ht()},Ho=(r=!1)=>{xo()&&Lc()&&rn.isFollowing()&&(!r&&!on||(Po!==null&&(cancelAnimationFrame(Po),Po=null),pa=!0,Po=requestAnimationFrame(()=>{Po=null,pa=!1,rn.isFollowing()&&fv(ag(),r?220:140)})))},dg=(r,a,d,m=()=>!0)=>{let f=r.scrollTop,b=a(),D=b-f;if(jr(),Math.abs(D)<1){Kt=!0,r.scrollTop=b,sn=r.scrollTop,Kt=!1;return}let $=performance.now();Kt=!0;let F=K=>1-Math.pow(1-K,3),q=K=>{if(!m()){jr();return}let X=a();X!==b&&(b=X,D=b-f);let ae=K-$,He=Math.min(ae/d,1),Fe=F(He),De=f+D*Fe;r.scrollTop=De,sn=r.scrollTop,He<1?qr=requestAnimationFrame(q):(r.scrollTop=b,sn=r.scrollTop,qr=null,Kt=!1)};qr=requestAnimationFrame(q)},fv=(r,a=500)=>{let d=uo(r)-r.scrollTop;if(Math.abs(d)<1){sn=r.scrollTop;return}if(Math.abs(d)>=lv){jr(),Kt=!0,r.scrollTop=uo(r),sn=r.scrollTop,Kt=!1;return}dg(r,()=>uo(r),a,()=>rn.isFollowing())},Ic=()=>{if(!Lc()){Ht();return}let r=ag();Kt=!0,r.scrollTop=uo(r),sn=r.scrollTop,Kt=!1,Ht()},gr=r=>{let a=0,d=r;for(;d&&d!==j;)a+=d.offsetTop,d=d.offsetParent;return a},hv=()=>{let r=j.getRootNode();return(typeof r.getSelection=="function"?r.getSelection():null)??j.ownerDocument.getSelection()},va=()=>Lf(hv(),j),Hc=()=>{if(zb()!=="last-user-turn")return!1;let r=S?.getMessages()??[];if(r.length<2)return!1;let a=[...r].reverse().find(b=>b.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=j.querySelector(`[data-message-id="${d}"]`);if(!m)return!1;let f=Math.min(Math.max(0,gr(m)-Os()),uo(j));return Kt=!0,j.scrollTop=f,sn=j.scrollTop,Kt=!1,nn()==="follow"&&!Er(j,to)&&rn.pause(),Ht(),!0},Ca=r=>{let a=Math.max(0,Math.round(r));cn.style.height=`${a}px`,cn.style.display=a>0?"":"none",vt&&(vt.spacerHeight=Math.max(0,r))},wa=r=>{let a=parseFloat(getComputedStyle(j).paddingBottom)||0,d=0;for(let f of Array.from(j.children)){if(f===cn||f.offsetHeight===0)continue;let b=gr(f)+f.offsetHeight;b>d&&(d=b)}let m=j.scrollHeight-r;return d>0?Math.min(d+a,m):m},yv=()=>{if(!vt||vt.spacerHeight<=0)return;let r=wa(vt.spacerHeight),a=Math.max(0,Math.round(j.scrollTop)+j.clientHeight-r+to);a<vt.spacerHeight&&(Ca(a),Ht())},mr=()=>{dr!==null&&(cancelAnimationFrame(dr),dr=null),jr(),vt=null,cn.style.height="0px",cn.style.display="none"},pg=r=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Rc=r=>j.querySelector(`[data-message-id="${pg(r)}"]`),ug=r=>{dr!==null&&cancelAnimationFrame(dr),dr=requestAnimationFrame(()=>{dr=null;let a=pg(r),d=j.querySelector(`[data-message-id="${a}"]`);if(!d)return;let m=gr(d),f=vt?.spacerHeight??0,b=wa(f),{targetScrollTop:D,spacerHeight:$}=Hd({anchorOffsetTop:m,topOffset:Os(),viewportHeight:j.clientHeight,contentHeight:b,slack:to});vt={initialSpacerHeight:$,contentHeightAtAnchor:b,spacerHeight:$},Ca($),dg(j,()=>d.isConnected?Math.max(0,gr(d)-Os()):D,220)})},Gr=()=>{if(nn()!=="anchor-top"||!vt||!zr)return;let r=Rc(zr);if(!r)return;jr();let a=vt.spacerHeight,d=wa(a),{targetScrollTop:m,spacerHeight:f}=Hd({anchorOffsetTop:gr(r),topOffset:Os(),viewportHeight:j.clientHeight,contentHeight:d,slack:to});vt={initialSpacerHeight:f,contentHeightAtAnchor:d,spacerHeight:f},Ca(f),Kt=!0,j.scrollTop=m,sn=j.scrollTop,Kt=!1,Ht()},bv=()=>{if(xo()){if(!rn.isFollowing()||Er(j,1))return;Ho(!on);return}if(vt&&vt.initialSpacerHeight>0){let r=j.scrollHeight-vt.spacerHeight,a=If({initialSpacerHeight:vt.initialSpacerHeight,contentHeightAtAnchor:vt.contentHeightAtAnchor,currentContentHeight:r});a!==vt.spacerHeight&&Ca(a)}Ht()},vv=r=>{let a=nn();a==="follow"?(On(),Ho(!0)):a==="anchor-top"&&(Ys=!1,ua=!0,ga=!1,zr=r,ug(r))},Cv=()=>{if(nn()==="anchor-top"){if(ua){Ys=!1;return}Ys=!0,mr(),On(),Ho(!0)}},wv=96,Sv=r=>{if(pr===null)return!0;let a=Rc(pr),d=Rc(r);if(!a||!d)return!0;let m=gr(d)-gr(a);return Os()+m>j.clientHeight-wv},xv=r=>{if(nn()!=="anchor-top"||!ua||ga||va())return;let a=pr===null;for(let d of r){if(!a){d.id===pr&&(a=!0);continue}if(Ef(d)){if(d.id===zr||!Sv(d.id))return;zr=d.id,ug(d.id);return}}},Av=r=>{let a=new Map;r.forEach(d=>{let m=Mc.get(d.id);a.set(d.id,{streaming:d.streaming,role:d.role}),!m&&d.role==="assistant"&&(G.emit("assistant:message",d),!$r&&(nn()!=="anchor-top"||du())&&Pc()&&(Lo+=1,kc(),Ht(),Ns(Lo===1?"1 new message below.":`${Lo} new messages below.`))),d.role==="assistant"&&m?.streaming&&d.streaming===!1&&G.emit("assistant:complete",d),d.variant==="approval"&&d.approval&&(m?d.approval.status!=="pending"&&G.emit("approval:resolved",{approval:d.approval,decision:d.approval.status}):G.emit("approval:requested",{approval:d.approval,message:d}))}),Mc.clear(),a.forEach((d,m)=>{Mc.set(m,d)})},Xs=(r,a)=>{let d=a==="user"?"user":"assistant",m=o.layout?.messages?.[d],f=m?.width??"content",b=m?.maxWidth??(f==="full"?`var(--persona-message-${d}-max-width, 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-${f}`),r.classList.toggle("persona-justify-end",a==="user"),r.setAttribute("data-message-role",a),r.setAttribute("data-message-width",f),b?r.style.setProperty("--persona-message-row-max-width",b):r.style.removeProperty("--persona-message-row-max-width")},ro=(r,a)=>{let d=document.createElement("div");return d.className="persona-flex",d.id=`wrapper-${r}`,d.setAttribute("data-wrapper-id",r),Xs(d,a),d},Mv=(r,a,d)=>{let m=new Set;for(let M of a){let me=M.variant==="tool"?"tool":M.variant==="reasoning"?"reasoning":null;if(!me||qo(o,me)!=="row")continue;let fe=me==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;fe?.expandable!==!1&&(m.add(M.id),l.observe(M,me,me==="tool"?s:i,fe))}let f=document.createElement("div"),D=(()=>{let M=g.find(me=>me.renderLoadingIndicator);if(M?.renderLoadingIndicator)return M.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),$=(M,me)=>me==null?!1:typeof me=="string"?(M.textContent=me,!0):(M.appendChild(me),!0),F=new Set,q=new Map,K=new Set,X=g.some(M=>M.renderAskUserQuestion),ae=[],He=[],Fe=o.enableComponentStreaming!==!1,De=o.approval!==!1,Gt=[],nt=o.messageActions,it=nt?.showRegenerate===!0&&nt.enabled!==!1&&pn.current?.isStreaming()!==!0?ih(a):null,Ft=nt?.showEdit===!0&&nt.enabled!==!1,pt=nt?.showQuote===!0&&nt.enabled!==!1,ze=null,Vn=o.features?.reasoningDisplay?.completedVisibility,$n=M=>Vn==="removed"?!0:Vn==="removed-when-short"?qm(M,o.features?.reasoningDisplay?.shortThinkThreshold):!1,hn=o.features?.toolCallDisplay?.completedVisibility==="removed",yn=M=>M.variant==="reasoning"&&M.reasoning?.status==="complete"?$n(M.reasoning):hn&&M.variant==="tool"&&M.toolCall?.status==="complete";if(a.forEach(M=>{if(yn(M))return;if(F.add(M.id),q.set(M.id,M.role),ar===M.id&&ko){let ye=ro(M.id,M.role);ye.setAttribute("data-persona-message-edit-stub","true"),ye.setAttribute("data-preserve-runtime","true"),f.appendChild(ye),ze={messageId:M.id,element:ko.element};return}let me=X&&cs(M),fe=De&&M.variant==="approval"&&!!M.approval,U=!me&&M.role==="assistant"&&!M.variant&&Fe&&qp(M);!fe&&To.has(M.id)&&(r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime"),To.delete(M.id)),!U&&ir.has(M.id)&&(r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime"),ir.delete(M.id));let Ue=cs(M)?`:${M.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${M.agentMetadata?.askUserQuestionAnswers?Object.keys(M.agentMetadata.askUserQuestionAnswers).length:0}`:"",mt={canRegenerate:it===M.id,canEdit:Ft&&$d(M),canQuote:pt&&!M.variant&&(M.content?.trim().length??0)>0},Bt=`${mt.canRegenerate?"r":""}${mt.canEdit?"e":""}${mt.canQuote?"q":""}`,At=ty(M,cr)+Ue+`:${Bt}`,Ye=me||fe||U?null:oy(It,M.id,At);if(Ye){f.appendChild(Ye.cloneNode(!0)),cs(M)&&M.toolCall?.id&&M.agentMetadata?.awaitingLocalTool===!0&&!M.agentMetadata?.askUserQuestionAnswered&&(K.add(M.toolCall.id),yc(M));return}let ut=null,Ct=g.find(ye=>!!(M.variant==="reasoning"&&ye.renderReasoning||M.variant==="tool"&&ye.renderToolCall||!M.variant&&ye.renderMessage)),ue=o.layout?.messages;if(cs(M)&&M.agentMetadata?.askUserQuestionAnswered===!0){Vr.delete(M.id),r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ja(M)&&ds(o).enabled)return;if(cs(M)&&o.features?.askUserQuestion?.enabled!==!1){let ye=g.find(wt=>typeof wt.renderAskUserQuestion=="function");if(ye&&pn.current){let wt=Vr.get(M.id),bn=wt!==At,Mt=null;if(bn){let{payload:we,complete:be}=Jm(M),Vo=M.id,ht=()=>pn.current?.getMessages().find(Yt=>Yt.id===Vo);Mt=ye.renderAskUserQuestion({message:M,payload:we,complete:be,resolve:Yt=>{let co=ht();co&&pn.current?.resolveAskUserQuestion(co,Yt)},dismiss:()=>{let Yt=ht();Yt?.agentMetadata?.awaitingLocalTool&&(pn.current?.markAskUserQuestionResolved(Yt),pn.current?.resolveAskUserQuestion(Yt,"(dismissed)"))},config:o})}let qe=wt!=null;if(bn&&Mt===null&&!qe){M.agentMetadata?.awaitingLocalTool===!0&&!M.agentMetadata?.askUserQuestionAnswered&&(K.add(M.toolCall.id),yc(M));return}let ge=ro(M.id,M.role);ge.setAttribute("data-ask-plugin-stub","true"),ge.setAttribute("data-preserve-runtime","true"),f.appendChild(ge),ae.push({messageId:M.id,fingerprint:At,bubble:Mt});return}else{M.agentMetadata?.awaitingLocalTool===!0&&!M.agentMetadata?.askUserQuestionAnswered&&(K.add(M.toolCall.id),yc(M));return}}else if(fe){let ye=O();if(!ye){f.appendChild(ro(M.id,M.role));return}let wt=g.find(ge=>typeof ge.renderApproval=="function")??I,Mt=To.get(M.id)!==At,qe=null;if(Mt&&wt?.renderApproval){let ge=M.id,we=(be,Vo)=>{let ht=pn.current?.getMessages().find(Yt=>Yt.id===ge);ht?.approval&&(ht.approval.toolType==="webmcp"?pn.current?.resolveWebMcpApproval(ht.id,be):pn.current?.resolveApproval(ht.approval,be,Vo))};qe=wt.renderApproval({message:M,defaultRenderer:()=>ye.createApprovalBubble(M,o,c),config:o,approve:be=>we("approved",be),deny:be=>we("denied",be)})}if(Mt&&qe===null)r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime"),To.delete(M.id),ut=ye.createApprovalBubble(M,o,c);else{let ge=ro(M.id,M.role);ge.setAttribute("data-approval-plugin-stub","true"),ge.setAttribute("data-preserve-runtime","true"),f.appendChild(ge),Gt.push({messageId:M.id,fingerprint:At,bubble:qe});return}}else if(Ct)if(M.variant==="reasoning"&&M.reasoning&&Ct.renderReasoning){if(!Is)return;ut=Ct.renderReasoning({message:M,defaultRenderer:()=>Tp(M,o,i),config:o})}else if(M.variant==="tool"&&M.toolCall&&Ct.renderToolCall){if(!Hs)return;ut=Ct.renderToolCall({message:M,defaultRenderer:()=>Ip(M,o,s),config:o})}else Ct.renderMessage&&(ut=Ct.renderMessage({message:M,defaultRenderer:()=>{let ye=hp(M,d,ue,o.messageActions,Wr,{loadingIndicatorRenderer:D,widgetConfig:o,actionEligibility:mt});return M.role!=="user"&&Q(ye,M,o,S),ye},config:o}));if(!ut&&U){let ye=ub(M);if(ye){let wt=ir.get(M.id),bn=wt!==At,Mt=o.wrapComponentDirectiveInBubble!==!1&&go.getOptions(ye.component)?.bubbleChrome!==!1,qe=null;if(bn){let ge=db(ye,{config:o,message:M,transform:d});if(ge&&ye.component==="PersonaArtifactInline"){let we=ge.hasAttribute("data-artifact-inline")?ge:ge.querySelector("[data-artifact-inline]"),be=we?.getAttribute("data-artifact-inline")??"",Vo=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(be):be,ht=be?r.querySelector(`#wrapper-${M.id}`)?.querySelector(`[data-artifact-inline="${Vo}"]`)??null:null;we&&ht&&ht!==we&&yo()?.hasLiveInlineArtifactBlock(ht)&&(we===ge?ge=ht:we.replaceWith(ht))}if(ge)if(Mt){let we=document.createElement("div");if(we.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),we.id=`bubble-${M.id}`,we.setAttribute("data-message-id",M.id),M.content&&M.content.trim()){let be=document.createElement("div");be.className="persona-mb-3 persona-text-sm persona-leading-relaxed",be.innerHTML=d({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),we.appendChild(be)}we.appendChild(ge),qe=we}else{let we=document.createElement("div");if(we.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",we.id=`bubble-${M.id}`,we.setAttribute("data-message-id",M.id),we.setAttribute("data-persona-component-directive","true"),M.content&&M.content.trim()){let be=document.createElement("div");be.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",be.innerHTML=d({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),we.appendChild(be)}we.appendChild(ge),qe=we}}if(qe||wt!=null){let ge=ro(M.id,M.role);ge.setAttribute("data-component-directive-stub","true"),ge.setAttribute("data-preserve-runtime","true"),f.appendChild(ge),He.push({messageId:M.id,fingerprint:At,bubble:qe});return}}}if(!ut)if(M.variant==="reasoning"&&M.reasoning){if(!Is)return;ut=Tp(M,o,i)}else if(M.variant==="tool"&&M.toolCall){if(!Hs)return;ut=Ip(M,o,s)}else if(M.variant==="approval"&&M.approval){if(o.approval===!1)return;let ye=O();if(!ye)return;ut=ye.createApprovalBubble(M,o,c)}else{let ye=o.layout?.messages;ye?.renderUserMessage&&M.role==="user"?ut=ye.renderUserMessage({message:M,config:o,streaming:!!M.streaming}):ye?.renderAssistantMessage&&M.role==="assistant"?ut=ye.renderAssistantMessage({message:M,config:o,streaming:!!M.streaming}):ut=hp(M,d,ye,o.messageActions,Wr,{loadingIndicatorRenderer:D,widgetConfig:o,actionEligibility:mt}),M.role!=="user"&&ut&&Q(ut,M,o,S)}let Qe=ro(M.id,M.role);Qe.appendChild(ut),ry(It,M.id,At,Qe),f.appendChild(Qe)}),Re.composerOverlay&&Re.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(me=>{let fe=me.getAttribute("data-persona-ask-sheet-for");fe&&!K.has(fe)&&xd(Re.composerOverlay,fe)}),o.features?.toolCallDisplay?.grouped){let M=[],me=[],fe=o.features.toolCallDisplay.groupedMode==="summary";a.forEach(U=>{if(U.variant==="tool"&&U.toolCall&&Hs){if(hn&&U.toolCall.status==="complete")return;me.push(U);return}U.variant==="reasoning"&&(!Is||U.reasoning?.status==="complete"&&$n(U.reasoning))||((me.length>1||fe&&me.length>0)&&M.push(me),me=[])}),(me.length>1||fe&&me.length>0)&&M.push(me),M.forEach(U=>{let Ue=U.map(ue=>Array.from(f.children).find(Qe=>Qe instanceof HTMLElement&&Qe.getAttribute("data-wrapper-id")===ue.id)).filter(ue=>!!ue);if(Ue.length<(fe?1:2))return;let mt=ro(`tool-group-${U[0].id}`,"assistant");if(mt.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let ue=`tool-group-${U[0].id}`,Qe=U.some(qe=>qe.toolCall?.status!=="complete"),ye={...U[0],id:ue,toolCall:{id:ue,name:`${U.length} tools`,status:Qe?"running":"complete",chunks:U.flatMap(qe=>qe.toolCall?.chunks??[]),success:!U.some(qe=>qe.toolCall?.success===!1)}};m.add(ue),l.observe(ye,"tool",s,o.features.toolCallDisplay);let wt=`${Qe?"Using":"Used"} ${U.length} tools`,bn=o.toolCall?.renderGroupedSummary?.({messages:U,toolCalls:U.map(qe=>qe.toolCall),defaultSummary:wt,config:o}),Mt=_f(ye,o,s.has(ue),bn??wt);Mt.bubble.classList.add("persona-tool-group"),Mt.body.dataset.personaToolGroupStack="true",Ue[0].before(mt),mt.appendChild(Mt.bubble),Ue.forEach((qe,ge)=>{qe.style.setProperty("--persona-message-row-max-width","100%"),qe.style.setProperty("--persona-activity-stagger",`${ge*40}ms`),qe.classList.add("persona-activity-group-child"),Mt.body.appendChild(qe)});return}let Bt=document.createElement("div");Bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Bt.setAttribute("data-persona-tool-group","true");let At=document.createElement("div");At.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",At.id=`tool-group-summary-${U[0].id}`;let Ye=`Called ${U.length} ${U.length===1?"tool":"tools"}`,ut=o.toolCall?.renderGroupedSummary?.({messages:U,toolCalls:U.map(ue=>ue.toolCall).filter(ue=>!!ue),defaultSummary:Ye,config:o});$(At,ut)||(At.textContent=Ye);let Ct=document.createElement("div");Ct.className="persona-tool-group-stack persona-flex persona-flex-col",Ct.id=`tool-group-stack-${U[0].id}`,Ct.setAttribute("data-persona-tool-group-stack","true"),Bt.appendChild(At),fe||Bt.appendChild(Ct),mt.appendChild(Bt),Ue[0].before(mt),Ue.forEach((ue,Qe)=>{if(fe){ue.remove();return}ue.style.setProperty("--persona-message-row-max-width","100%");let ye=document.createElement("div");ye.className="persona-tool-group-item persona-relative",ye.setAttribute("data-persona-tool-group-item","true"),Qe<Ue.length-1&&ye.setAttribute("data-persona-tool-group-connector","true"),ye.appendChild(ue),Ct.appendChild(ye)})})}l.prune(m),sy(It,F);let Fo=M=>M.variant==="tool"&&!Hs||M.variant==="reasoning"&&!Is||yn(M),zn=a.some(M=>M.role==="assistant"&&M.streaming&&!Fo(M)),kn=a.length-1;for(;kn>=0&&Fo(a[kn]);)kn--;let No=kn>=0?a[kn]:void 0,pi=kn<a.length-1,vr=No?.role==="assistant"&&!No.streaming&&No.variant!=="approval"&&!pi;if(on&&a.some(M=>M.role==="user")&&!zn&&!vr){let M={config:o,streaming:!0,location:"standalone",defaultRenderer:Bi},me=g.find(U=>U.renderLoadingIndicator),fe=null;if(me?.renderLoadingIndicator&&(fe=me.renderLoadingIndicator(M)),fe===null&&o.loadingIndicator?.render&&(fe=o.loadingIndicator.render(M)),fe===null&&(fe=Bi()),fe){let U=document.createElement("div"),Ue=o.loadingIndicator?.showBubble!==!1,mt=o.layout?.messages?.layout??"bubble";U.className=Ue?Di("assistant",mt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),U.setAttribute("data-typing-indicator","true"),Ue&&(U.style.color="var(--persona-message-assistant-text, var(--persona-text))",mt!=="flat"&&(U.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",U.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),U.appendChild(fe);let Bt=ro("typing-indicator","assistant");Bt.appendChild(U),f.appendChild(Bt)}}if(!on&&a.length>0){let M=a[a.length-1],me={config:o,lastMessage:M,messageCount:a.length},fe=g.find(Ue=>Ue.renderIdleIndicator),U=null;if(fe?.renderIdleIndicator&&(U=fe.renderIdleIndicator(me)),U===null&&o.loadingIndicator?.renderIdle&&(U=o.loadingIndicator.renderIdle(me)),U){let Ue=document.createElement("div"),mt=o.loadingIndicator?.showBubble!==!1;Ue.className=mt?["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(" "),Ue.setAttribute("data-idle-indicator","true"),Ue.appendChild(U);let Bt=ro("idle-indicator","assistant");Bt.appendChild(Ue),f.appendChild(Bt)}}if(Gf(f),Rl(r,f),Bd(r),ze){let{messageId:M,element:me}=ze,fe=r.querySelector(`#wrapper-${M}`);fe&&me.parentElement!==fe&&(Xs(fe,q.get(M)??"user"),fe.replaceChildren(me))}if(ae.length>0)for(let{messageId:M,fingerprint:me,bubble:fe}of ae){let U=r.querySelector(`#wrapper-${M}`);U&&(Xs(U,q.get(M)??"assistant"),fe!==null&&(U.replaceChildren(fe),U.setAttribute("data-bubble-fp",me),Vr.set(M,me)))}if(Vr.size>0)for(let M of Vr.keys())F.has(M)||Vr.delete(M);if(He.length>0)for(let{messageId:M,fingerprint:me,bubble:fe}of He){let U=r.querySelector(`#wrapper-${M}`);U&&(Xs(U,q.get(M)??"assistant"),fe!==null&&(U.replaceChildren(fe),U.setAttribute("data-bubble-fp",me),ir.set(M,me)))}if(ir.size>0)for(let M of ir.keys())F.has(M)||ir.delete(M);if(Gt.length>0)for(let{messageId:M,fingerprint:me,bubble:fe}of Gt){let U=r.querySelector(`#wrapper-${M}`);U&&(Xs(U,q.get(M)??"assistant"),fe!==null&&(U.replaceChildren(fe),U.setAttribute("data-bubble-fp",me),To.set(M,me)))}if(To.size>0)for(let M of To.keys())F.has(M)||To.delete(M)},Wc=!1,Sa=()=>{Wc||(Wc=!0,Tr().catch(()=>{}),Om().catch(()=>{Wc=!1}))},un=(r,a,d)=>{a.length>0&&Sa(),Mv(r,a,d),Lu()},Js=null,Ev=()=>{if(Js)return;let r=d=>{let m=d.composedPath();m.includes(Pe)||St&&m.includes(St)||Ge(!1,"user")};Js=r,(t.ownerDocument??document).addEventListener("pointerdown",r,!0)},gg=()=>{if(!Js)return;(t.ownerDocument??document).removeEventListener("pointerdown",Js,!0),Js=null};oe.push(()=>gg());let Zs=null,Tv=()=>{if(Zs)return;let r=d=>{d.key==="Escape"&&(d.isComposing||Ge(!1,"user"))};Zs=r,(t.ownerDocument??document).addEventListener("keydown",r,!0)},mg=()=>{if(!Zs)return;(t.ownerDocument??document).removeEventListener("keydown",Zs,!0),Zs=null};oe.push(()=>mg());let ei=!1,fg=new Set,kv=()=>{let r=o.launcher?.composerBar?.peek?.streamAnimation;return r||o.features?.streamAnimation},Yr=()=>{if(!Ae())return;let r=Re.peekBanner,a=Re.peekTextNode;if(!r||!a)return;if(Se){r.classList.remove("persona-pill-peek--visible");return}let d=S?.getMessages()??[],m;for(let nt=d.length-1;nt>=0;nt--){let it=d[nt];if(it.role==="assistant"&&it.content){m=it;break}}if(!m){r.classList.remove("persona-pill-peek--visible");return}let f=m.content,b=!!m.streaming,D=kv(),$=cl(D),F=$.type!=="none"?Sc($.type,D?.plugins):null,q=F?.isAnimating?.(m)===!0,K=F!==null&&(b||q);K&&F&&!fg.has(F.name)&&(yi(F,t),fg.add(F.name));let X=K&&F?.containerClass?F.containerClass:null,ae=a.dataset.personaPeekStreamClass??null;ae&&ae!==X&&(a.classList.remove(ae),delete a.dataset.personaPeekStreamClass),X&&ae!==X&&(a.classList.add(X),a.dataset.personaPeekStreamClass=X),K?(a.style.setProperty("--persona-stream-step",`${$.speed}ms`),a.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(a.style.removeProperty("--persona-stream-step"),a.style.removeProperty("--persona-stream-duration"));let He=K?dl(f,$.buffer,F,m,b):f;if(K&&$.placeholder==="skeleton"&&b&&(!He||!He.trim())){let nt=document.createElement("div"),it=hi();it.classList.add("persona-pill-peek__skeleton"),nt.appendChild(it),Rl(a,nt)}else{let nt=Math.max(0,He.length-100),it=He.length>100?He.slice(-100):He,Ft=ja(it);if(!K||!F){let pt=He.length>100?`\u2026${it}`:it;a.textContent!==pt&&(a.textContent=pt)}else{let pt=Ft;(F.wrap==="char"||F.wrap==="word")&&(pt=fi(Ft,F.wrap,`peek-${m.id}`,{skipTags:F.skipTags,startIndex:nt}));let ze=document.createElement("div");if(ze.innerHTML=pt,F.useCaret&&it.length>0){let Vn=pl(),$n=ze.querySelectorAll(".persona-stream-char, .persona-stream-word"),hn=$n[$n.length-1];hn?.parentNode?hn.parentNode.insertBefore(Vn,hn.nextSibling):ze.appendChild(Vn)}Rl(a,ze),F.onAfterRender?.({container:a,bubble:r,messageId:m.id,message:m,speed:$.speed,duration:$.duration})}}let Gt=on||ei;r.classList.toggle("persona-pill-peek--visible",Gt)};if(Ae()){let r=Re.peekBanner;if(r){let m=f=>{f.preventDefault(),f.stopPropagation(),Ge(!0,"user")};r.addEventListener("pointerdown",m),oe.push(()=>{r.removeEventListener("pointerdown",m)})}let a=()=>{ei||(ei=!0,Yr())},d=()=>{ei&&(ei=!1,Yr())};le.addEventListener("pointerenter",a),le.addEventListener("pointerleave",d),oe.push(()=>{le.removeEventListener("pointerenter",a),le.removeEventListener("pointerleave",d)}),St&&(St.addEventListener("pointerenter",a),St.addEventListener("pointerleave",d),oe.push(()=>{St.removeEventListener("pointerenter",a),St.removeEventListener("pointerleave",d)}))}let Pv=r=>{let a=o.launcher?.composerBar??{},d=a.expandedSize??"anchored",m=a.bottomOffset??"16px",f=a.collapsedMaxWidth,b=a.expandedMaxWidth??"880px",D=a.expandedTopOffset??"5vh",$=a.modalMaxWidth??"880px",F=a.modalMaxHeight??"min(90vh, 800px)",q="calc(100vw - 32px)",K="var(--persona-pill-area-height, 80px)",X=Pe.style;if(X.left="",X.right="",X.top="",X.bottom="",X.transform="",X.width="",X.maxWidth="",X.height="",X.maxHeight="",St){let ae=St.style;ae.bottom=m,ae.width=f??""}if(r&&d!=="fullscreen"){if(d==="modal"){X.top="50%",X.left="50%",X.transform="translate(-50%, -50%)",X.bottom="auto",X.right="auto",X.width=$,X.maxWidth=q,X.maxHeight=F,X.height=F;return}X.left="50%",X.transform="translateX(-50%)",X.bottom=`calc(${m} + ${K})`,X.top=D,X.width=b,X.maxWidth=q}},ti=()=>{if(Se&&Sa(),!Ve())return;if(Ae()){let q=(o.launcher?.composerBar??{}).expandedSize??"anchored",K=Se?"expanded":"collapsed";Pe.dataset.state=K,Pe.dataset.expandedSize=q,St&&(St.dataset.state=K,St.dataset.expandedSize=q),Pe.style.removeProperty("display"),Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Pv(Se),re.style.display=Se?"flex":"none",er(),Se?(Ev(),Tv()):(gg(),mg()),Yr();return}let r=rt(o),a=t.ownerDocument.defaultView??window,d=o.launcher?.mobileBreakpoint??640,m=o.launcher?.mobileFullscreen??!0,f=a.innerWidth<=d,b=m&&f&&de,D=Cn(o).reveal;Se?(Pe.style.removeProperty("display"),Pe.style.display=r?"flex":"",Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0"),le.classList.add("persona-scale-100","persona-opacity-100"),ct?(ct.setPanelOpen(!0),ct.element.style.display="none"):_t&&(_t.style.display="none")):(r?r&&(D==="overlay"||D==="push")&&!b?(Pe.style.removeProperty("display"),Pe.style.display="flex",Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Pe.style.setProperty("display","none","important"),Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Pe.style.display="",Pe.classList.add("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100"),le.classList.add("persona-scale-95","persona-opacity-0")),ct?(ct.setPanelOpen(!1),ct.element.style.display=r?"none":""):_t&&(_t.style.display=r?"none":""))},Ge=(r,a="user")=>{if(!Ve()||Se===r)return;let d=Se;Se=r,ti();let m=(()=>{let b=o.launcher?.sidebarMode??!1,D=t.ownerDocument.defaultView??window,$=o.launcher?.mobileFullscreen??!0,F=o.launcher?.mobileBreakpoint??640,q=D.innerWidth<=F,K=rt(o)&&$&&q,X=Ae()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return b||$&&q&&de||K||X})();if(Se&&m){if(!Bn){let b=t.getRootNode(),D=b instanceof ShadowRoot?b.host:t.closest(".persona-host");D&&(Bn=ap(D,o.launcher?.zIndex??Dt))}Dn||(Dn=lp(t.ownerDocument))}else Se||(Bn?.(),Bn=null,Dn?.(),Dn=null);Se&&(li(),Hc()||(nn()==="follow"?Ho(!0):Ic()));let f={open:Se,source:a,timestamp:Date.now()};Se&&!d?G.emit("widget:opened",f):!Se&&d&&G.emit("widget:closed",f),G.emit("widget:state",{open:Se,launcherEnabled:de,voiceActive:Ie.active,streaming:S.isStreaming()})},Ro={inputDisabled:!1,sendDisabled:!1},_n=()=>Ro.inputDisabled,Bc=()=>Nt(o.voiceRecognition?.provider)&&!!S&&(S.isBargeInActive()||["listening","processing","speaking"].includes(S.getVoiceStatus())),fr=()=>Ro.inputDisabled||Ro.sendDisabled,Lv=()=>(Ro.inputDisabled?Ro.inputReason:void 0)??(Ro.sendDisabled?Ro.sendReason:void 0);function Dc(){if(!pe)return;if(ie.getState().phase==="streaming"){pe.disabled=!1;return}let r=_e?!_e.isReady():!1;pe.disabled=fr()||r}function xa(){if(!Hn)return;let r=ie.getState(),a=o.sendButton?.visibility==="when-text"&&r.phase!=="streaming"&&r.text.trim().length===0&&r.attachments.length===0;Hn.toggleAttribute("data-persona-send-hidden",a)}function Iv(){let r=Lv();if(Ae()){let a=Ut??Le;r?a.setAttribute("title",r):a.removeAttribute("title"),Le.toggleAttribute(Ts,!!r);return}if(r){We.setAttribute("role","status"),We.setAttribute("aria-live","polite"),We.setAttribute(Ts,""),We.textContent=r,ui(We,o.statusIndicator??{},"idle");return}if(We.hasAttribute(Ts)&&(We.removeAttribute("role"),We.removeAttribute("aria-live"),We.removeAttribute(Ts),C)){let a=S.getStatus();Ws(We,Jl(a),o.statusIndicator??{},a)}}function Oc(){let r=Pd(o.composer?.inputDisabled),a=Pd(o.composer?.sendDisabled);Ro={inputDisabled:r.disabled,inputReason:r.reason,sendDisabled:a.disabled,sendReason:a.reason},ie.setInputDisabled(r.disabled),ie.setSendDisabled(a.disabled);let d=ie.getState().phase==="streaming",m=r.disabled,f=d||m;Z&&(Z instanceof HTMLTextAreaElement?Z.disabled=m:Z.setAttribute("contenteditable",m?"false":"true"),Z.setAttribute("aria-disabled",m?"true":"false")),st&&(st.disabled=m),et&&(et.disabled=m);for(let b of lt?.affordanceButtons??[])b.querySelectorAll("button").forEach(D=>{D.disabled=m});te&&(te.disabled=m||d&&!Bc()),nr.forEach(b=>{b.elements.forEach(D=>{D.toggleAttribute("data-disabled",f),D instanceof HTMLButtonElement||D.setAttribute("aria-disabled",f?"true":"false")}),b.buttons.forEach(D=>{D.disabled=f})}),zc.forEach(b=>{b.toggleAttribute("data-disabled",f),b instanceof HTMLButtonElement?b.disabled=f:b.setAttribute("aria-disabled",f?"true":"false"),b.querySelectorAll("button").forEach(D=>{D.disabled=f})}),Le.dataset.personaComposerStreaming=d?"true":"false",Le.dataset.personaComposerInputDisabled=m?"true":"false",Le.dataset.personaComposerSendDisabled=fr()?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(b=>{(b instanceof HTMLButtonElement||b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement||b instanceof HTMLSelectElement)&&(b.disabled=d)}),Dc(),Iv()}let ni=r=>{ie.setStreaming(r),lu(r?"stop":"send"),Oc()},Aa=()=>{Ie.active||Z&&Z.focus()};G.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Aa(),200)});let hg=null,_c=!1,Fc=!xt.hidden,Wo=null,Nc=!z,Ma=null;oe.push(()=>{Ma?.cancel(),Ma=null});let Hv=r=>{let a=Ay(r);if(a===Qi)return;Qi=a,t.setAttribute("data-persona-conversation-state",a);let d=oc();Ji(),Nc&&(Ma?.cancel(),Ma=Sy(Le,a==="active"?d:oc(),a==="active"?"drop":"rise",Xo().layout==="centered"?320:260)),Gr()},yg=null,bg,vg=null,Qr=null,Vc=!1,oi=r=>{let a=Xo(),d=`${a.variant}|${a.layout}|${a.dismiss}|${a.anchor??"bottom"}|${a.align??""}|${a.iconPlacement}|${a.kicker??""}|${a.title}|${a.subtitle}`;(d!==yg||a.icon!==bg)&&(yg=d,bg=a.icon,Fl({host:xt,iconHolder:Bb,kicker:Db,title:Ob,subtitle:_b,starterSuggestions:Zl},a));let m=a.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${a.message}`;m!==vg&&(vg=m,Nl(en,a.message,o));let f=r??(S?S.getMessages():o.initialMessages);Hv(f);let b=_c,D=!b&&Ss(a,f),$=D!==Fc;if(Fc=D,Qr){Wo?.cancel(),Wo=null,b!==Vc&&(Vc=b,b?vp(j,xt,null):bp(j,xt,Qr)),ws(j,xt,!b);return}if($&&!D&&!b&&a.dismiss==="on-first-message"&&Nc){Wo=wy(xt,q=>{Wo===q&&(Wo=null),!Fc&&!Qr&&(ws(j,xt,!1),Gr()),q?.cancel()});return}if(Wo){if(!D&&!b)return;Wo.cancel(),Wo=null}let F=!xt.hidden;ws(j,xt,D),!D&&F&&Gr()},$c=[],zc=[],Uc=!1,Cg=null,wg,Sg=()=>{zc.length=0;let r=$c.splice(0,$c.length);for(let a of r)try{a()}catch(d){console.warn("[persona] renderWelcome cleanup threw",d)}};oe.push(Sg);let Rv=(r,a)=>{let d=dp(r,a);if(!d)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),P("span");let m=o.suggestions?.starters,f=pp({item:{...d,behavior:d.behavior??m?.behavior??"send"},index:a,surface:"starter",source:"config",variant:m?.variant??"card",streaming:C?S.isStreaming():!1,config:o,plugins:g,chipsConfig:o.suggestionChipsConfig,session:S,getTextarea:()=>Z,eventTarget:xt,submitPrompt:Ra});return zc.push(f),f},qc=()=>{if(Uc)return;Uc=!0;let r=Xo();Cg=`${r.variant}|${r.layout}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`,wg=r.icon;try{Sg(),vp(j,xt,Qr),Qr=null,Vc=!1;let a=S?S.getMessages():o.initialMessages,d=Ss(r,a),m=0,f=null;for(let b of g)if(b.renderWelcome&&(f=b.renderWelcome({config:r,variant:r.variant,visible:d,defaultRenderer:()=>xt,sendMessage:D=>{if(!S||S.isStreaming())return;let $=D.trim();$&&S.sendMessage($)},requestRender:()=>qc(),renderStarter:D=>Rv(D,m++),storage:E(b.id),onCleanup:D=>{$c.push(D)}}),f))break;f&&f!==xt&&(Qr=f,bp(j,xt,f))}finally{Uc=!1}oi()},Wv=()=>{let r=Xo();`${r.variant}|${r.layout}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`===Cg&&r.icon===wg||qc()},Ea=()=>{oi(),Fr||(Z.placeholder=Hh(ie.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!S?.isStreaming()&&(pe.textContent=o.copy?.sendButtonLabel??"Send")),Z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Z.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Bv=!!o.setStoredConversationId,Xr=r=>$e(a=>{let d={...a};return delete d[r],d}),Ta=r=>{let a=x[r];return typeof a=="string"?a:null},xg=()=>{let r=x.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:()=>Ta("sessionId"),setStoredSessionId:r=>{$e(a=>({...a,sessionId:r}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Xr("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ta("conversationId")),setStoredConversationId:o.setStoredConversationId??(r=>{$e(a=>({...a,conversationId:r}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Xr("conversationId"))});let Ag=()=>o.clientToken??null,Mg=r=>ib(r,$i(),o.persistState===!1),Eg=Ag(),gn=Eg?Mg(Eg):null,Dv=()=>{let r=x.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")}},Bo={...gn?{visitorStore:gn}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!jl()?Promise.all([ee,he]).then(()=>{}):ee,getStoredMessageCursor:()=>Ta("historyMessageCursor"),setStoredMessageCursor:r=>{if(r===null){Xr("historyMessageCursor");return}$e(a=>({...a,historyMessageCursor:r}))},getPendingDisplayProjections:Dv,setPendingDisplayProjections:r=>{if(!r){Xr("pendingDisplayProjections");return}$e(a=>({...a,pendingDisplayProjections:r}))},getStoredResumableHandle:xg,setStoredResumableHandle:r=>{if(!r){Xr("durableResume");return}$e(a=>({...a,durableResume:r}))},shouldResumeDurableConversation:()=>T&&xg()!==null,...Bv?{}:{getStoredConversationRevision:()=>Ta("conversationRevision"),setStoredConversationRevision:r=>{if(r===null){Xr("conversationRevision");return}$e(a=>({...a,conversationRevision:r}))}}};if(T){let r=o.onExecutionState,a=t.ownerDocument.defaultView,d=!1,m=()=>d=!0,f=()=>d=!1;a?.addEventListener("pagehide",m),a?.addEventListener("pageshow",f),oe.push(()=>{a?.removeEventListener("pagehide",m),a?.removeEventListener("pageshow",f)}),o={...o,reconnectStream:o.reconnectStream??(b=>S.getClient().reconnectClientTokenStream(b)),onExecutionState:b=>{(b||!d)&&Bo.setStoredResumableHandle?.(b?{executionId:b.executionId,after:b.lastEventId}:null),r?.(b)}}}let Ov=()=>{let r=Ag();if(r&&gn?.matches(r,$i(),o.persistState===!1)||!r&&!gn)return;gn?.destroy(),gn=r?Mg(r):null;let a={...Bo};gn?a.visitorStore=gn:delete a.visitorStore,Bo=a,S.setHistoryInternals(Bo)},hr=null,_v=()=>{hr==null&&(hr=setInterval(()=>{let r=ce.querySelectorAll("[data-tool-elapsed]");if(r.length===0){clearInterval(hr),hr=null;return}let a=Date.now();r.forEach(d=>{let m=Number(d.getAttribute("data-tool-elapsed"));m&&(d.textContent=d.closest(".persona-activity-row")?bi(a-m):Km(a-m))})},100))},jc=(r,a)=>{if(Object.is(r,a))return!0;if(r===null||a===null||typeof r!="object"||typeof a!="object")return!1;if(Array.isArray(r)||Array.isArray(a))return!Array.isArray(r)||!Array.isArray(a)||r.length!==a.length?!1:r.every((D,$)=>jc(D,a[$]));let d=r,m=a,f=Object.keys(d),b=Object.keys(m);return f.length===b.length&&f.every(D=>Object.prototype.hasOwnProperty.call(m,D)&&jc(d[D],m[D]))},Tg=r=>{let{content:a,rawContent:d,llmContent:m,...f}=r;return f},Kc=r=>r.role==="assistant"&&r.streaming===!0&&!r.variant&&!r.toolCall&&!r.tools&&!r.approval&&!r.reasoning&&!r.contentParts&&!r.stopReason&&!qp(r),Fv=(r,a,d)=>{if(r.length!==a.length)return!1;let m=r[d.index],f=a[d.index];return!m||!f||m.id!==d.id||f.id!==d.id?!1:(!Object.is(m.content,f.content)||!Object.is(m.rawContent,f.rawContent)||!Object.is(m.llmContent,f.llmContent))&&Kc(m)&&Kc(f)&&jc(Tg(m),Tg(f))},ka=null,Jr=null,yr=null,so=null,Gc=null,Nv=r=>{if(!T)return Ur(r);Gc=r,queueMicrotask(()=>{Gc===r&&(Gc=null,Ur(r))})},Pa=r=>{ka=r;let a,d;Jr=null;for(let f=r.length-1;f>=0;f-=1){let b=r[f];if(!a&&b.role==="user"&&(a=b),!d&&b.role==="assistant"&&(d=b),!Jr&&Kc(b)&&(Jr={index:f,id:b.id}),a&&d&&Jr)break}un(ce,r,Xt),yo()?.updateInlineArtifactBlocks(ce,dn.artifacts,{suppressTransition:on}),_v(),oi(r),sr(r),Ho(!on),Av(r),r.length===0&&(mr(),Ys=!0,ua=!1,zr=null,ga=!1),!xc||$r?(xc=!0,pr=a?.id??null,Ac=d?.id??null):a&&a.id!==pr?(pr=a.id,vv(a.id)):d&&d.id!==Ac&&Cv(),d&&(Ac=d.id),xv(r);let m=Ie.lastUserMessageId;a&&a.id!==m&&(Ie.lastUserMessageId=a.id,G.emit("user:message",a)),Ie.lastUserMessageWasVoice=!!a?.viaVoice,Nv(r),Yr()},Yc=()=>{so!==null&&(cancelAnimationFrame(so),so=null);let r=yr;yr=null,r&&Pa(r)},kg=()=>{so!==null&&cancelAnimationFrame(so),so=null,yr=null},Vv=r=>{let a=yr??ka;if(on&&a&&Jr&&Fv(a,r,Jr)){yr=r,so===null&&(so=requestAnimationFrame(()=>{so=null;let d=yr;yr=null,d&&Pa(d)}));return}if(r.length===0){kg(),Pa(r);return}Yc(),Pa(r)};S=new Sl(o,{onMessagesChanged(r){Vv(r)},onStatusChanged(r){let a=o.statusIndicator??{};Ws(We,(m=>m==="idle"?a.idleText??gt.idle:m==="connecting"?a.connectingText??gt.connecting:m==="connected"?a.connectedText??gt.connected:m==="error"?a.errorText??gt.error:m==="paused"?a.pausedText??gt.paused:m==="resuming"?a.resumingText??gt.resuming:gt[m])(r),a,r),Ki()},onStreamingChanged(r){r||(S?.getMessages().length===0?kg():Yc()),on=r,ni(r),Ki(),S&&un(ce,S.getMessages(),Xt),r||(Ho(!0),yv(),Zu=!0,S&&eg(S.getMessages(),ds(o))),Ht(),Ns(r?"Responding\u2026":"Response complete."),Yr()},onVoiceStatusChanged(r){if(G.emit("voice:status",{status:r,timestamp:Date.now()}),!(r!=="disconnected"&&!Nt(o.voiceRecognition?.provider)))switch(r){case"listening":if(!Ec){let a=S.getVoiceDisclosure();a&&(Ec=!0,Ae()?(ma=Z.placeholder,Z.placeholder=a,Ns(a)):Fg(a,1e4))}lo(),ns();break;case"processing":lo(),dC();break;case"speaking":lo(),pC();break;default:r==="idle"&&S.isBargeInActive()?(lo(),ns(),te?.setAttribute("aria-label","End voice session")):(Ie.active=!1,Ec=!1,ma!==null&&(Z.placeholder=ma,ma=null),lo(),oo("system"),Tn());break}},onArtifactsState(r){dn=r,r.artifacts.length===0&&(Nr=!1),yo()?.updateInlineArtifactBlocks(ce,r.artifacts,{suppressTransition:on}),En(),Ur()},onHistoryStateChanged(r){iu(r)},onHistoryNotice(r){au(r)},onReconnect(r){let{executionId:a,lastEventId:d}=r.handle;r.phase==="paused"?G.emit("stream:paused",{executionId:a,after:d}):r.phase==="resuming"?G.emit("stream:resuming",{executionId:a,after:d,attempt:r.attempt??1}):G.emit("stream:resumed",{executionId:a,after:d})}},Bo),pn.current=S,oe.push(()=>S.cancel()),oe.push(()=>{S.destroy(),gn?.destroy(),gn=null});let Qc=null;if(S.onReadAloudChange((r,a)=>{ku=r,Pu=a,Lu();let d=r??Qc;r&&(Qc=r);let m=d?S.getMessages().find(f=>f.id===d)??null:null;G.emit("message:read-aloud",{messageId:d,message:m,state:a,timestamp:Date.now()}),a==="idle"&&(Qc=null)}),C=!0,xc=!0,o.voiceRecognition?.enabled===!0&&Nt(o.voiceRecognition.provider))try{S.setupVoice()}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",r)}let tt=null,Xc=null,Pg=!1,Lg=S.getHistoryState(),ri=()=>o.features?.history?.enabled===!0,Ig=r=>{r&&(Qn.textContent="",Qn.textContent=r)},Jc=()=>{h.forEach(d=>d()),h=[];let r=tt,a=r?.railCollapseShortcut();r&&a&&h.push(y.register({id:"history-rail-collapse",combo:a.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Rs&&Ui==="rail"&&r.railCollapsible()||r.railTriggerApplies(),run:()=>r.railOverlayMode()?r.toggleRailPinned():r.toggleRailCollapsed()}));for(let d of o.layout?.header?.trailingActions??[])d.shortcut&&h.push(y.register({id:`header-action-${d.id}`,combo:d.shortcut,run:()=>{let m=t.querySelector(`[data-persona-header-action="${d.id}"]`);m?m.click():o.layout?.header?.onAction?.(d.id)}}));for(let d of g)for(let m of d.shortcuts??[])h.push(y.register({...m,id:`${d.id}:${m.id}`}))};Jc();let La=null,Hg=!1,si=()=>{if(!So)return;let r=o.layout?.header?.titleSource==="conversation",a=r&&La?.trim()||null;So.textContent=a??o.launcher?.title??"Chat Assistant";let d=So.closest(".persona-combo-btn");if(!d)return;let m=!r||S.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 f=d.querySelector("svg");f&&(f.style.display=m?"":"none")},$v=r=>{r!==La&&(La=r,si())},zv=r=>{Hg=r?.starred===!0,$v(r&&r.title.trim()||null),si()};si(),re.addEventListener("persona:title-menu-builtin",r=>{let a=r.detail?.actionId,d=S.getActiveConversationId();d&&(a==="delete"?Fn(m=>m.requestDeleteConversation(d)):a==="star"&&S.canUpdateConversations()&&Fn(m=>m.updateHistoryConversation(d,{starred:!Hg})).catch(()=>{}))}),iu=r=>{Lg=r,tt?.historySurface?.view.setNewConversationRequired(r.recovery==="new_conversation_required"),ni(r.sendBlocked||on),tt?.syncEarlierMessagesPill()},au=r=>{(r.code==="history_continuity_reset"||r.code==="conversation_deleted_recovered")&&(It.clear(),mr(),On()),Ig(r.message),tt?.historySurface?.view.refresh()};let Uv={get actionManager(){return Me},get activeConversationTitle(){return La},announceHistory:Ig,get applyRailChrome(){return ji},set applyRailChrome(r){ji=r},get artifactSplitRoot(){return Zn},get body(){return j},get config(){return o},get container(){return re},get conversationOpenPendingEl(){return hg},set conversationOpenPendingEl(r){hg=r},get conversationOpenTakeover(){return _c},set conversationOpenTakeover(r){_c=r},currentKeyPrefix:$i,destroyCallbacks:oe,eventBus:G,get footer(){return Le},get header(){return Ke},get historyChromeSync(){return Ki},set historyChromeSync(r){Ki=r},historyFeatureEnabled:ri,get historyInternals(){return Bo},set historyInternals(r){Bo=r},get historyPresentation(){return Ui},set historyPresentation(r){Ui=r},get historySessionState(){return Lg},get historyVisible(){return Rs},set historyVisible(r){Rs=r},get isStreaming(){return on},jumpToBottomInstant:Ic,get lastAppliedMessages(){return ka},set lastAppliedMessages(r){ka=r},get launcherEnabled(){return de},get launcherSurfaceInstance(){return ct},maybeFocusInput:Aa,messageCache:It,get messagesWrapper(){return ce},mount:t,get open(){return Se},panel:le,panelElements:Re,get persistentMetadata(){return x},set persistentMetadata(r){x=r},plugins:g,get reapplyHistoryHostChrome(){return qi},set reapplyHistoryHostChrome(r){qi=r},repinAnchoredMessage:Gr,resetAnchorState:mr,restoreScrollPosition:Hc,resumeAutoScroll:On,runStorageMutation:ha,get session(){return S},setActiveConversationSummary:zv,storageAdapter:v,get suppressScrollSend(){return $r},set suppressScrollSend(r){$r=r},syncScrollToBottomButton:Ht,updateWelcome:oi,getHistoryProviderFactory:cb,historyErrors:{HistoryClientError:bt,HistoryProviderError:el},isDockedMountMode:rt,renderLucideIcon:se,loadHistoryView:ab,createHeaderIconButton:bs,attachTooltip:vn},Zc=r=>(!tt&&!Pg&&(tt=r.createHistoryShell(Uv),tt.railCollapseShortcut()&&Jc()),tt),ed=()=>{if(tt)return Promise.resolve(tt);let r=jl();return r?Promise.resolve(Zc(r)):(Xc??=lb().then(Zc,a=>{throw Xc=null,a}),Xc)},Fn=r=>{let a=jl(),d=tt??(a?Zc(a):null);return d?r(d):ed().then(m=>{if(!m)throw new Error("[AgentWidget] The widget was destroyed");return r(m)})},Ia=()=>{tt?.syncHistoryPresentation()};oe.push(()=>{Pg=!0}),ri()&&ed().catch(()=>{}).finally(ne),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&S.initClientSession().then(()=>{let r=tt;if(r?.historyAvailable())return S.reconcileBootConversation({scope:r.historyScope()})}).then(()=>{tt?.syncEarlierMessagesPill()}).catch(r=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",r)});let td=()=>S.warmClientSession(),Rg=r=>{let a=o.sessionInit??"input",d=Be?.input??Z,m=r.target;d&&(r.type==="input"?(a==="input"||a==="focus")&&m===d&&r.inputType&&d.value.trim():a==="focus"&&(r.type==="keyup"?m===d&&r.key==="Tab":(Be?.form??Ut)?.contains(m)))&&td()},Wg=["input","pointerdown","keyup"];Wg.forEach(r=>t.addEventListener(r,Rg));let Bg,nd,Dg=()=>{let r=nd;nd=void 0;try{typeof r=="function"&&r()}catch{}},Og=()=>{let r=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(r!==Bg){Dg(),Bg=r;try{nd=r?.({warm:td,mount:t})}catch{}}};Og(),oe.push(()=>{Wg.forEach(r=>t.removeEventListener(r,Rg)),Dg()}),(Jt||o.onSSEEvent)&&S.setSSEEventCallback((r,a)=>{o.onSSEEvent?.(r,a),Xl(r,a)});let _g=()=>{let r=o.resume??(T?Bo.getStoredResumableHandle?.():null);r&&typeof o.reconnectStream=="function"&&S.resumeFromHandle(r)};z?z.then(r=>{if(r){if(r.metadata&&(x=jp(r.metadata),Me.syncFromMetadata()),r.messages?.length){$r=!0;try{S.hydrateMessages(r.messages)}finally{$r=!1}Sa()}r.artifacts?.length&&S.hydrateArtifacts(r.artifacts,r.selectedArtifactId??null),ig(r.draft)}}).catch(r=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",r)}).finally(()=>{Nc=!0,W(),_g()}):(ig(ve),_g());let qv=()=>{!Ae()||Se||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Ge(!0,"auto")},jv=(r,a)=>r?a?{refs:[...r.refs,...a.refs],finalize:async()=>{let[d,m]=await Promise.allSettled([r.finalize(),a.finalize()]),f=[];return d.status==="fulfilled"?f.push(d.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",d.reason),m.status==="fulfilled"?f.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),nA(f)}}:r:a,od=()=>{let a=Z.getInlineMessageFields?.();return a&&a.contentSegments.some(m=>m.kind==="mention")?a.contentSegments:void 0},io=!1,br=null,Ha=()=>{Z.value="",Z.style.height="auto",Rn(),ai()},rd="data-persona-composer-notice",Zr=null;function Fg(r,a=4e3){Ns(r),!(Ae()||!We)&&(We.hasAttribute(Ts)||(We.setAttribute(rd,""),We.setAttribute("role","status"),We.setAttribute("aria-live","polite"),We.textContent=r,ui(We,o.statusIndicator??{},"idle"),Zr&&clearTimeout(Zr),Zr=setTimeout(()=>{if(Zr=null,!!We?.hasAttribute(rd)&&(We.removeAttribute(rd),We.removeAttribute("role"),We.removeAttribute("aria-live"),C)){let d=S.getStatus();Ws(We,Jl(d),o.statusIndicator??{},d)}},a)))}function Kv(){let r=ie.getState().pendingSubmission;r&&(Or(void 0),Z&&(Z.value=r.text,Z.dispatchEvent(new Event("input",{bubbles:!0})),Rn()),r.options.selectedModelId&&(ie.setSelectedModelId(r.options.selectedModelId),Ao?.repaint()),r.options.activeModeIds?.length&&Zi(r.options.activeModeIds),r.options.quote&&Wn(r.options.quote),Z?.focus())}let Gv=r=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",r)},Ng=(r={})=>{let a=(r.overrideText??Z?.value??"").trim();return r.resolveInlineCommand&&a?(lt?.takeInlineCommand(a)??Promise.resolve(null)).then(d=>Vg(r,a,d)):Vg(r,a,null)},Vg=(r,a,d)=>{if(d?.kind==="action"){Ha(),lt?.clear(),Zo();return}let m=d?.kind==="server"?d.mentions:null,f=d?.kind==="prompt"?d.sendText:a,b=r.pending?.contentParts,D=(_e?.hasAttachments()??!1)||(b?.length??0)>0;if(!Uh({text:f,hasAttachments:D,attachmentsReady:_e?.isReady()??!0,hasMentions:lt?.hasMentions()??!1,hasServerMentions:!!m,inputDisabled:_n(),sendDisabled:fr()}))return;let $=S.isStreaming()?ac():"block";if($==="defer-one"&&!r.pending){if(ie.getState().pendingSubmission){Fg("One message is already queued. Edit or remove it first.");return}Yv({intent:r,sendText:f,serverMentions:m});return}let F={text:f,mentionRefs:[...lt?.getMentionRefs()??[],...m?.refs??[]],contentSegments:d?.kind==="prompt"?void 0:od(),options:{...ie.getState().selectedModelId&&{selectedModelId:ie.getState().selectedModelId},...ie.getState().activeModeIds.length>0&&{activeModeIds:[...ie.getState().activeModeIds]},...ie.getState().quote&&{quote:{...ie.getState().quote}}},viaVoice:r.viaVoice};r.pending&&(F.options={...r.pending.options},F.contentSegments=r.pending.contentSegments,F.mentionRefs=[...r.pending.mentionRefs],F.viaVoice=r.pending.viaVoice);let q=()=>{if(b?.length)return[...b];if(!_e?.hasAttachments())return;let De=[..._e.getContentParts()];return F.text&&De.push(zo(F.text)),De};F.contentParts=q();let K=()=>{lr(),qv();let De=lt?.collectForSubmit()??null,Gt=jv(De,m),nt=q();r.consumeDraft!==!1&&Ha();let it={selectedModelId:F.options.selectedModelId,activeModeIds:F.options.activeModeIds},Ft=$==="interrupt";Ft&&S.cancel(),S.sendMessage(F.text,{contentParts:nt,mentions:Gt??void 0,contentSegments:F.contentSegments,viaVoice:F.viaVoice,composerOptions:it,...F.options.quote&&{quote:F.options.quote},...Ft&&{interrupt:!0}}),_e?.hasAttachments()&&_e.clearAttachments(),De&&lt?.clear(),Zo();let pt=ie.getState().activeModeIds,ze=Ih(pt,o.composer?.modes);ze.length!==pt.length&&Zi(ze),ie.getState().quote&&Wn(void 0),ba(),gc.release(),An()},X=o.composer?.onBeforeSend;if(!X){K();return}let ae=new AbortController;br=ae;let He=De=>{if(br=null,De.status==="error"){Gv(De.error);return}De.status==="proceed"&&K()},Fe=qh(X,F,ae.signal);if(!(Fe instanceof Promise)){He(Fe);return}return ie.setPreparing(!0),Fe.then(He).finally(()=>ie.setPreparing(!1))};function Yv(r){let a=ie.getState(),d=_e?.hasAttachments()??!1,m=d?[..._e.getContentParts()]:[];d&&r.sendText&&m.push(zo(r.sendText));let f=Zd({text:r.sendText,contentParts:m.length?m:void 0,mentionRefs:[...lt?.getMentionRefs()??[],...r.serverMentions?.refs??[]],contentSegments:od(),options:{...a.selectedModelId&&{selectedModelId:a.selectedModelId},...a.activeModeIds.length>0&&{activeModeIds:[...a.activeModeIds]},...a.quote&&{quote:{...a.quote}}},viaVoice:r.intent.viaVoice});Or(f),r.intent.consumeDraft!==!1&&Ha(),d&&_e.clearAttachments(),lt?.clear(),Zo(),a.quote&&Wn(void 0),ba(),gc.release(),An(),Ns("Message queued. It sends when the response finishes.")}function Qv(){let r=ie.getState().pendingSubmission;r&&(Or(void 0),Wa(r.text,{consumeDraft:!1,pending:r}))}function Xv(r){if(o.messageActions?.showEdit!==!0)return;let a=S.getMessages().find(d=>d.id===r);!a||!$d(a)||ar!==r&&(lr(),ar=r,ko=Dh({messageId:r,initialText:a.content,onSave:d=>Jv(r,d),onCancel:()=>lr()}),It.delete(r),un(ce,S.getMessages(),Xt),ko.focus())}function Jv(r,a){let d=ko;if(ar=null,ko=null,d?.destroy(),It.delete(r),!S.resubmitFrom(r,{reason:"edit",replacement:{text:a,mentionRefs:[],options:{}}})){un(ce,S.getMessages(),Xt);return}Gr()}function Zv(r){if(S.isStreaming())return;let a=Vd(S.getMessages(),r);a&&(lr(),S.resubmitFrom(a,{reason:"retry"})&&Gr())}ea={regenerate:Zv,edit:Xv,quote:r=>{let d=S.getMessages().find(m=>m.id===r)?.content?.trim();d&&(Wn({text:d,messageId:r}),Z?.focus())}};let ii=async r=>{if(!io){io=!0;try{await Ng({resolveInlineCommand:!0,...r})}finally{io=!1}}};function Ra(r){fr()||(Ha(),Wa(r,{consumeDraft:!1}))}let Wa=(r,a)=>{if(io)return;io=!0;let d=()=>{io=!1};try{let m=Ng({...a,overrideText:r});m instanceof Promise?m.finally(d):d()}catch(m){throw d(),m}},eC=r=>{if(r.preventDefault(),S.isStreaming()){S.cancel(),wn?.reset(),Ot?.update();return}io||ii()},tC=()=>o.features?.composerHistory!==!1,sd={...ip},id=!1,ai=()=>{sd={...ip}},nC=()=>S.getMessages().filter(r=>r.role==="user").map(r=>r.content??"").filter(r=>r.length>0),oC=r=>{if(!Z)return;id=!0,Z.value=r,Z.dispatchEvent(new Event("input",{bubbles:!0})),id=!1;let a=Z.value.length;Z.setSelectionRange(a,a)},rC=r=>{id||(r.isComposing||lt?.handleInput(r.inputType??void 0),ai())},sC=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:kd(Z)}),iC=r=>{if(Z&&!_n()&&!(!r.isComposing&&lt?.handleKeydown(r))){if(tC()&&(r.key==="ArrowUp"||r.key==="ArrowDown")&&!r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.isComposing){let a=Z.selectionStart===0&&Z.selectionEnd===0,d=ey({direction:r.key==="ArrowUp"?"up":"down",history:nC(),currentValue:Z.value,atStart:a,state:sd});if(sd=d.state,d.handled){r.preventDefault(),d.value!==void 0&&oC(d.value);return}}if(uf(r,sC())){if(S.isStreaming()){if(r.preventDefault(),ac()==="block"||io||fr())return;ai(),ii();return}if(io){r.preventDefault();return}if(fr()){r.preventDefault();return}ai(),r.preventDefault(),pe.click()}}},$g=r=>{if(!(r.key!=="Escape"||r.isComposing)&&r.composedPath().includes(re)){if(br){br.abort(),br=null,r.preventDefault(),r.stopImmediatePropagation();return}S.isStreaming()&&(S.cancel(),wn?.reset(),Ot?.update(),ai(),r.preventDefault(),r.stopImmediatePropagation())}},aC=async r=>{if(o.attachments?.enabled!==!0||!_e||_n())return;let a=Jx(r.clipboardData);a.length!==0&&(r.preventDefault(),await _e.handleFiles(a))},mn=null,Nn=!1,es=null,ao=null,ad=()=>o.voiceRecognition?.completionBehavior==="review";function Ba(r){te?.setAttribute("data-state",r),r==="recording"?cC():pd()}let zg="--persona-voice-level",ld=.5,ts=null,cd=-1,Da=0,Ug=()=>{let r=[],a=tn??te?.parentElement??null;return a&&r.push(a),Le&&r.push(Le),r},dd=r=>{let a=Math.round(Math.max(0,Math.min(1,r))*100)/100;if(a!==cd){cd=a;for(let d of Ug())d.style.setProperty(zg,String(a))}},lC=()=>{cd=-1,Da=0;for(let r of Ug())r.style.removeProperty(zg)};function cC(){if(ts!==null)return;if(typeof requestAnimationFrame!="function"){dd(C?S.getVoiceLevel()??ld:ld);return}let r=()=>{ts=requestAnimationFrame(r);let a=C?S.getVoiceLevel():null;if(a===null){dd(ld);return}Da+=(a-Da)*.3,dd(Da)};ts=requestAnimationFrame(r)}function pd(){ts!==null&&(cancelAnimationFrame(ts),ts=null),lC()}let qg=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Oa=(r="user")=>{if(Nn||S.isStreaming())return;let a=qg();if(!a)return;mn=new a;let d=o.voiceRecognition??{},m=d.pauseDuration??2e3;mn.continuous=d.provider?.browser?.continuous??!0,mn.interimResults=!0,mn.lang=d.provider?.browser?.language??"en-US";let f=Z.value;mn.onresult=b=>{let D="",$="";for(let q=0;q<b.results.length;q++){let K=b.results[q],X=K[0].transcript;K.isFinal?D+=X+" ":$=X}let F=f+D+$;Z.value=F,Rn(),es&&clearTimeout(es),(D||$)&&(es=window.setTimeout(()=>{if(Z.value.trim()&&mn&&Nn){if(Do(),ad())return;ii({viaVoice:!0})}},m))},mn.onerror=b=>{b.error!=="no-speech"&&Do()},mn.onend=()=>{if(Nn){let b=Z.value.trim();!ad()&&b&&b!==f.trim()&&ii({viaVoice:!0}),Do()}};try{if(mn.start(),Nn=!0,Ie.active=!0,r!=="system"&&(Ie.manuallyDeactivated=!1),oo(r),Tn(),An(),te){let b=o.voiceRecognition??{};ao={backgroundColor:te.style.backgroundColor,color:te.style.color,borderColor:te.style.borderColor,iconName:b.iconName??"mic",iconSize:parseFloat(b.iconSize??"")||qn};let D=b.recordingBackgroundColor,$=b.recordingIconColor,F=b.recordingBorderColor;if(te.classList.add("persona-voice-recording"),Ba("recording"),te.style.backgroundColor=D??"var(--persona-voice-recording-bg, #ef4444)",te.style.color=$??"var(--persona-voice-recording-indicator, #ffffff)",$){let q=te.querySelector("svg");q&&q.setAttribute("stroke",$)}F&&(te.style.borderColor=F),te.setAttribute("aria-label","Stop voice recognition")}}catch{Do("system")}},Do=(r="user")=>{if(Nn){if(Nn=!1,es&&(clearTimeout(es),es=null),mn){try{mn.stop()}catch{}mn=null}if(Ie.active=!1,oo(r),Tn(),An(),te){if(te.classList.remove("persona-voice-recording"),Ba("idle"),ao){te.style.backgroundColor=ao.backgroundColor,te.style.color=ao.color,te.style.borderColor=ao.borderColor;let a=te.querySelector("svg");a&&a.setAttribute("stroke",ao.color||"currentColor"),ao=null}te.setAttribute("aria-label","Start voice recognition")}}},jg=null,_a=r=>{let a=m=>{jg??=m.createMicStateStyles({mic:()=>te,config:()=>o,session:()=>S,get original(){return ao},set original(f){ao=f},setMicState:Ba,renderIcon:se,iconFallbackPx:qn}),r(jg)},d=ah();d?a(d):Si().then(a,()=>{})},ns=()=>_a(r=>r.recording()),dC=()=>_a(r=>r.processing()),pC=()=>_a(r=>r.speaking()),lo=()=>_a(r=>r.reset()),ud=()=>{if(!_n()){if(Nt(o.voiceRecognition?.provider)){let r=S.getVoiceStatus(),a=S.getVoiceInterruptionMode();if(a==="none"&&(r==="processing"||r==="speaking"))return;if(a==="cancel"&&(r==="processing"||r==="speaking")){S.stopVoicePlayback();return}if(S.isBargeInActive()){S.stopVoicePlayback(),S.deactivateBargeIn().then(()=>{Ie.active=!1,Ie.manuallyDeactivated=!0,Tn(),oo("user"),lo()});return}S.toggleVoice().then(()=>{Ie.active=S.isVoiceActive(),Ie.manuallyDeactivated=!S.isVoiceActive(),Tn(),oo("user"),S.isVoiceActive()?ns():lo()});return}if(Nn){let r=Z.value.trim();Ie.manuallyDeactivated=!0,Tn(),Do("user"),r&&!ad()&&ii()}else Ie.manuallyDeactivated=!1,Tn(),Oa("user")}};lc=ud;let Kg=()=>S.prewarmVoice(),Gg=()=>{let r=o.voiceRecognition;return r?.enabled!==!0?!1:r.prewarm??(o.clientToken?"hover":!1)},Yg=r=>{Gg()==="hover"&&te?.contains(r.target)&&Kg()},Qg=["pointerover","pointerdown","focusin"];Qg.forEach(r=>t.addEventListener(r,Yg));let Xg,Jg=null,gd,Zg=()=>{let r=gd;gd=void 0;try{typeof r=="function"&&r()}catch{}},md=()=>{let r=Gg(),a=typeof r=="function"&&te?r:void 0,d=a?te:null;if(!(a===Xg&&d===Jg)&&(Zg(),Xg=a,Jg=d,!(!a||!d)))try{gd=a({warm:Kg,micButton:d,mount:t})}catch{}};md(),oe.push(()=>{Qg.forEach(r=>t.removeEventListener(r,Yg)),Zg()}),te&&oe.push(()=>{Nt(o.voiceRecognition?.provider)?(S.isVoiceActive()&&S.toggleVoice(),lo()):Do("system")});let uC=G.on("assistant:complete",()=>{ie.getState().pendingSubmission&&setTimeout(()=>{S.isStreaming()||Qv()},0)});oe.push(uC);let gC=G.on("assistant:complete",()=>{og&&(Ie.active||Ie.manuallyDeactivated||og==="assistant"&&!Ie.lastUserMessageWasVoice||setTimeout(()=>{!Ie.active&&!Ie.manuallyDeactivated&&(Nt(o.voiceRecognition?.provider)?S.toggleVoice().then(()=>{Ie.active=S.isVoiceActive(),oo("auto"),S.isVoiceActive()&&ns()}):Oa("auto"))},600))});oe.push(gC);let mC=G.on("action:resubmit",()=>{setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)});oe.push(mC);let em=()=>{Ge(!Se,"user")},ct=null,_t=null;if(de&&!Ae()){let{instance:r,element:a}=Mp({config:o,plugins:g,onToggle:em});ct=r,r||(_t=a)}ct?t.appendChild(ct.element):_t&&t.appendChild(_t),ti(),sr(),Ea(),qc(),ni(S.isStreaming()),Hc()||(nn()==="follow"?Ho(!0):Ic()),pv(),Ps&&(!de||Ae()?setTimeout(()=>Aa(),0):Se&&setTimeout(()=>Aa(),200));let Oo=null,tm=()=>{Oo&&(Oo.disconnect(),Oo.observe(Le),Oo.observe(re),Oo.observe(xt))},nm=Vs(),li=()=>{if(Ae()){Jo(),ti();return}let r=rt(o),a=o.launcher?.sidebarMode??!1,d=t.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640,b=d.innerWidth<=f,D=m&&b&&de;try{if(D){er(),qs=ca();return}let $=!1;Yl&&(Yl=!1,er(),$=!0);let F=ca();if(!$&&F!==qs&&(er(),$=!0),qs=F,$&&sa(),!de&&!r){le.style.height="",le.style.width="";return}if(!a&&!r){let q=Pr(o);le.style.width=q.width,le.style.maxWidth=q.maxWidth}la(),Vu()}finally{Jo(),Ji();let $=Vs();if($!==nm&&(nm=$,oi(),sr()),ti(),Se&&de){let q=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),K=o.launcher?.sidebarMode??!1,X=o.launcher?.mobileFullscreen??!0,ae=rt(o)&&X&&q,He=K||X&&q&&de||ae;if(He&&!Dn){let Fe=t.getRootNode(),De=Fe instanceof ShadowRoot?Fe.host:t.closest(".persona-host");De&&!Bn&&(Bn=ap(De,o.launcher?.zIndex??Dt)),Dn=lp(t.ownerDocument)}else He||(Bn?.(),Bn=null,Dn?.(),Dn=null)}}};li();let Fa=t.ownerDocument.defaultView??window;if(Fa.addEventListener("resize",li),oe.push(()=>Fa.removeEventListener("resize",li)),typeof ResizeObserver<"u"){Oo=new ResizeObserver(()=>{Ji()}),tm(),oe.push(()=>{Oo?.disconnect(),Oo=null});let r=new ResizeObserver(()=>{Ia()});r.observe(re),oe.push(()=>r.disconnect())}Fa.addEventListener("resize",Ia),oe.push(()=>Fa.removeEventListener("resize",Ia)),sn=j.scrollTop;let om=uo(j),rm=()=>{Nu();let r=j.scrollTop,a=uo(j),d=a<om;if(om=a,!xo()){sn=r,Ht();return}let{action:m,nextLastScrollTop:f}=kf({following:rn.isFollowing(),currentScrollTop:r,lastScrollTop:sn,nearBottom:Er(j,to),userScrollThreshold:av,isAutoScrolling:Kt||pa||d,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(sn=f,m==="resume"){va()||On();return}m==="pause"&&Kr()};if(j.addEventListener("scroll",rm,{passive:!0}),oe.push(()=>j.removeEventListener("scroll",rm)),typeof ResizeObserver<"u"){let r=new ResizeObserver(()=>{bv(),Bd(ce)});r.observe(ce),r.observe(j),oe.push(()=>r.disconnect())}let sm=()=>{xo()&&rn.isFollowing()&&va()&&Kr()},im=j.ownerDocument;im.addEventListener("selectionchange",sm),oe.push(()=>{im.removeEventListener("selectionchange",sm)});let fC=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),am=r=>{fC.has(r.key)&&(Io(),cu()&&xo()&&rn.isFollowing()&&Kr())},lm=r=>{r.target?.closest("a, button, [tabindex], input, textarea, select")&&(Io(),cu()&&xo()&&rn.isFollowing()&&Kr())};j.addEventListener("keydown",am),j.addEventListener("focusin",lm),oe.push(()=>{j.removeEventListener("keydown",am),j.removeEventListener("focusin",lm)});let cm=r=>{if(r.deltaY!==0&&Io(),!xo())return;let a=Pf({following:rn.isFollowing(),deltaY:r.deltaY,nearBottom:Er(j,to),resumeWhenNearBottom:!0});a==="pause"?Kr():a==="resume"&&!va()&&On()};j.addEventListener("wheel",cm,{passive:!0}),j.addEventListener("touchmove",Io,{passive:!0}),j.addEventListener("pointerdown",Io,{passive:!0}),oe.push(()=>{j.removeEventListener("touchmove",Io),j.removeEventListener("pointerdown",Io)}),oe.push(()=>j.removeEventListener("wheel",cm)),ft.addEventListener("click",()=>{mr(),j.scrollTop=j.scrollHeight,sn=j.scrollTop,On(),Ho(!0),Ht()}),oe.push(()=>ft.remove()),oe.push(()=>{lg(),mr()});let dm=()=>{xe&&(or&&(xe.removeEventListener("click",or),or=null),Ve()?(xe.style.display="",or=()=>{Ge(!1,"user")},xe.addEventListener("click",or)):xe.style.display="none")};dm(),(()=>{let{clearChatButton:r}=Re;r&&r.addEventListener("click",()=>{let a=tt;if(a?.historyAvailable()){a.startNewConversation({focusComposer:!0}).catch(m=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",m)});return}S.clearMessages(),o.layout?.topFade&&(j.scrollTop=0),j.removeAttribute("data-persona-top-fade"),It.clear(),On(),xd(Re.composerOverlay);try{localStorage.removeItem(Es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Es}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let d=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(d),v?.clear&&ha(()=>v.clear(),"[AgentWidget] Failed to clear storage adapter:"),x={},Me.syncFromMetadata(),_e?.clearAttachments(),ba(),Or(void 0),Wn(void 0),lr(),Lt?.clear(),wn?.reset(),Ot?.update()})})();let pm=[["keydown",iC],["input",rC],["input",Rn],["input",Zo],["keyup",Zo],["paste",aC],["focus",Yb]],um=r=>{if(r)for(let[a,d]of pm)Be?.addListener(r,a,d)},hC=r=>{if(r)for(let[a,d]of pm)Be?.removeListener(r,a,d)},gm=()=>{Be&&(Be.addListener(Be.form,"submit",eC),Be.addListener(Be.footer,"click",Zo),um(Z),te&&Be.addListener(te,"click",ud),md())};gm();let mm=()=>{lt?.onComposerSwap((r,a)=>{hC(a),Z=r,Be&&(Be.input=r),um(r),dc(),Oc(),Rn()})};mm();let fd=!1;function fm(){if(!fd){fd=!0;try{let r=Z?.value??"",a=Le.ownerDocument??document,d=Z?a.activeElement===Z:!1;pd(),Be?.destroy(),Be=null,lt?.destroy(),lt=null;let m=null,f=()=>(m=Ae()?Dl({config:o}):Wi({config:o}),m.footer),b=vu(f)??f();Zt.replaceComposer(b),Le=Zt.composer.footer;let D=m!==null&&b===m.footer;Fr=!D,lu=D?m.setSendButtonMode:()=>{},bu(Le),wu(Le),Su(),xu(),pc(),mm(),Au(),uc(),Mu(),gm();let $=nr.indexOf(eo);if(eo.destroy(),eo=Hi(wo),$>=0&&(nr[$]=eo),Z&&(Z.value=r),Rn(),Zo(),Ea(),sr(),ni(S.isStreaming()),o.statusIndicator?.mode==="transient"&&!Ae()){let F=S.getStatus();Ws(We,Jl(F),o.statusIndicator,F)}Ie.active&&Ba("recording"),er(),tm(),Jo(),An(),xa(),d&&Z?.focus()}finally{fd=!1}}}let ci=t.ownerDocument??document;ci.addEventListener("keydown",$g,!0);let hm=()=>{Tc()},ym=()=>{ci.visibilityState==="hidden"&&Tc()};typeof window<"u"&&(window.addEventListener("pagehide",hm),ci.addEventListener("visibilitychange",ym),oe.push(()=>{window.removeEventListener("pagehide",hm),ci.removeEventListener("visibilitychange",ym)}));let bm="persona-attachment-drop-active",di=0,hd=()=>{di=0,re.classList.remove(bm)},os=()=>o.attachments?.enabled===!0&&_e!==null&&!_n(),vm=r=>{!Kl(r.dataTransfer)||!os()||(di++,di===1&&re.classList.add(bm))},Cm=r=>{!Kl(r.dataTransfer)||!os()||(di--,di<=0&&hd())},wm=r=>{!Kl(r.dataTransfer)||!os()||(r.preventDefault(),r.dataTransfer.dropEffect="copy")},Sm=r=>{if(!Kl(r.dataTransfer)||!os())return;r.preventDefault(),r.stopPropagation(),hd();let a=Array.from(r.dataTransfer.files??[]);a.length!==0&&_e.handleFiles(a)},_o=!0;re.addEventListener("dragenter",vm,_o),re.addEventListener("dragleave",Cm,_o),t.addEventListener("dragover",wm,_o),t.addEventListener("drop",Sm,_o);let Na=t.ownerDocument,xm=r=>{os()&&r.preventDefault()},Am=r=>{os()&&r.preventDefault()};Na.addEventListener("dragover",xm),Na.addEventListener("drop",Am),oe.push(()=>{Be?.destroy(),Be=null,pd(),xn?.destroy(),xn=null,Xn?.destroy(),Xn=null,Mo?.destroy(),Mo=null,Eo?.destroy(),Eo=null,Ao=null,ic=null,Tc(),Qs.destroy(),Zr&&clearTimeout(Zr),lr(),br?.abort(),br=null,_e?.destroy(),_e=null,ie.destroy(),ci.removeEventListener("keydown",$g,!0),lt?.destroy()}),oe.push(()=>{re.removeEventListener("dragenter",vm,_o),re.removeEventListener("dragleave",Cm,_o),t.removeEventListener("dragover",wm,_o),t.removeEventListener("drop",Sm,_o),Na.removeEventListener("dragover",xm),Na.removeEventListener("drop",Am),hd()}),oe.push(()=>{S.cancel()}),ct?oe.push(()=>{ct?.destroy()}):_t&&oe.push(()=>{_t?.remove()});let dt={update(r){let a=o.future?.v5Defaults===!0,d=o.toolCall,m=o.messageActions,f=o.layout?.messages,b=o.colorScheme,D=o.loadingIndicator,$=o.iterationDisplay,F=o.features?.showReasoning,q=o.features?.showToolCalls,K=o.features?.toolCallDisplay,X=o.features?.reasoningDisplay,ae=o.features?.streamAnimation?.type,He=o.features?.history?.enabled===!0,Fe=o.features?.history?.provider,De=o.getIdentityProof,Gt=o.clientToken,nt=o.contextMentions;o=tb({...o,features:p},r),p=o.features,o=_p(o),u(),vc(),Ti(t,o),Oi(t,o),_i(t,o),ji(),En(),o.colorScheme!==b&&$u();let it=Vp.getForInstance(o.plugins);g.length=0,g.push(...it),Jc(),de=o.launcher?.enabled??!0,In=o.launcher?.autoExpand??!1,Is=o.features?.showReasoning??!0,Hs=o.features?.showToolCalls??!0,Vi=o.features?.scrollToBottom??{};let Ft=nn();vo=o.features?.scrollBehavior??{},Ft!==nn()&&(mr(),On()),ng(),uu(),Ht();let pt=Jt;if(Jt=o.features?.showEventStreamToggle??!1,Jt&&!pt){if(Lt||(zi(),S.setSSEEventCallback((N,Te)=>{o.onSSEEvent?.(N,Te),Xl(N,Te)})),!Ne&&Ke){let N=o.features?.eventStream?.classNames,Te="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"+(N?.toggleButton?" "+N.toggleButton:"");Ne=P("button",Te),Ne.style.width="28px",Ne.style.height="28px",Ne.style.color=Vt.actionIconColor,Ne.type="button",Ne.setAttribute("aria-label","Event Stream"),Ne.title="Event Stream";let ke=yt(fb,"18px","currentColor",1.5);ke&&Ne.appendChild(ke);let Oe=Re.clearChatButtonWrapper,Ze=Re.closeButtonWrapper,Rt=Oe||Ze;Rt&&Rt.parentNode===Ke?Ke.insertBefore(Ne,Rt):Ke.appendChild(Ne),Ne.addEventListener("click",()=>{Sn?_r():cc()})}}else!Jt&&pt&&(_r(),Ne&&(Ne.remove(),Ne=null),Lt?.clear(),Rr?.destroy(),Lt=null,Rr=null,wn?.reset(),wn=null,Yn=null);if(o.launcher?.enabled===!1&&ct&&(ct.destroy(),ct=null),o.launcher?.enabled===!1&&_t&&(_t.remove(),_t=null),o.launcher?.enabled!==!1&&!ct&&!_t){let{instance:N,element:Te}=Mp({config:o,plugins:g,onToggle:em});ct=N,N||(_t=Te),t.appendChild(Te)}ct&&ct.update(o),si(),Yo&&o.launcher?.subtitle!==void 0&&(Yo.textContent=o.launcher.subtitle);let ze=o.layout?.header;if(ze?.layout!==tu&&Ke){let N=ze?Bl(o,ze,{showClose:Ve(),onClose:()=>Ge(!1,"user")}):kr({config:o,showClose:Ve(),onClose:()=>Ge(!1,"user")});Zt.replaceHeader(N),Ke=Zt.header.element,at=Zt.header.iconHolder,So=Zt.header.headerTitle,Yo=Zt.header.headerSubtitle,xe=Zt.header.closeButton,tu=ze?.layout,si()}else if(ze){if(at&&(at.style.display=ze.showIcon===!1?"none":""),So&&(So.style.display=ze.showTitle===!1?"none":""),Yo&&(Yo.style.display=ze.showSubtitle===!1?"none":""),xe){let N=Ve()&&ze.showCloseButton!==!1;xe.style.display=N?"":"none"}if(Re.clearChatButtonWrapper){let N=ze.showClearChat;if(N!==void 0){Re.clearChatButtonWrapper.style.display=N?"":"none";let{closeButtonWrapper:Te}=Re;Te&&!Te.classList.contains("persona-absolute")&&(N?Te.classList.remove("persona-ml-auto"):Te.classList.add("persona-ml-auto"))}}}let $n=o.layout?.showHeader!==!1;Ke&&(Ke.style.display=$n?"":"none");let hn=o.layout?.showFooter!==!1;Le&&(Le.style.display=hn?"":"none"),Jo(),Ht(),de!==eu?de?Ge(In,"auto"):(Se=!0,ti()):In!==Zp&&Ge(In,"auto"),Zp=In,eu=de,li(),dm();let zn=JSON.stringify(o.toolCall)!==JSON.stringify(d),kn=JSON.stringify(o.messageActions)!==JSON.stringify(m),No=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),pi=o.loadingIndicator?.render!==D?.render||o.loadingIndicator?.renderIdle!==D?.renderIdle||o.loadingIndicator?.showBubble!==D?.showBubble,vr=o.iterationDisplay!==$,M=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(K)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(X);(o.future?.v5Defaults===!0!==a||zn||kn||No||pi||vr||M)&&S&&(cr++,un(ce,S.getMessages(),Xt));let fe=o.features?.streamAnimation?.type;if(fe!==ae&&fe&&fe!=="none"){let N=Sc(fe,o.features?.streamAnimation?.plugins);N&&yi(N,t)}let U=o.launcher??{},Ue=U.headerIconHidden??!1,mt=o.layout?.header?.showIcon,Bt=Ue||mt===!1,At=U.headerIconName,Ye=U.headerIconSize??$a;if(at){let N=Ke,Te=N?.querySelector(".persona-flex-col");if(Bt)at.style.display="none",N&&Te&&!N.contains(Te)&&N.insertBefore(Te,N.firstChild);else{if(at.style.display="",at.style.height=Ye,at.style.width=Ye,N&&Te&&(N.contains(at)?at.nextSibling!==Te&&(at.remove(),N.insertBefore(at,Te)):N.insertBefore(at,Te)),At){let Oe=parseFloat(Ye)||24,Ze=se(At,Oe*.6,"currentColor",1);Ze?(Ze.style.width=`calc(${Oe}px * var(--persona-components-header-iconScale, 0.6))`,Ze.style.height=`calc(${Oe}px * var(--persona-components-header-iconScale, 0.6))`,at.replaceChildren(Ze)):at.textContent=U.agentIconText??"\u{1F4AC}"}else if(U.iconUrl){let Oe=at.querySelector("img");if(Oe)Oe.src=U.iconUrl,Oe.style.height=Ye,Oe.style.width=Ye;else{let Ze=document.createElement("img");Ze.src=U.iconUrl,Ze.alt="",Ze.className="persona-rounded-xl persona-object-cover",Ze.style.height=Ye,Ze.style.width=Ye,at.replaceChildren(Ze)}}else{let Oe=at.querySelector("svg"),Ze=at.querySelector("img");(Oe||Ze)&&at.replaceChildren(),at.textContent=U.agentIconText??"\u{1F4AC}"}let ke=at.querySelector("img");ke&&(ke.style.height=Ye,ke.style.width=Ye)}}let ut=o.layout?.header?.showTitle,Ct=o.layout?.header?.showSubtitle;if(So&&(So.style.display=ut===!1?"none":""),Yo&&(Yo.style.display=Ct===!1?"none":""),xe){let N=Ve()&&o.layout?.header?.showCloseButton!==!1;if(xe.style.display=N?"":"none",!Ae()){let Et=U.closeButtonSize??"";xe.style.height=Et,xe.style.width=Et,xe.style.minWidth=Et,xe.style.minHeight=Et}let Te=U.closeButtonPlacement??"inline",{closeButtonWrapper:ke}=Re,Oe=Te==="top-right",Ze=ke?.classList.contains("persona-absolute");if(ke&&Oe!==Ze)if(ke.remove(),Oe){ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Et=tt?.railColumn??re;Et.style.position="relative",Et.appendChild(ke)}else{let Et=U.clearChat?.placement??"inline",Tt=U.clearChat?.enabled??!0;ke.className=Tt&&Et==="inline"?"":"persona-ml-auto",Ke&&Ke.appendChild(ke)}if(xe.style.color=U.closeButtonColor||Vt.actionIconColor,U.closeButtonBackgroundColor?(xe.style.backgroundColor=U.closeButtonBackgroundColor,xe.classList.remove("hover:persona-bg-gray-100")):(xe.style.backgroundColor="",xe.classList.add("hover:persona-bg-gray-100")),U.closeButtonBorderWidth||U.closeButtonBorderColor){let Et=U.closeButtonBorderWidth||"0px",Tt=U.closeButtonBorderColor||"transparent";xe.style.border=`${Et} solid ${Tt}`,xe.classList.remove("persona-border-none")}else xe.style.border="",xe.classList.add("persona-border-none");U.closeButtonBorderRadius?(xe.style.borderRadius=U.closeButtonBorderRadius,xe.classList.remove("persona-rounded-full")):(xe.style.borderRadius="",xe.classList.add("persona-rounded-full")),U.closeButtonPaddingX?(xe.style.paddingLeft=U.closeButtonPaddingX,xe.style.paddingRight=U.closeButtonPaddingX):(xe.style.paddingLeft="",xe.style.paddingRight=""),U.closeButtonPaddingY?(xe.style.paddingTop=U.closeButtonPaddingY,xe.style.paddingBottom=U.closeButtonPaddingY):(xe.style.paddingTop="",xe.style.paddingBottom=""),Wl(xe,U.closeButtonIconName??"x",{iconSize:Ae()?wp:void 0,iconText:U.closeButtonIconText??"\xD7"});let Rt=U.closeButtonTooltipText??"Close chat",Ln=U.closeButtonShowTooltip??!0;xe.setAttribute("aria-label",Rt),ke&&vn({anchor:xe,trigger:ke,text:()=>xe?.getAttribute("aria-label")??Rt,enabled:Ln})}let{clearChatButton:ue,clearChatButtonWrapper:Qe}=Re;if(ue){let N=U.clearChat??{},Te=N.enabled??!0,ke=o.layout?.header?.showClearChat,Oe=ke!==void 0?ke:Te,Ze=N.placement??"inline";if(Qe){Qe.style.display=Oe?"":"none";let{closeButtonWrapper:Rt}=Re;!Ae()&&Rt&&!Rt.classList.contains("persona-absolute")&&(Oe?Rt.classList.remove("persona-ml-auto"):Rt.classList.add("persona-ml-auto"));let Ln=Ze==="top-right",Et=Qe.classList.contains("persona-absolute");if(!Ae()&&Ln!==Et&&Oe){if(Qe.remove(),Ln){Qe.className="persona-absolute persona-top-4 persona-z-50",Qe.style.right="48px";let Un=tt?.railColumn??re;Un.style.position="relative",Un.appendChild(Qe)}else{Qe.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Qe.style.right="";let Un=Re.closeButtonWrapper;Ke&&Un&&Un.parentElement===Ke?Ke.insertBefore(Qe,Un):Ke&&Ke.appendChild(Qe)}let Tt=Re.closeButtonWrapper;Tt&&!Tt.classList.contains("persona-absolute")&&(Ln?Tt.classList.add("persona-ml-auto"):Tt.classList.remove("persona-ml-auto"))}}if(Oe){if(!Ae()){let Tt=N.size??"";ue.style.height=Tt,ue.style.width=Tt,ue.style.minWidth=Tt,ue.style.minHeight=Tt}let Rt=N.iconColor??"";if(ue.style.color=Rt||Vt.actionIconColor,Wl(ue,N.iconName??"refresh-cw",{iconSize:Ae()?Sp:void 0}),N.backgroundColor?(ue.style.backgroundColor=N.backgroundColor,ue.classList.remove("hover:persona-bg-gray-100")):(ue.style.backgroundColor="",ue.classList.add("hover:persona-bg-gray-100")),N.borderWidth||N.borderColor){let Tt=N.borderWidth||"0px",Un=N.borderColor||"transparent";ue.style.border=`${Tt} solid ${Un}`,ue.classList.remove("persona-border-none")}else ue.style.border="",ue.classList.add("persona-border-none");N.borderRadius?(ue.style.borderRadius=N.borderRadius,ue.classList.remove("persona-rounded-full")):(ue.style.borderRadius="",ue.classList.add("persona-rounded-full")),N.paddingX?(ue.style.paddingLeft=N.paddingX,ue.style.paddingRight=N.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),N.paddingY?(ue.style.paddingTop=N.paddingY,ue.style.paddingBottom=N.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let Ln=N.tooltipText??"Clear chat",Et=N.showTooltip??!0;ue.setAttribute("aria-label",Ln),Qe&&vn({anchor:ue,trigger:Qe,text:()=>ue?.getAttribute("aria-label")??Ln,enabled:Et})}}let ye=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zp],wt=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Fi.message,Fi.messageAndClick];Me=Up({parsers:ye,handlers:wt,getSessionMetadata:Wt,updateSessionMetadata:$e,emit:G.emit,documentRef:typeof document<"u"?document:null}),Xt=vb(o,Me,nu),Ov(),S.updateConfig(o),Og(),(o.features?.history?.enabled===!0!==He||o.features?.history?.provider!==Fe||o.getIdentityProof!==De||o.clientToken!==Gt)&&(tt?.closeHistory({restoreFocus:!1}),tt?.installHistoryProvider()),tt?.syncHistoryChromeImpl(),Ia(),ri()&&!tt&&ed().catch(()=>{}),un(ce,S.getMessages(),Xt),sr(),Ea(),Wv(),ni(S.isStreaming()),nt!==o.contextMentions&&fm();let bn=o.voiceRecognition?.enabled===!0,Mt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),qe=Nt(o.voiceRecognition?.provider);if(bn&&(Mt||qe))if(!te||!tn){let N=gs(o);if(N){te=N.button,tn=N.wrapper;let Te=Hn&&Hn.parentElement===Gi?Hn:null;Gi?Gi.insertBefore(tn,Te):Ut?.appendChild(tn),Be&&(Be.micButton=te),Be?.addListener(te,"click",ud),te.disabled=_n()||S.isStreaming()&&!Bc()}}else{let N=o.voiceRecognition??{},Te=o.sendButton??{},ke=N.iconName??"mic",Oe=N.iconSize,Ze=parseFloat(Oe??"")||qn;te.classList.add(Uo),te.classList.toggle(Mr,!Oe),te.style.width=Oe??"",te.style.height=Oe??"",te.style.minWidth=Oe??"",te.style.minHeight=Oe??"";let Rt=N.iconColor??Te.textColor;te.innerHTML="";let Ln=se(ke,Ze,Rt||"currentColor",1.5);Ln?te.appendChild(Ln):te.textContent="\u{1F3A4}";let Et=N.backgroundColor??Te.backgroundColor;Et?te.style.backgroundColor=Et:te.style.backgroundColor="",Rt?te.style.color=Rt:te.style.color="var(--persona-text, #111827)",N.borderWidth?(te.style.borderWidth=N.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),N.borderColor?te.style.borderColor=N.borderColor:te.style.borderColor="",N.paddingX?(te.style.paddingLeft=N.paddingX,te.style.paddingRight=N.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),N.paddingY?(te.style.paddingTop=N.paddingY,te.style.paddingBottom=N.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Tt=N.tooltipText??"Start voice recognition",Un=N.showTooltip??!1;te.setAttribute("aria-label",Tt),tn&&vn({anchor:te,trigger:tn,text:()=>te?.getAttribute("aria-label")??Tt,enabled:Un}),tn.style.display="",te.disabled=_n()||S.isStreaming()&&!Bc()}else te&&tn&&(tn.style.display="none",Nt(o.voiceRecognition?.provider)?S.isVoiceActive()&&S.toggleVoice():Nn&&Do());if(md(),o.attachments?.enabled===!0){if(!qt||!st){let N=o.attachments??{};jt||(jt=P("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),jt.style.display="none",(Z.parentElement??Ut).insertBefore(jt,Z)),et||(et=document.createElement("input"),et.type="file",et.accept=(N.allowedTypes??us).join(","),et.multiple=(N.maxFiles??4)>1,et.style.display="none",et.setAttribute("aria-label","Attach files"),(Z.parentElement??Ut).insertBefore(et,Z)),qt=P("div","persona-send-button-wrapper"),st=P("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Uo} ${Mr}`),st.type="button",st.setAttribute("aria-label",N.buttonTooltipText??"Attach file");let Te=N.buttonIconName??"paperclip";st.style.fontSize="18px",st.style.lineHeight="1";let ke=se(Te,qn,"currentColor",1.5);ke?st.appendChild(ke):st.textContent="\u{1F4CE}",st.addEventListener("click",Ze=>{Ze.preventDefault(),et?.click()}),qt.appendChild(st);let Oe=N.buttonTooltipText??"Attach file";vn({anchor:st,trigger:qt,text:()=>st?.getAttribute("aria-label")??Oe}),ec?ec.append(qt):Ut.appendChild(qt),Be&&(Be.attachmentButton=st,Be.attachmentInput=et??void 0,Be.attachmentPreviews=jt??void 0),!_e&&et&&jt&&(_e=xi.fromConfig(N,gu),_e.setPreviewsContainer(jt),Be?.addListener(et,"change",async()=>{_e&&et?.files&&(await _e.handleFileSelect(et.files),et.value="")}))}else{qt.style.display="";let N=o.attachments??{};et&&(et.accept=(N.allowedTypes??us).join(","),et.multiple=(N.maxFiles??4)>1),_e&&_e.updateConfig({allowedTypes:N.allowedTypes,maxFileSize:N.maxFileSize,maxFiles:N.maxFiles,adapter:N.adapter})}if(re.querySelector(".persona-attachment-drop-overlay")?.remove(),re.appendChild(Cb(o.attachments?.dropOverlay)),st){let N=o.attachments??{},Te=N.buttonTooltipText??"Attach file";st.setAttribute("aria-label",Te),st.textContent="";let ke=se(N.buttonIconName??"paperclip",qn,"currentColor",1.5);ke?st.appendChild(ke):st.textContent="\u{1F4CE}",qt&&vn({anchor:st,trigger:qt,text:()=>st?.getAttribute("aria-label")??Te})}}else qt&&(qt.style.display="none"),_e&&_e.clearAttachments(),re.querySelector(".persona-attachment-drop-overlay")?.remove();let be=o.sendButton??{},Vo=be.useIcon??!1,ht=be.iconText??"\u2191",Yt=be.iconName,co=be.tooltipText??"Send message",yd=be.showTooltip??!1,Cr=be.size,bd=parseFloat(Cr??"")||ff,po=be.backgroundColor,wr=be.textColor;if(Vo){if(pe.style.width=Cr??"",pe.style.height=Cr??"",pe.style.minWidth=Cr??"",pe.style.minHeight=Cr??"",pe.style.fontSize="18px",pe.style.lineHeight="1",wr?pe.style.color=wr:pe.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!S.isStreaming())if(pe.innerHTML="",Yt){let N=parseFloat(be.iconSize??"")||Math.round(bd*.5),Te=wr?.trim()||"currentColor",ke=be.iconStrokeWidth??2,Oe=se(Yt,N,Te,ke),Ze=se(be.stopIconName??"square",N,Te,ke);Oe&&Ze?pe.appendChild(hf(Oe,Ze)):Oe?pe.appendChild(Oe):pe.textContent=ht}else pe.textContent=ht;pe.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Uo}`,po?(pe.style.backgroundColor=po,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=o.copy?.sendButtonLabel??"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.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",po?(pe.style.backgroundColor=po,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),wr?pe.style.color=wr:pe.classList.add("persona-text-white");be.borderWidth?(pe.style.borderWidth=be.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),be.borderColor?pe.style.borderColor=be.borderColor:pe.style.borderColor="",be.paddingX?(pe.style.paddingLeft=be.paddingX,pe.style.paddingRight=be.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),be.paddingY?(pe.style.paddingTop=be.paddingY,pe.style.paddingBottom=be.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom=""),S.isStreaming()||pe.setAttribute("aria-label",co),xa(),Hn&&vn({anchor:pe,trigger:Hn,text:()=>pe.getAttribute("aria-label")??co,enabled:yd}),Eu(),wc();let Mm=Ml(ie.getState().activeModeIds,o.composer?.modes);ie.setActiveModeIds(Mm),Br().length>0!==!!Xn&&uc(),Xn?.render(Mm,Br());for(let N of[...Dr.keys()])Al(N,o.composer?.modeGroups)||Dr.delete(N);Dr.forEach(N=>N.repaint()),Ao?.repaint(),xn?.resolve();let Va=Ko(o,Ae());if(Cc(),Va){ce.style.maxWidth=Va,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",en.style.maxWidth=Va,en.style.marginLeft="auto",en.style.marginRight="auto",en.style.width="100%";for(let N of[Ut,wo,jt,We])N&&(N.style.maxWidth=Va,N.style.marginLeft="auto",N.style.marginRight="auto",N.style.width="100%")}else{ce.style.maxWidth="",ce.style.marginLeft="",ce.style.marginRight="",ce.style.width="",en.style.maxWidth="",en.style.marginLeft="",en.style.marginRight="",en.style.width="";for(let N of[Ut,wo,jt,We])N&&(N.style.maxWidth="",N.style.marginLeft="",N.style.marginRight="",N.style.width="")}let Pn=o.statusIndicator??{};if(vd(We,Ut,Pn),ui(We,Pn,S?.getStatus()??"idle"),S){let N=S.getStatus();Ws(We,(ke=>ke==="idle"?Pn.idleText??gt.idle:ke==="connecting"?Pn.connectingText??gt.connecting:ke==="connected"?Pn.connectedText??gt.connected:ke==="error"?Pn.errorText??gt.error:ke==="paused"?Pn.pausedText??gt.paused:ke==="resuming"?Pn.resumingText??gt.resuming:gt[ke])(N),Pn,N)}We.classList.remove("persona-text-left","persona-text-center","persona-text-right");let vC=Pn.align==="left"?"persona-text-left":Pn.align==="center"?"persona-text-center":"persona-text-right";We.classList.add(vC),dc(),Oc(),An(),qi()},open(){Ve()&&Ge(!0,"api")},close(){Ve()&&Ge(!1,"api")},toggle(){Ve()&&Ge(!Se,"api")},reconnect(){S.reconnectNow()},clearChat(){Jn=!1,l.clear(),s.clear(),i.clear(),c.clear(),S.clearMessages(),o.layout?.topFade&&(j.scrollTop=0),j.removeAttribute("data-persona-top-fade"),It.clear(),On();try{localStorage.removeItem(Es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Es}`)}catch(a){console.error("[AgentWidget] Failed to clear default localStorage:",a)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Es)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),v?.clear&&ha(()=>v.clear(),"[AgentWidget] Failed to clear storage adapter:"),x={},Me.syncFromMetadata(),_e?.clearAttachments(),ba(),Or(void 0),Wn(void 0),lr(),Lt?.clear(),wn?.reset(),Ot?.update()},setMessage(r){return!Z||S.isStreaming()||_n()?!1:(!Se&&Ve()&&Ge(!0,"system"),Z.value=r,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(r){if(S.isStreaming()||fr())return!1;let a=r?.trim()||Z.value.trim();return a?(!Se&&Ve()&&Ge(!0,"system"),Z.value="",Z.style.height="auto",Rn(),Wa(a,{consumeDraft:!1}),!0):!1},getComposerState(){return ie.getState()},setQuote(r){let a=r?.text?.trim();a&&Wn({...r,text:a})},clearQuote(){Wn(void 0)},startVoiceRecognition(){return S.isStreaming()?!1:Nt(o.voiceRecognition?.provider)?(S.isVoiceActive()||S.isBargeInActive()||(!Se&&Ve()&&Ge(!0,"system"),Ie.manuallyDeactivated=!1,Tn(),S.toggleVoice().then(()=>{Ie.active=S.isVoiceActive(),oo("user"),S.isVoiceActive()&&ns()})),!0):Nn?!0:qg()?(!Se&&Ve()&&Ge(!0,"system"),Ie.manuallyDeactivated=!1,Tn(),Oa("user"),!0):!1},stopVoiceRecognition(){return Nt(o.voiceRecognition?.provider)?!S.isVoiceActive()&&!S.isBargeInActive()?!1:((S.isBargeInActive()?S.deactivateBargeIn():S.toggleVoice()).then(()=>{Ie.active=!1,Ie.manuallyDeactivated=!0,Tn(),oo("user"),lo()}),!0):Nn?(Ie.manuallyDeactivated=!0,Tn(),Do("user"),!0):!1},injectMessage(r){return!Se&&Ve()&&Ge(!0,"system"),S.injectMessage(r)},injectAssistantMessage(r){!Se&&Ve()&&Ge(!0,"system");let a=S.injectAssistantMessage(r);return Ls&&(Ls=!1,Hr&&(clearTimeout(Hr),Hr=null),setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)),a},injectUserMessage(r){return!Se&&Ve()&&Ge(!0,"system"),S.injectUserMessage(r)},injectSystemMessage(r){return!Se&&Ve()&&Ge(!0,"system"),S.injectSystemMessage(r)},injectMessageBatch(r){return!Se&&Ve()&&Ge(!0,"system"),S.injectMessageBatch(r)},injectComponentDirective(r){return!Se&&Ve()&&Ge(!0,"system"),S.injectComponentDirective(r)},injectTestMessage(r){!Se&&Ve()&&Ge(!0,"system"),S.injectTestEvent(r)},async connectStream(r,a){return S.connectStream(r,a)},__pushEventStreamEvent(r){Jt&&(zi(),Xl(r.type,r.payload))},showEventStream(){Jt&&cc()},hideEventStream(){Sn&&_r()},isEventStreamVisible(){return Sn},listConversations(r){return S.listConversations(r)},getActiveConversationId(){return S.getActiveConversationId()},openConversation(r,a){return Fn(d=>d.openHistoryConversation(r,{focusComposer:a?.focus===!0}))},startNewConversation(r){return Fn(a=>a.startNewConversation({focusComposer:r?.focus===!0}))},warmSession(){td()},deleteConversation(r){return Fn(a=>a.deleteHistoryConversation(r))},renameConversation(r,a){return Fn(d=>d.updateHistoryConversation(r,{title:a}))},setConversationStarred(r,a){return Fn(d=>d.updateHistoryConversation(r,{starred:a}))},clearConversationHistory(r){return Fn(a=>a.clearConversationHistory(r))},resetHistoryIdentity(){return Fn(r=>r.resetHistoryIdentity())},async getVisitorToken(){let r=gn;if(!r)return null;let a=await r.get();return r===gn?a:null},getHistoryIdentityStatus(){let r=tt?.historyProvider;return r?r.getIdentityStatus():ri()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(r){return ri()?Fn(a=>a.openHistory({...r?.returnSurface?{returnSurface:r.returnSurface}:{},...r?.focus!==void 0?{focus:r.focus}:{}})):Promise.resolve()},hideHistory(r){tt?.closeHistory(r?.restoreFocus!==void 0?{restoreFocus:r.restoreFocus}:void 0)},isHistoryVisible(){return Rs},showArtifacts(){zt(o)&&(Jn=!1,Nr=!0,En(),Ee?.setMobileOpen(!0))},hideArtifacts(){zt(o)&&(Jn=!0,En())},upsertArtifact(r){return zt(o)?(as(o.features?.artifacts,{artifactType:r.artifactType,...r.artifactType==="markdown"&&r.file?{file:r.file}:{},...r.presentation?{presentation:r.presentation}:{}})==="panel"&&(Jn=!1,Nr=!0),S.upsertArtifact(r)):null},selectArtifact(r){zt(o)&&S.selectArtifact(r)},clearArtifacts(){zt(o)&&S.clearArtifacts()},getArtifacts(){return S?.getArtifacts()??[]},getSelectedArtifactId(){return S?.getSelectedArtifactId()??null},focusInput(){return de&&!Se&&!Ae()||!Z?!1:(Z.focus(),!0)},async resolveApproval(r,a,d){let f=S.getMessages().find(b=>b.variant==="approval"&&b.approval?.id===r);if(!f?.approval)throw new Error(`Approval not found: ${r}`);if(f.approval.toolType==="webmcp"){S.resolveWebMcpApproval(f.id,a);return}return S.resolveApproval(f.approval,a,d)},setFollowUpSuggestions(r){sv(r)},clearFollowUpSuggestions(){tg()},getMessages(){return S.getMessages()},getStatus(){return S.getStatus()},getPersistentMetadata(){return{...x}},updatePersistentMetadata(r){$e(r)},on(r,a){return G.on(r,a)},off(r,a){G.off(r,a)},isOpen(){return Ve()&&Se},isVoiceActive(){return Ie.active},toggleReadAloud(r){S.toggleReadAloud(r)},stopReadAloud(){S.stopSpeaking()},getReadAloudState(r){return S.getReadAloudState(r)},onReadAloudChange(r){return S.onReadAloudChange(r)},getState(){return{open:Ve()&&Se,launcherEnabled:de,voiceActive:Ie.active,streaming:S.isStreaming()}},showCSATFeedback(r){!Se&&Ve()&&Ge(!0,"system");let a=ce.querySelector(".persona-feedback-container");a&&a.remove();let d=gb({onSubmit:async(m,f)=>{S.isClientTokenMode()&&await S.submitCSATFeedback(m,f),r?.onSubmit?.(m,f)},onDismiss:r?.onDismiss,...r});ce.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(r){!Se&&Ve()&&Ge(!0,"system");let a=ce.querySelector(".persona-feedback-container");a&&a.remove();let d=mb({onSubmit:async(m,f)=>{S.isClientTokenMode()&&await S.submitNPSFeedback(m,f),r?.onSubmit?.(m,f)},onDismiss:r?.onDismiss,...r});ce.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(r,a){return S.submitCSATFeedback(r,a)},async submitNPSFeedback(r,a){return S.submitNPSFeedback(r,a)},destroy(){Yc(),hr!=null&&(clearInterval(hr),hr=null),l.clear(),s.clear(),i.clear(),c.clear(),oe.forEach(r=>r()),Pe.remove(),St?.remove(),ct?.destroy(),_t?.remove(),or&&xe.removeEventListener("click",or)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let r=window.AgentWidgetBrowser,a={controller:dt,getMessages:dt.getMessages,getStatus:dt.getStatus,getMetadata:dt.getPersistentMetadata,updateMetadata:dt.updatePersistentMetadata,clearHistory:()=>dt.clearChat(),setVoiceActive:d=>d?dt.startVoiceRecognition():dt.stopVoiceRecognition()};window.AgentWidgetBrowser=a,oe.push(()=>{window.AgentWidgetBrowser===a&&(window.AgentWidgetBrowser=r)})}if(typeof window<"u"){let r=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),a=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.focusInput()};if(window.addEventListener("persona:focusInput",a),oe.push(()=>{window.removeEventListener("persona:focusInput",a)}),Jt){let q=X=>{let ae=X.detail;(!ae?.instanceId||ae.instanceId===r)&&dt.showEventStream()},K=X=>{let ae=X.detail;(!ae?.instanceId||ae.instanceId===r)&&dt.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",K),oe.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",K)})}let d=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.showHistory()},m=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.hideHistory()};window.addEventListener("persona:showHistory",d),window.addEventListener("persona:hideHistory",m),oe.push(()=>{window.removeEventListener("persona:showHistory",d),window.removeEventListener("persona:hideHistory",m)});let f=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.showArtifacts()},b=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.hideArtifacts()},D=q=>{let K=q.detail;K?.instanceId&&K.instanceId!==r||K?.artifact&&dt.upsertArtifact(K.artifact)},$=q=>{let K=q.detail;K?.instanceId&&K.instanceId!==r||typeof K?.id=="string"&&dt.selectArtifact(K.id)},F=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.clearArtifacts()};window.addEventListener("persona:showArtifacts",f),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",F),oe.push(()=>{window.removeEventListener("persona:showArtifacts",f),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",F)})}let fn=Zx(o.persistState);if(fn&&Ve()){let r=eA(fn.storage),a=`${fn.keyPrefix}widget-open`,d=`${fn.keyPrefix}widget-voice`,m=`${fn.keyPrefix}widget-voice-mode`;if(r){let f=fn.persist?.openState&&r.getItem(a)==="true",b=fn.persist?.voiceState&&r.getItem(d)==="true",D=fn.persist?.voiceState&&r.getItem(m)==="true";if(f&&(ct?.setPanelOpen(!0,"auto"),setTimeout(()=>{dt.open(),setTimeout(()=>{if(b||D)dt.startVoiceRecognition();else if(fn.persist?.focusInput){let $=t.querySelector("textarea");$&&$.focus()}},100)},0)),fn.persist?.openState&&(G.on("widget:opened",()=>{r.setItem(a,"true")}),G.on("widget:closed",()=>{r.setItem(a,"false")})),fn.persist?.voiceState&&(G.on("voice:state",$=>{r.setItem(d,$.active?"true":"false")}),G.on("user:message",$=>{r.setItem(m,$.viaVoice?"true":"false")})),fn.clearOnChatClear){let $=()=>{r.removeItem(a),r.removeItem(d),r.removeItem(m)},F=()=>$();window.addEventListener("persona:clear-chat",F),oe.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}if(Xe&&Ve()&&(ct?.setPanelOpen(!0,"auto"),setTimeout(()=>{dt.open()},0)),Yr(),!iv){let r=qa(()=>{S&&(cr++,It.clear(),un(ce,S.getMessages(),Xt))});oe.push(r)}R=()=>{S&&(cr++,It.clear(),un(ce,S.getMessages(),Xt))},S.getMessages().length>0&&Sa(),_=()=>{S&&(cr++,It.clear(),un(ce,S.getMessages(),Xt))};let yC=Dm(()=>{S&&(cr++,It.clear(),un(ce,S.getMessages(),Xt))});oe.push(yC);let bC=Wp(()=>{S&&(cr++,It.clear(),un(ce,S.getMessages(),Xt),yo()?.updateInlineArtifactBlocks(ce,dn.artifacts,{suppressTransition:!0}),En())});return oe.push(bC),dt};var Sb=(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},oA=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},rA=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},sA=(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.")},xb=(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"},Qp=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=""},Ab=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Qp(t)},Kp=t=>{t.style.transition=""},Gp=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=""},Yp=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Gl=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},iA=(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))},aA=(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)},lA=t=>{let e=ho(t),n=e.components?.panel,o=(s,i)=>s==null||s===""?i:Pt(e,s)??s;return{inset:o(n?.inset,Pl),canvasBackground:o(n?.canvasBackground,Ll)}},Mb=(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},cA=(t,e,n,o,s,i,l,c)=>{let u=Cn(i),p=u.reveal==="push",g=c!=null,y=c?.inset??"",h=c?.canvasBackground??"";iA(t,e,n,o,p),aA(t,e,n,o,u.side,p),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=u.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 C=t.ownerDocument.defaultView,E=i?.launcher?.mobileFullscreen??!0,A=i?.launcher?.mobileBreakpoint??640,I=C!=null?C.innerWidth<=A:!1;if(E&&I&&l){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Gp(e),Kp(o),Ab(o),Yp(n),Gl(s,o),Mb(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??Dt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(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"),Ab(o),oA(o,u.maxHeight),Mb(o,g&&l,y,h),u.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Gp(e),Kp(o),Yp(n),Gl(s,o);let k=u.animate?"transform 180ms ease":"none",R=u.side==="right"?"translateX(100%)":"translateX(-100%)",B=l?"translateX(0)":R;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=u.width,o.style.maxWidth=u.width,o.style.minWidth=u.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=k,o.style.transform=B,o.style.pointerEvents=l?"auto":"none",o.style.zIndex="2",u.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(u.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Kp(o),Qp(o),Gl(s,o);let k=Sb(u.width,t.clientWidth),R=Math.max(0,t.clientWidth),B=u.animate?"margin-left 180ms ease":"none",O=u.side==="right"?l?-k:0:l?0:-k;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=`${R+k}px`,e.style.transition=B,e.style.marginLeft=`${O}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${R}px`,n.style.maxWidth=`${R}px`,n.style.minWidth=`${R}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=u.width,o.style.minWidth=u.width,o.style.maxWidth=u.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="",Gp(e),Qp(o),Yp(n),Gl(s,o);let k=u.reveal==="emerge";k?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let R=l?u.width:"0px",B=u.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${g?", padding 180ms ease":""}`:"none",O=!l;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${R}`,o.style.width=R,o.style.maxWidth=R,o.style.minWidth=R,o.style.minHeight="0",rA(o,u.maxHeight),o.style.overflow=k||O?"hidden":"visible",o.style.transition=B,k){o.style.alignItems=u.side==="right"?"flex-start":"flex-end";let V=g?`calc(${Sb(u.width,t.clientWidth)}px - (2 * ${y}))`:u.width;s.style.width=V,s.style.minWidth=V,s.style.maxWidth=V,s.style.boxSizing="border-box"}}},dA=(t,e)=>{let n=t.ownerDocument.createElement("div");return xb(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){xb(n,o)},destroy(){n.remove()}}},pA=(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"),u=n.createElement("div"),p=n.createElement("aside"),g=n.createElement("div"),y=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;c.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",p.appendChild(g),o.insertBefore(l,t),u.appendChild(t);let h=null,C=()=>{h?.disconnect(),h=null},E=null,A=()=>{E=e?.launcher?.detachedPanel===!0?lA(e):null};A();let I=()=>{cA(l,c,u,p,g,e,y,E)},L=null,k=()=>{L?.(),L=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(L=Il(()=>{A(),I()}))},R=()=>{C(),Cn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{I()}),h.observe(l)))},B=!1,O=()=>{I(),R(),y&&!B&&l.dataset.personaDockMobileFullscreen!=="true"&&(B=!0,sA(l,Cn(e)))},V=l.ownerDocument.defaultView,J=()=>{O()};return V?.addEventListener("resize",J),Cn(e).reveal==="push"?(c.appendChild(u),c.appendChild(p),l.appendChild(c)):(l.appendChild(u),l.appendChild(p)),O(),k(),{mode:"docked",host:g,shell:l,syncWidgetState(_){let Q=_.launcherEnabled?_.open:!0;y!==Q&&(y=Q,O())},updateConfig(_){e=_,(e?.launcher?.enabled??!0)===!1&&(y=!0),A(),O(),k()},destroy(){V?.removeEventListener("resize",J),L?.(),L=null,C(),o.isConnected&&(i&&i.parentNode===o?o.insertBefore(t,i):o.appendChild(t)),l.remove()}}},Eb=(t,e)=>rt(e)?pA(t,e):dA(t,e);var Ni={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Tb=.15,kb=1.5,Xp="persona-preview-shell-theme",uA={load:()=>null,save:()=>{},clear:()=>{}},gA=["How do I get started?","Pricing & plans","Talk to support"];function Jp(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function mA(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 Pb(t){let e=mA(t);return`* { box-sizing: border-box; }
124
+ `)}if(!f&&!a){let ge="max-height: -moz-available !important; max-height: stretch !important;",Se=d?"":"padding-top: 1.25em !important;",be=d?"":`z-index: ${o.launcher?.zIndex??Dt} !important;`;Le.style.cssText+=ge+Se+be}ic(),vn()},Sc=()=>{t.style.setProperty("--persona-content-max-width",Ko(o,Me()))},Vu=!1;function $u(){o.layout?.topFade&&j.scrollTop>1?j.setAttribute("data-persona-top-fade","true"):j.removeAttribute("data-persona-top-fade")}let xc=()=>{$u();let r=ap(o,Me());Me()&&o.composer?.placement&&o.debug===!0&&!Vu&&(Vu=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let a=Xo();t.setAttribute("data-persona-composer-placement",r),t.setAttribute("data-persona-conversation-state",Xi),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",a.composerGap??Wl),Zi()},zu=()=>{if(Me())return;let r=rt(o),a=o.launcher?.sidebarMode??!1;if(r||a||(o.launcher?.fullHeight??!1)||!de)return;let m=t.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640;if(f&&m.innerWidth<=b)return;let D=Pr(o);le.style.height=D.height,le.style.maxHeight=D.maxHeight};wc(),Ti(t,o),Oi(t,o),_i(t,o),Sc(),xc(),er=()=>{wc(),zu(),Ti(t,o),Oi(t,o),_i(t,o),Sc(),xc(),na?t.style.setProperty("--persona-artifact-welded-outer-radius",na):t.style.removeProperty("--persona-artifact-welded-outer-radius"),Ki(),ji()};let oe=[];oe.push(()=>{Ru=!0}),oe.push(()=>{h.forEach(r=>r()),y.destroy()}),oe.push(()=>{document.removeEventListener("keydown",Ou)}),oe.push(()=>{Fs!==null&&clearTimeout(Fs)});let Bn=null,Dn=null;oe.push(()=>{Bn?.(),Bn=null,Dn?.(),Dn=null}),Us&&oe.push(()=>{Us?.disconnect(),Us=null}),oe.push(()=>{Gs?.(),Gs=null,Cc(),ot&&(ot.remove(),ot=null),Te?.element.style.removeProperty("width"),Te?.element.style.removeProperty("maxWidth"),Te?.destroy()}),Zt&&oe.push(()=>{iu=!0,Yn=null,Co!==null&&(cancelAnimationFrame(Co),Co=null),_t?.destroy(),_t=null,Lt?.destroy(),Lt=null,Rr=null});let tr=null,Uu=()=>{tr&&(tr(),tr=null),o.colorScheme==="auto"&&(tr=Rl(()=>{Ti(t,o)}))};Uu(),oe.push(()=>{tr&&(tr(),tr=null)}),oe.push(()=>{k=!0,L?.()}),oe.push(()=>{V=!0});let qu=!1;oe.push(()=>{qu=!0});let Ac=(r,a)=>{let d=mi(r,a);return d||!Bf.includes(r)?d:(cy().then(m=>{if(qu)return;Bd(m.wipe),Bd(m.glyphCycle);let f=mi(r,a);f&&yi(f,t)}).catch(()=>{}),null)},pa=o.features?.streamAnimation;if(pa?.type&&pa.type!=="none"){let r=Ac(pa.type,pa.plugins);r&&yi(r,t),oe.push(()=>Df(t))}let eo=Hi(wo),ju=Hi(tc),Ku=Hi(Bs),nr=[eo,ju,Ku];oe.push(()=>{nr.forEach(r=>r.destroy())});let or=null,x,rr=null,Gu=!1,Yu=0,Qu=null,Xu=r=>r.reduce((a,d)=>d.role==="user"?a+1:a,0),Ju=r=>{for(let a=r.length-1;a>=0;a--)if(el(r[a]))return r[a].id??null;return null},Zu=!1,av=()=>{Zu||o.debug!==!0||(Zu=!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".'))},eg=!1,tg=!1,ng=(r,a)=>{eg||o.debug!==!0||!a.enabled||a.expose||Gu||tg&&(x.isStreaming()||r.some(el)||(eg=!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.")))},sr=r=>{if(!x)return;let a=r??x.getMessages(),d=X=>{X.render([],x,Z,a)},m=X=>{nr.forEach(ae=>{ae!==X&&d(ae)})};rr&&(Xu(a)>Yu||Ju(a)!==Qu)&&(rr=null);let f=ds(o);ng(a,f);let b=f.enabled?of(a):null,D=rr??b,$=rr?"host":"agent";if(D){let X=o.suggestions?.followUps,ae=X?.placement??(X?"auto":"composer"),Fe=(ae==="auto"?Me()?"composer":"after-message":ae)==="after-message"?Ku:eo;m(Fe),Fe.render(D,x,Z,a,o.suggestionChipsConfig,{source:$,surface:"followUp",variant:X?.variant??"chip",behavior:X?.behavior??"send",overflow:X?.overflow??"wrap",maxItems:X?.maxItems??4,config:o,plugins:g,submitPrompt:Ba});return}if(a.some(X=>X.role==="user")){nr.forEach(d);return}let F=o.future?.v5Defaults===!0,q=Vs(),K=o.suggestions?.starters??(F?{}:void 0);if(K){let X=Ss(Xo(),a),ae=K.placement??"auto",He=ae==="auto"?X?"welcome":"composer":ae;if(He==="welcome"&&!X){av(),nr.forEach(d);return}let Fe=He==="welcome"?ju:eo;m(Fe),Fe.render(K.items??o.suggestionChips,x,Z,a,o.suggestionChipsConfig,{surface:"starter",variant:K.variant??(F&&!q?"chip":"card"),behavior:K.behavior??"send",overflow:K.overflow??"wrap",maxItems:K.maxItems??(F&&!q?3:4),config:o,plugins:g,submitPrompt:Ba});return}m(eo),eo.render(o.suggestionChips,x,Z,a,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:g,submitPrompt:Ba})},og=()=>{rr&&(rr=null,sr())},lv=r=>{let a=Array.isArray(r)?[...r]:[];if(!a.length){og();return}let d=x?x.getMessages():[];rr=a,Gu=!0,Yu=Xu(d),Qu=Ju(d),sr(d)},rn=!1,It=sy(),Vr=new Map,ir=new Map,To=new Map,ar=null,ko=null;function lr(){if(!ar)return;let r=ar;ar=null,ko?.destroy(),ko=null,It.delete(r),re.querySelector(`#wrapper-${r}`)?.removeAttribute("data-preserve-runtime"),x&&gn(ce,x.getMessages(),Jt)}let cr=0,cv=is()!==null,sn=Lf(),an=0,Po=null,Kt=!1,ua=!1,Lo=0,vt=null,dr=null,Mc=!1,$r=!1,pr=null,Ys=!0,ga=!1,zr=null,ma=!1,Io=()=>{ma=!0,gv()},Ec=null,dv=4,to=24,pv=80,uv=1e3,no=null,rg=()=>{t.setAttribute("data-persona-scrollbar",oc()),oc()!=="on-scroll"&&(no!==null&&clearTimeout(no),no=null,j.removeAttribute("data-persona-scrollbar-visible"))},gv=()=>{oc()==="on-scroll"&&(j.setAttribute("data-persona-scrollbar-visible",""),no!==null&&clearTimeout(no),no=setTimeout(()=>{no=null,Er(j,to)&&j.removeAttribute("data-persona-scrollbar-visible")},uv))};rg(),oe.push(()=>{no!==null&&clearTimeout(no)});let Tc=new Map,kc=!1,fa=null,we={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Mn();let sg=o.voiceRecognition?.autoResume??!1,Pc=()=>x.isVoiceActive()||x.isBargeInActive(),ig=!1,oo=r=>{G.emit("voice:state",{active:we.active,source:r,timestamp:Date.now()})},Gt=()=>{$e(r=>({...r,voiceState:{active:we.active,timestamp:Date.now(),manuallyDeactivated:we.manuallyDeactivated}}))},mv=()=>{if(o.voiceRecognition?.enabled===!1)return;let r=Gp(S.voiceState),a=!!r.active,d=Number(r.timestamp??0);we.manuallyDeactivated=!!r.manuallyDeactivated,a&&Date.now()-d<Jx&&setTimeout(()=>{we.active||(we.manuallyDeactivated=!1,Ot(o.voiceRecognition?.provider)?x.toggleVoice().then(()=>{we.active=Pc(),oo("restore"),we.active?ns():(Gt(),Wa(Zx,1e4))}):Fa("restore"))},Ot(o.voiceRecognition?.provider)?0:1e3)},ag=r=>{ig=!r.persisted,we.active&&Gt()};typeof window<"u"&&(window.addEventListener("pagehide",ag),oe.push(()=>window.removeEventListener("pagehide",ag)));let fv=()=>x?wb(x.getMessages()).filter(r=>!r.__skipPersist):[],ha=null,lg=(r,a)=>{typeof console<"u"&&console.error(r,a)},ya=(r,a)=>{let d=()=>{try{let D=r();return!D||typeof D.then!="function"?null:Promise.resolve(D).catch($=>{lg(a,$)})}catch(D){return lg(a,D),null}},m=ha,f=m?m.then(()=>d()??void 0):d();if(!f)return;let b=f.finally(()=>{ha===b&&(ha=null)});ha=b};function Ur(r){if(!v?.save)return;let a=r?wb(r):x?fv():[],d=T&&x?.getResumableHandle();d&&(S={...S,durableResume:{executionId:d.executionId,after:d.lastEventId}});let m={messages:a,metadata:S,artifacts:pn.artifacts,selectedArtifactId:pn.selectedId,...ur?{draft:ur}:{}};ya(()=>v.save(m),"[AgentWidget] Failed to persist state:")}let ur,ba=()=>!v?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Qs=$h({write:()=>{if(!ba())return;let r=ie.getState(),a=Nh({text:r.text,mentionRefs:r.mentionRefs,contentSegments:id(),selectedModelId:r.selectedModelId,activeModeIds:r.activeModeIds,quote:r.quote});JSON.stringify(a)!==JSON.stringify(ur)&&(ur=a,Ur())}});function cg(){ba()&&Qs.schedule()}function Lc(){Qs.flush()}function dg(r){if(!ba())return;let a=Vh(r,{mentionSourceIds:(o.contextMentions?.sources??[]).map(d=>d.id),modelIds:(o.composer?.models??[]).map(d=>d.id),modes:o.composer?.modes??[]});a&&(ur=r,Z&&!Z.value&&(Z.value=a.text,Z.dispatchEvent(new Event("input",{bubbles:!0})),Rn()),a.selectedModelId&&(ie.setSelectedModelId(a.selectedModelId),Ao?.repaint()),ea(a.activeModeIds??[]),a.quote&&Wn(a.quote),Qs.cancel())}function va(){Qs.cancel(),ur&&(ur=void 0,ba()&&Ur())}let qr=null,pg=()=>Le.querySelector("#persona-scroll-container")||j,jr=()=>{qr!==null&&(cancelAnimationFrame(qr),qr=null),Kt=!1},ug=()=>{Po!==null&&(cancelAnimationFrame(Po),Po=null),ua=!1,jr()},hv=()=>rn&&Hc()&&(on()!=="anchor-top"||uu()),Ic=()=>{let r=Ds()||"Jump to latest",a=hv();ft.toggleAttribute("data-persona-scroll-to-bottom-streaming",a),Lo>0?(Qo.textContent=String(Lo),Qo.style.display="",ft.setAttribute("aria-label",`${r} (${Lo} new)`)):(Qo.textContent="",Qo.style.display="none",ft.setAttribute("aria-label",a?`${r} (response streaming below)`:r))},gg=()=>{Lo!==0&&(Lo=0,Ic())},yv=()=>{let r=vt?.spacerHeight??0;return r<=0?Er(j,to):Sa(r)-j.scrollTop-j.clientHeight<=to},Hc=()=>xo()?!sn.isFollowing():!yv(),Rc=()=>!!x&&x.getMessages().length>0,Ht=()=>{if(!qb()||Ob()){ft.parentNode&&ft.remove(),ft.style.display="none";return}ft.parentNode!==re&&re.appendChild(ft),Jo();let a=uo(j)>0&&Hc()&&Rc();a?Ic():gg(),ft.style.display=a?"":"none"},Kr=()=>{sn.pause()&&(ug(),Ht())},On=()=>{sn.resume(),gg(),Ht()},Ho=(r=!1)=>{xo()&&Rc()&&sn.isFollowing()&&(!r&&!rn||(Po!==null&&(cancelAnimationFrame(Po),Po=null),ua=!0,Po=requestAnimationFrame(()=>{Po=null,ua=!1,sn.isFollowing()&&bv(pg(),r?220:140)})))},mg=(r,a,d,m=()=>!0)=>{let f=r.scrollTop,b=a(),D=b-f;if(jr(),Math.abs(D)<1){Kt=!0,r.scrollTop=b,an=r.scrollTop,Kt=!1;return}let $=performance.now();Kt=!0;let F=K=>1-Math.pow(1-K,3),q=K=>{if(!m()){jr();return}let X=a();X!==b&&(b=X,D=b-f);let ae=K-$,He=Math.min(ae/d,1),Fe=F(He),De=f+D*Fe;r.scrollTop=De,an=r.scrollTop,He<1?qr=requestAnimationFrame(q):(r.scrollTop=b,an=r.scrollTop,qr=null,Kt=!1)};qr=requestAnimationFrame(q)},bv=(r,a=500)=>{let d=uo(r)-r.scrollTop;if(Math.abs(d)<1){an=r.scrollTop;return}if(Math.abs(d)>=pv){jr(),Kt=!0,r.scrollTop=uo(r),an=r.scrollTop,Kt=!1;return}mg(r,()=>uo(r),a,()=>sn.isFollowing())},Wc=()=>{if(!Rc()){Ht();return}let r=pg();Kt=!0,r.scrollTop=uo(r),an=r.scrollTop,Kt=!1,Ht()},gr=r=>{let a=0,d=r;for(;d&&d!==j;)a+=d.offsetTop,d=d.offsetParent;return a},vv=()=>{let r=j.getRootNode();return(typeof r.getSelection=="function"?r.getSelection():null)??j.ownerDocument.getSelection()},Ca=()=>Rf(vv(),j),Bc=()=>{if(jb()!=="last-user-turn")return!1;let r=x?.getMessages()??[];if(r.length<2)return!1;let a=[...r].reverse().find(b=>b.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=j.querySelector(`[data-message-id="${d}"]`);if(!m)return!1;let f=Math.min(Math.max(0,gr(m)-Os()),uo(j));return Kt=!0,j.scrollTop=f,an=j.scrollTop,Kt=!1,on()==="follow"&&!Er(j,to)&&sn.pause(),Ht(),!0},wa=r=>{let a=Math.max(0,Math.round(r));dn.style.height=`${a}px`,dn.style.display=a>0?"":"none",vt&&(vt.spacerHeight=Math.max(0,r))},Sa=r=>{let a=parseFloat(getComputedStyle(j).paddingBottom)||0,d=0;for(let f of Array.from(j.children)){if(f===dn||f.offsetHeight===0)continue;let b=gr(f)+f.offsetHeight;b>d&&(d=b)}let m=j.scrollHeight-r;return d>0?Math.min(d+a,m):m},Cv=()=>{if(!vt||vt.spacerHeight<=0)return;let r=Sa(vt.spacerHeight),a=Math.max(0,Math.round(j.scrollTop)+j.clientHeight-r+to);a<vt.spacerHeight&&(wa(a),Ht())},mr=()=>{dr!==null&&(cancelAnimationFrame(dr),dr=null),jr(),vt=null,dn.style.height="0px",dn.style.display="none"},fg=r=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Dc=r=>j.querySelector(`[data-message-id="${fg(r)}"]`),hg=r=>{dr!==null&&cancelAnimationFrame(dr),dr=requestAnimationFrame(()=>{dr=null;let a=fg(r),d=j.querySelector(`[data-message-id="${a}"]`);if(!d)return;let m=gr(d),f=vt?.spacerHeight??0,b=Sa(f),{targetScrollTop:D,spacerHeight:$}=Wd({anchorOffsetTop:m,topOffset:Os(),viewportHeight:j.clientHeight,contentHeight:b,slack:to});vt={initialSpacerHeight:$,contentHeightAtAnchor:b,spacerHeight:$},wa($),mg(j,()=>d.isConnected?Math.max(0,gr(d)-Os()):D,220)})},Gr=()=>{if(on()!=="anchor-top"||!vt||!zr)return;let r=Dc(zr);if(!r)return;jr();let a=vt.spacerHeight,d=Sa(a),{targetScrollTop:m,spacerHeight:f}=Wd({anchorOffsetTop:gr(r),topOffset:Os(),viewportHeight:j.clientHeight,contentHeight:d,slack:to});vt={initialSpacerHeight:f,contentHeightAtAnchor:d,spacerHeight:f},wa(f),Kt=!0,j.scrollTop=m,an=j.scrollTop,Kt=!1,Ht()},wv=()=>{if(xo()){if(!sn.isFollowing()||Er(j,1))return;Ho(!rn);return}if(vt&&vt.initialSpacerHeight>0){let r=j.scrollHeight-vt.spacerHeight,a=Wf({initialSpacerHeight:vt.initialSpacerHeight,contentHeightAtAnchor:vt.contentHeightAtAnchor,currentContentHeight:r});a!==vt.spacerHeight&&wa(a)}Ht()},Sv=r=>{let a=on();a==="follow"?(On(),Ho(!0)):a==="anchor-top"&&(Ys=!1,ga=!0,ma=!1,zr=r,hg(r))},xv=()=>{if(on()==="anchor-top"){if(ga){Ys=!1;return}Ys=!0,mr(),On(),Ho(!0)}},Av=96,Mv=r=>{if(pr===null)return!0;let a=Dc(pr),d=Dc(r);if(!a||!d)return!0;let m=gr(d)-gr(a);return Os()+m>j.clientHeight-Av},Ev=r=>{if(on()!=="anchor-top"||!ga||ma||Ca())return;let a=pr===null;for(let d of r){if(!a){d.id===pr&&(a=!0);continue}if(Pf(d)){if(d.id===zr||!Mv(d.id))return;zr=d.id,hg(d.id);return}}},Tv=r=>{let a=new Map;r.forEach(d=>{let m=Tc.get(d.id);a.set(d.id,{streaming:d.streaming,role:d.role}),!m&&d.role==="assistant"&&(G.emit("assistant:message",d),!$r&&(on()!=="anchor-top"||uu())&&Hc()&&(Lo+=1,Ic(),Ht(),Ns(Lo===1?"1 new message below.":`${Lo} new messages below.`))),d.role==="assistant"&&m?.streaming&&d.streaming===!1&&G.emit("assistant:complete",d),d.variant==="approval"&&d.approval&&(m?d.approval.status!=="pending"&&G.emit("approval:resolved",{approval:d.approval,decision:d.approval.status}):G.emit("approval:requested",{approval:d.approval,message:d}))}),Tc.clear(),a.forEach((d,m)=>{Tc.set(m,d)})},Xs=(r,a)=>{let d=a==="user"?"user":"assistant",m=o.layout?.messages?.[d],f=m?.width??"content",b=m?.maxWidth??(f==="full"?`var(--persona-message-${d}-max-width, 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-${f}`),r.classList.toggle("persona-justify-end",a==="user"),r.setAttribute("data-message-role",a),r.setAttribute("data-message-width",f),b?r.style.setProperty("--persona-message-row-max-width",b):r.style.removeProperty("--persona-message-row-max-width")},ro=(r,a)=>{let d=document.createElement("div");return d.className="persona-flex",d.id=`wrapper-${r}`,d.setAttribute("data-wrapper-id",r),Xs(d,a),d},kv=(r,a,d)=>{let m=new Set;for(let M of a){let me=M.variant==="tool"?"tool":M.variant==="reasoning"?"reasoning":null;if(!me||qo(o,me)!=="row")continue;let fe=me==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;fe?.expandable!==!1&&(m.add(M.id),l.observe(M,me,me==="tool"?s:i,fe))}let f=document.createElement("div"),D=(()=>{let M=g.find(me=>me.renderLoadingIndicator);if(M?.renderLoadingIndicator)return M.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),$=(M,me)=>me==null?!1:typeof me=="string"?(M.textContent=me,!0):(M.appendChild(me),!0),F=new Set,q=new Map,K=new Set,X=g.some(M=>M.renderAskUserQuestion),ae=[],He=[],Fe=o.enableComponentStreaming!==!1,De=o.approval!==!1,Yt=[],nt=o.messageActions,it=nt?.showRegenerate===!0&&nt.enabled!==!1&&un.current?.isStreaming()!==!0?ch(a):null,Nt=nt?.showEdit===!0&&nt.enabled!==!1,pt=nt?.showQuote===!0&&nt.enabled!==!1,ze=null,Vn=o.features?.reasoningDisplay?.completedVisibility,$n=M=>Vn==="removed"?!0:Vn==="removed-when-short"?Gm(M,o.features?.reasoningDisplay?.shortThinkThreshold):!1,yn=o.features?.toolCallDisplay?.completedVisibility==="removed",bn=M=>M.variant==="reasoning"&&M.reasoning?.status==="complete"?$n(M.reasoning):yn&&M.variant==="tool"&&M.toolCall?.status==="complete";if(a.forEach(M=>{if(bn(M))return;if(F.add(M.id),q.set(M.id,M.role),ar===M.id&&ko){let ye=ro(M.id,M.role);ye.setAttribute("data-persona-message-edit-stub","true"),ye.setAttribute("data-preserve-runtime","true"),f.appendChild(ye),ze={messageId:M.id,element:ko.element};return}let me=X&&cs(M),fe=De&&M.variant==="approval"&&!!M.approval,U=!me&&M.role==="assistant"&&!M.variant&&Fe&&Kp(M);!fe&&To.has(M.id)&&(r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime"),To.delete(M.id)),!U&&ir.has(M.id)&&(r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime"),ir.delete(M.id));let Ue=cs(M)?`:${M.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${M.agentMetadata?.askUserQuestionAnswers?Object.keys(M.agentMetadata.askUserQuestionAnswers).length:0}`:"",mt={canRegenerate:it===M.id,canEdit:Nt&&Ud(M),canQuote:pt&&!M.variant&&(M.content?.trim().length??0)>0},Bt=`${mt.canRegenerate?"r":""}${mt.canEdit?"e":""}${mt.canQuote?"q":""}`,At=ry(M,cr)+Ue+`:${Bt}`,Ye=me||fe||U?null:iy(It,M.id,At);if(Ye){f.appendChild(Ye.cloneNode(!0)),cs(M)&&M.toolCall?.id&&M.agentMetadata?.awaitingLocalTool===!0&&!M.agentMetadata?.askUserQuestionAnswered&&(K.add(M.toolCall.id),vc(M));return}let ut=null,Ct=g.find(ye=>!!(M.variant==="reasoning"&&ye.renderReasoning||M.variant==="tool"&&ye.renderToolCall||!M.variant&&ye.renderMessage)),ue=o.layout?.messages;if(cs(M)&&M.agentMetadata?.askUserQuestionAnswered===!0){Vr.delete(M.id),r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime");return}if(el(M)&&ds(o).enabled)return;if(cs(M)&&o.features?.askUserQuestion?.enabled!==!1){let ye=g.find(wt=>typeof wt.renderAskUserQuestion=="function");if(ye&&un.current){let wt=Vr.get(M.id),vn=wt!==At,Mt=null;if(vn){let{payload:Se,complete:be}=tf(M),Vo=M.id,ht=()=>un.current?.getMessages().find(Qt=>Qt.id===Vo);Mt=ye.renderAskUserQuestion({message:M,payload:Se,complete:be,resolve:Qt=>{let co=ht();co&&un.current?.resolveAskUserQuestion(co,Qt)},dismiss:()=>{let Qt=ht();Qt?.agentMetadata?.awaitingLocalTool&&(un.current?.markAskUserQuestionResolved(Qt),un.current?.resolveAskUserQuestion(Qt,"(dismissed)"))},config:o})}let qe=wt!=null;if(vn&&Mt===null&&!qe){M.agentMetadata?.awaitingLocalTool===!0&&!M.agentMetadata?.askUserQuestionAnswered&&(K.add(M.toolCall.id),vc(M));return}let ge=ro(M.id,M.role);ge.setAttribute("data-ask-plugin-stub","true"),ge.setAttribute("data-preserve-runtime","true"),f.appendChild(ge),ae.push({messageId:M.id,fingerprint:At,bubble:Mt});return}else{M.agentMetadata?.awaitingLocalTool===!0&&!M.agentMetadata?.askUserQuestionAnswered&&(K.add(M.toolCall.id),vc(M));return}}else if(fe){let ye=O();if(!ye){f.appendChild(ro(M.id,M.role));return}let wt=g.find(ge=>typeof ge.renderApproval=="function")??I,Mt=To.get(M.id)!==At,qe=null;if(Mt&&wt?.renderApproval){let ge=M.id,Se=(be,Vo)=>{let ht=un.current?.getMessages().find(Qt=>Qt.id===ge);ht?.approval&&(ht.approval.toolType==="webmcp"?un.current?.resolveWebMcpApproval(ht.id,be):un.current?.resolveApproval(ht.approval,be,Vo))};qe=wt.renderApproval({message:M,defaultRenderer:()=>ye.createApprovalBubble(M,o,c),config:o,approve:be=>Se("approved",be),deny:be=>Se("denied",be)})}if(Mt&&qe===null)r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime"),To.delete(M.id),ut=ye.createApprovalBubble(M,o,c);else{let ge=ro(M.id,M.role);ge.setAttribute("data-approval-plugin-stub","true"),ge.setAttribute("data-preserve-runtime","true"),f.appendChild(ge),Yt.push({messageId:M.id,fingerprint:At,bubble:qe});return}}else if(Ct)if(M.variant==="reasoning"&&M.reasoning&&Ct.renderReasoning){if(!Is)return;ut=Ct.renderReasoning({message:M,defaultRenderer:()=>Pp(M,o,i),config:o})}else if(M.variant==="tool"&&M.toolCall&&Ct.renderToolCall){if(!Hs)return;ut=Ct.renderToolCall({message:M,defaultRenderer:()=>Rp(M,o,s),config:o})}else Ct.renderMessage&&(ut=Ct.renderMessage({message:M,defaultRenderer:()=>{let ye=bp(M,d,ue,o.messageActions,Wr,{loadingIndicatorRenderer:D,widgetConfig:o,actionEligibility:mt});return M.role!=="user"&&Q(ye,M,o,x),ye},config:o}));if(!ut&&U){let ye=fb(M);if(ye){let wt=ir.get(M.id),vn=wt!==At,Mt=o.wrapComponentDirectiveInBubble!==!1&&go.getOptions(ye.component)?.bubbleChrome!==!1,qe=null;if(vn){let ge=gb(ye,{config:o,message:M,transform:d});if(ge&&ye.component==="PersonaArtifactInline"){let Se=ge.hasAttribute("data-artifact-inline")?ge:ge.querySelector("[data-artifact-inline]"),be=Se?.getAttribute("data-artifact-inline")??"",Vo=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(be):be,ht=be?r.querySelector(`#wrapper-${M.id}`)?.querySelector(`[data-artifact-inline="${Vo}"]`)??null:null;Se&&ht&&ht!==Se&&yo()?.hasLiveInlineArtifactBlock(ht)&&(Se===ge?ge=ht:Se.replaceWith(ht))}if(ge)if(Mt){let Se=document.createElement("div");if(Se.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Se.id=`bubble-${M.id}`,Se.setAttribute("data-message-id",M.id),M.content&&M.content.trim()){let be=document.createElement("div");be.className="persona-mb-3 persona-text-sm persona-leading-relaxed",be.innerHTML=d({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),Se.appendChild(be)}Se.appendChild(ge),qe=Se}else{let Se=document.createElement("div");if(Se.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Se.id=`bubble-${M.id}`,Se.setAttribute("data-message-id",M.id),Se.setAttribute("data-persona-component-directive","true"),M.content&&M.content.trim()){let be=document.createElement("div");be.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",be.innerHTML=d({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),Se.appendChild(be)}Se.appendChild(ge),qe=Se}}if(qe||wt!=null){let ge=ro(M.id,M.role);ge.setAttribute("data-component-directive-stub","true"),ge.setAttribute("data-preserve-runtime","true"),f.appendChild(ge),He.push({messageId:M.id,fingerprint:At,bubble:qe});return}}}if(!ut)if(M.variant==="reasoning"&&M.reasoning){if(!Is)return;ut=Pp(M,o,i)}else if(M.variant==="tool"&&M.toolCall){if(!Hs)return;ut=Rp(M,o,s)}else if(M.variant==="approval"&&M.approval){if(o.approval===!1)return;let ye=O();if(!ye)return;ut=ye.createApprovalBubble(M,o,c)}else{let ye=o.layout?.messages;ye?.renderUserMessage&&M.role==="user"?ut=ye.renderUserMessage({message:M,config:o,streaming:!!M.streaming}):ye?.renderAssistantMessage&&M.role==="assistant"?ut=ye.renderAssistantMessage({message:M,config:o,streaming:!!M.streaming}):ut=bp(M,d,ye,o.messageActions,Wr,{loadingIndicatorRenderer:D,widgetConfig:o,actionEligibility:mt}),M.role!=="user"&&ut&&Q(ut,M,o,x)}let Qe=ro(M.id,M.role);Qe.appendChild(ut),ay(It,M.id,At,Qe),f.appendChild(Qe)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(me=>{let fe=me.getAttribute("data-persona-ask-sheet-for");fe&&!K.has(fe)&&Md(We.composerOverlay,fe)}),o.features?.toolCallDisplay?.grouped){let M=[],me=[],fe=o.features.toolCallDisplay.groupedMode==="summary";a.forEach(U=>{if(U.variant==="tool"&&U.toolCall&&Hs){if(yn&&U.toolCall.status==="complete")return;me.push(U);return}U.variant==="reasoning"&&(!Is||U.reasoning?.status==="complete"&&$n(U.reasoning))||((me.length>1||fe&&me.length>0)&&M.push(me),me=[])}),(me.length>1||fe&&me.length>0)&&M.push(me),M.forEach(U=>{let Ue=U.map(ue=>Array.from(f.children).find(Qe=>Qe instanceof HTMLElement&&Qe.getAttribute("data-wrapper-id")===ue.id)).filter(ue=>!!ue);if(Ue.length<(fe?1:2))return;let mt=ro(`tool-group-${U[0].id}`,"assistant");if(mt.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let ue=`tool-group-${U[0].id}`,Qe=U.some(qe=>qe.toolCall?.status!=="complete"),ye={...U[0],id:ue,toolCall:{id:ue,name:`${U.length} tools`,status:Qe?"running":"complete",chunks:U.flatMap(qe=>qe.toolCall?.chunks??[]),success:!U.some(qe=>qe.toolCall?.success===!1)}};m.add(ue),l.observe(ye,"tool",s,o.features.toolCallDisplay);let wt=`${Qe?"Using":"Used"} ${U.length} tools`,vn=o.toolCall?.renderGroupedSummary?.({messages:U,toolCalls:U.map(qe=>qe.toolCall),defaultSummary:wt,config:o}),Mt=Vf(ye,o,s.has(ue),vn??wt);Mt.bubble.classList.add("persona-tool-group"),Mt.body.dataset.personaToolGroupStack="true",Ue[0].before(mt),mt.appendChild(Mt.bubble),Ue.forEach((qe,ge)=>{qe.style.setProperty("--persona-message-row-max-width","100%"),qe.style.setProperty("--persona-activity-stagger",`${ge*40}ms`),qe.classList.add("persona-activity-group-child"),Mt.body.appendChild(qe)});return}let Bt=document.createElement("div");Bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Bt.setAttribute("data-persona-tool-group","true");let At=document.createElement("div");At.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",At.id=`tool-group-summary-${U[0].id}`;let Ye=`Called ${U.length} ${U.length===1?"tool":"tools"}`,ut=o.toolCall?.renderGroupedSummary?.({messages:U,toolCalls:U.map(ue=>ue.toolCall).filter(ue=>!!ue),defaultSummary:Ye,config:o});$(At,ut)||(At.textContent=Ye);let Ct=document.createElement("div");Ct.className="persona-tool-group-stack persona-flex persona-flex-col",Ct.id=`tool-group-stack-${U[0].id}`,Ct.setAttribute("data-persona-tool-group-stack","true"),Bt.appendChild(At),fe||Bt.appendChild(Ct),mt.appendChild(Bt),Ue[0].before(mt),Ue.forEach((ue,Qe)=>{if(fe){ue.remove();return}ue.style.setProperty("--persona-message-row-max-width","100%");let ye=document.createElement("div");ye.className="persona-tool-group-item persona-relative",ye.setAttribute("data-persona-tool-group-item","true"),Qe<Ue.length-1&&ye.setAttribute("data-persona-tool-group-connector","true"),ye.appendChild(ue),Ct.appendChild(ye)})})}l.prune(m),ly(It,F);let Fo=M=>M.variant==="tool"&&!Hs||M.variant==="reasoning"&&!Is||bn(M),zn=a.some(M=>M.role==="assistant"&&M.streaming&&!Fo(M)),kn=a.length-1;for(;kn>=0&&Fo(a[kn]);)kn--;let No=kn>=0?a[kn]:void 0,pi=kn<a.length-1,vr=No?.role==="assistant"&&!No.streaming&&No.variant!=="approval"&&!pi;if(rn&&a.some(M=>M.role==="user")&&!zn&&!vr){let M={config:o,streaming:!0,location:"standalone",defaultRenderer:Bi},me=g.find(U=>U.renderLoadingIndicator),fe=null;if(me?.renderLoadingIndicator&&(fe=me.renderLoadingIndicator(M)),fe===null&&o.loadingIndicator?.render&&(fe=o.loadingIndicator.render(M)),fe===null&&(fe=Bi()),fe){let U=document.createElement("div"),Ue=o.loadingIndicator?.showBubble!==!1,mt=o.layout?.messages?.layout??"bubble";U.className=Ue?Di("assistant",mt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),U.setAttribute("data-typing-indicator","true"),Ue&&(U.style.color="var(--persona-message-assistant-text, var(--persona-text))",mt!=="flat"&&(U.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",U.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),U.appendChild(fe);let Bt=ro("typing-indicator","assistant");Bt.appendChild(U),f.appendChild(Bt)}}if(!rn&&a.length>0){let M=a[a.length-1],me={config:o,lastMessage:M,messageCount:a.length},fe=g.find(Ue=>Ue.renderIdleIndicator),U=null;if(fe?.renderIdleIndicator&&(U=fe.renderIdleIndicator(me)),U===null&&o.loadingIndicator?.renderIdle&&(U=o.loadingIndicator.renderIdle(me)),U){let Ue=document.createElement("div"),mt=o.loadingIndicator?.showBubble!==!1;Ue.className=mt?["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(" "),Ue.setAttribute("data-idle-indicator","true"),Ue.appendChild(U);let Bt=ro("idle-indicator","assistant");Bt.appendChild(Ue),f.appendChild(Bt)}}if(Xf(f),Bl(r,f),Od(r),ze){let{messageId:M,element:me}=ze,fe=r.querySelector(`#wrapper-${M}`);fe&&me.parentElement!==fe&&(Xs(fe,q.get(M)??"user"),fe.replaceChildren(me))}if(ae.length>0)for(let{messageId:M,fingerprint:me,bubble:fe}of ae){let U=r.querySelector(`#wrapper-${M}`);U&&(Xs(U,q.get(M)??"assistant"),fe!==null&&(U.replaceChildren(fe),U.setAttribute("data-bubble-fp",me),Vr.set(M,me)))}if(Vr.size>0)for(let M of Vr.keys())F.has(M)||Vr.delete(M);if(He.length>0)for(let{messageId:M,fingerprint:me,bubble:fe}of He){let U=r.querySelector(`#wrapper-${M}`);U&&(Xs(U,q.get(M)??"assistant"),fe!==null&&(U.replaceChildren(fe),U.setAttribute("data-bubble-fp",me),ir.set(M,me)))}if(ir.size>0)for(let M of ir.keys())F.has(M)||ir.delete(M);if(Yt.length>0)for(let{messageId:M,fingerprint:me,bubble:fe}of Yt){let U=r.querySelector(`#wrapper-${M}`);U&&(Xs(U,q.get(M)??"assistant"),fe!==null&&(U.replaceChildren(fe),U.setAttribute("data-bubble-fp",me),To.set(M,me)))}if(To.size>0)for(let M of To.keys())F.has(M)||To.delete(M)},Oc=!1,xa=()=>{Oc||(Oc=!0,Tr().catch(()=>{}),Nm().catch(()=>{Oc=!1}))},gn=(r,a,d)=>{a.length>0&&xa(),kv(r,a,d),Hu()},Js=null,Pv=()=>{if(Js)return;let r=d=>{let m=d.composedPath();m.includes(Le)||St&&m.includes(St)||Ge(!1,"user")};Js=r,(t.ownerDocument??document).addEventListener("pointerdown",r,!0)},yg=()=>{if(!Js)return;(t.ownerDocument??document).removeEventListener("pointerdown",Js,!0),Js=null};oe.push(()=>yg());let Zs=null,Lv=()=>{if(Zs)return;let r=d=>{d.key==="Escape"&&(d.isComposing||Ge(!1,"user"))};Zs=r,(t.ownerDocument??document).addEventListener("keydown",r,!0)},bg=()=>{if(!Zs)return;(t.ownerDocument??document).removeEventListener("keydown",Zs,!0),Zs=null};oe.push(()=>bg());let ei=!1,vg=new Set,Iv=()=>{let r=o.launcher?.composerBar?.peek?.streamAnimation;return r||o.features?.streamAnimation},Yr=()=>{if(!Me())return;let r=We.peekBanner,a=We.peekTextNode;if(!r||!a)return;if(xe){r.classList.remove("persona-pill-peek--visible");return}let d=x?.getMessages()??[],m;for(let nt=d.length-1;nt>=0;nt--){let it=d[nt];if(it.role==="assistant"&&it.content){m=it;break}}if(!m){r.classList.remove("persona-pill-peek--visible");return}let f=m.content,b=!!m.streaming,D=Iv(),$=pl(D),F=$.type!=="none"?Ac($.type,D?.plugins):null,q=F?.isAnimating?.(m)===!0,K=F!==null&&(b||q);K&&F&&!vg.has(F.name)&&(yi(F,t),vg.add(F.name));let X=K&&F?.containerClass?F.containerClass:null,ae=a.dataset.personaPeekStreamClass??null;ae&&ae!==X&&(a.classList.remove(ae),delete a.dataset.personaPeekStreamClass),X&&ae!==X&&(a.classList.add(X),a.dataset.personaPeekStreamClass=X),K?(a.style.setProperty("--persona-stream-step",`${$.speed}ms`),a.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(a.style.removeProperty("--persona-stream-step"),a.style.removeProperty("--persona-stream-duration"));let He=K?ul(f,$.buffer,F,m,b):f;if(K&&$.placeholder==="skeleton"&&b&&(!He||!He.trim())){let nt=document.createElement("div"),it=hi();it.classList.add("persona-pill-peek__skeleton"),nt.appendChild(it),Bl(a,nt)}else{let nt=Math.max(0,He.length-100),it=He.length>100?He.slice(-100):He,Nt=Ga(it);if(!K||!F){let pt=He.length>100?`\u2026${it}`:it;a.textContent!==pt&&(a.textContent=pt)}else{let pt=Nt;(F.wrap==="char"||F.wrap==="word")&&(pt=fi(Nt,F.wrap,`peek-${m.id}`,{skipTags:F.skipTags,startIndex:nt}));let ze=document.createElement("div");if(ze.innerHTML=pt,F.useCaret&&it.length>0){let Vn=gl(),$n=ze.querySelectorAll(".persona-stream-char, .persona-stream-word"),yn=$n[$n.length-1];yn?.parentNode?yn.parentNode.insertBefore(Vn,yn.nextSibling):ze.appendChild(Vn)}Bl(a,ze),F.onAfterRender?.({container:a,bubble:r,messageId:m.id,message:m,speed:$.speed,duration:$.duration})}}let Yt=rn||ei;r.classList.toggle("persona-pill-peek--visible",Yt)};if(Me()){let r=We.peekBanner;if(r){let m=f=>{f.preventDefault(),f.stopPropagation(),Ge(!0,"user")};r.addEventListener("pointerdown",m),oe.push(()=>{r.removeEventListener("pointerdown",m)})}let a=()=>{ei||(ei=!0,Yr())},d=()=>{ei&&(ei=!1,Yr())};le.addEventListener("pointerenter",a),le.addEventListener("pointerleave",d),oe.push(()=>{le.removeEventListener("pointerenter",a),le.removeEventListener("pointerleave",d)}),St&&(St.addEventListener("pointerenter",a),St.addEventListener("pointerleave",d),oe.push(()=>{St.removeEventListener("pointerenter",a),St.removeEventListener("pointerleave",d)}))}let Hv=r=>{let a=o.launcher?.composerBar??{},d=a.expandedSize??"anchored",m=a.bottomOffset??"16px",f=a.collapsedMaxWidth,b=a.expandedMaxWidth??"880px",D=a.expandedTopOffset??"5vh",$=a.modalMaxWidth??"880px",F=a.modalMaxHeight??"min(90vh, 800px)",q="calc(100vw - 32px)",K="var(--persona-pill-area-height, 80px)",X=Le.style;if(X.left="",X.right="",X.top="",X.bottom="",X.transform="",X.width="",X.maxWidth="",X.height="",X.maxHeight="",St){let ae=St.style;ae.bottom=m,ae.width=f??""}if(r&&d!=="fullscreen"){if(d==="modal"){X.top="50%",X.left="50%",X.transform="translate(-50%, -50%)",X.bottom="auto",X.right="auto",X.width=$,X.maxWidth=q,X.maxHeight=F,X.height=F;return}X.left="50%",X.transform="translateX(-50%)",X.bottom=`calc(${m} + ${K})`,X.top=D,X.width=b,X.maxWidth=q}},ti=()=>{if(xe&&xa(),!Ve())return;if(Me()){let q=(o.launcher?.composerBar??{}).expandedSize??"anchored",K=xe?"expanded":"collapsed";Le.dataset.state=K,Le.dataset.expandedSize=q,St&&(St.dataset.state=K,St.dataset.expandedSize=q),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Hv(xe),re.style.display=xe?"flex":"none",er(),xe?(Pv(),Lv()):(yg(),bg()),Yr();return}let r=rt(o),a=t.ownerDocument.defaultView??window,d=o.launcher?.mobileBreakpoint??640,m=o.launcher?.mobileFullscreen??!0,f=a.innerWidth<=d,b=m&&f&&de,D=wn(o).reveal;xe?(Le.style.removeProperty("display"),Le.style.display=r?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0"),le.classList.add("persona-scale-100","persona-opacity-100"),ct?(ct.setPanelOpen(!0),ct.element.style.display="none"):Ft&&(Ft.style.display="none")):(r?r&&(D==="overlay"||D==="push")&&!b?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.setProperty("display","none","important"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.display="",Le.classList.add("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100"),le.classList.add("persona-scale-95","persona-opacity-0")),ct?(ct.setPanelOpen(!1),ct.element.style.display=r?"none":""):Ft&&(Ft.style.display=r?"none":""))},Ge=(r,a="user")=>{if(!Ve()||xe===r)return;let d=xe;xe=r,ti();let m=(()=>{let b=o.launcher?.sidebarMode??!1,D=t.ownerDocument.defaultView??window,$=o.launcher?.mobileFullscreen??!0,F=o.launcher?.mobileBreakpoint??640,q=D.innerWidth<=F,K=rt(o)&&$&&q,X=Me()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return b||$&&q&&de||K||X})();if(xe&&m){if(!Bn){let b=t.getRootNode(),D=b instanceof ShadowRoot?b.host:t.closest(".persona-host");D&&(Bn=cp(D,o.launcher?.zIndex??Dt))}Dn||(Dn=dp(t.ownerDocument))}else xe||(Bn?.(),Bn=null,Dn?.(),Dn=null);xe&&(li(),Bc()||(on()==="follow"?Ho(!0):Wc()));let f={open:xe,source:a,timestamp:Date.now()};xe&&!d?G.emit("widget:opened",f):!xe&&d&&G.emit("widget:closed",f),G.emit("widget:state",{open:xe,launcherEnabled:de,voiceActive:we.active,streaming:x.isStreaming()})},Ro={inputDisabled:!1,sendDisabled:!1},_n=()=>Ro.inputDisabled,_c=()=>Ot(o.voiceRecognition?.provider)&&!!x&&(x.isBargeInActive()||["listening","processing","speaking"].includes(x.getVoiceStatus())),fr=()=>Ro.inputDisabled||Ro.sendDisabled,Rv=()=>(Ro.inputDisabled?Ro.inputReason:void 0)??(Ro.sendDisabled?Ro.sendReason:void 0);function Fc(){if(!pe)return;if(ie.getState().phase==="streaming"){pe.disabled=!1;return}let r=_e?!_e.isReady():!1;pe.disabled=fr()||r}function Aa(){if(!Hn)return;let r=ie.getState(),a=o.sendButton?.visibility==="when-text"&&r.phase!=="streaming"&&r.text.trim().length===0&&r.attachments.length===0;Hn.toggleAttribute("data-persona-send-hidden",a)}function Wv(){let r=Rv();if(Me()){let a=Ut??Ie;r?a.setAttribute("title",r):a.removeAttribute("title"),Ie.toggleAttribute(Ts,!!r);return}if(r){Re.setAttribute("role","status"),Re.setAttribute("aria-live","polite"),Re.setAttribute(Ts,""),Re.removeAttribute(Ni),Re.textContent=r,ui(Re,o.statusIndicator??{},"idle");return}if(Re.hasAttribute(Ts)&&(Re.removeAttribute("role"),Re.removeAttribute("aria-live"),Re.removeAttribute(Ts),C)){let a=x.getStatus();Ws(Re,ec(a),o.statusIndicator??{},a)}}function Nc(){let r=Id(o.composer?.inputDisabled),a=Id(o.composer?.sendDisabled);Ro={inputDisabled:r.disabled,inputReason:r.reason,sendDisabled:a.disabled,sendReason:a.reason},ie.setInputDisabled(r.disabled),ie.setSendDisabled(a.disabled);let d=ie.getState().phase==="streaming",m=r.disabled,f=d||m;Z&&(Z instanceof HTMLTextAreaElement?Z.disabled=m:Z.setAttribute("contenteditable",m?"false":"true"),Z.setAttribute("aria-disabled",m?"true":"false")),st&&(st.disabled=m),et&&(et.disabled=m);for(let b of lt?.affordanceButtons??[])b.querySelectorAll("button").forEach(D=>{D.disabled=m});te&&(te.disabled=m||d&&!_c()),nr.forEach(b=>{b.elements.forEach(D=>{D.toggleAttribute("data-disabled",f),D instanceof HTMLButtonElement||D.setAttribute("aria-disabled",f?"true":"false")}),b.buttons.forEach(D=>{D.disabled=f})}),jc.forEach(b=>{b.toggleAttribute("data-disabled",f),b instanceof HTMLButtonElement?b.disabled=f:b.setAttribute("aria-disabled",f?"true":"false"),b.querySelectorAll("button").forEach(D=>{D.disabled=f})}),Ie.dataset.personaComposerStreaming=d?"true":"false",Ie.dataset.personaComposerInputDisabled=m?"true":"false",Ie.dataset.personaComposerSendDisabled=fr()?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(b=>{(b instanceof HTMLButtonElement||b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement||b instanceof HTMLSelectElement)&&(b.disabled=d)}),Fc(),Wv()}let ni=r=>{ie.setStreaming(r),du(r?"stop":"send"),Nc()},Ma=()=>{we.active||Z&&Z.focus()};G.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Ma(),200)});let Cg=null,Vc=!1,$c=!xt.hidden,Wo=null,zc=!z,Ea=null;oe.push(()=>{Ea?.cancel(),Ea=null});let Bv=r=>{let a=Ty(r);if(a===Xi)return;Xi=a,t.setAttribute("data-persona-conversation-state",a);let d=sc();Zi(),zc&&(Ea?.cancel(),Ea=My(Ie,a==="active"?d:sc(),a==="active"?"drop":"rise",Xo().layout==="centered"?320:260)),Gr()},wg=null,Sg,xg=null,Qr=null,Uc=!1,oi=r=>{let a=Xo(),d=`${a.variant}|${a.layout}|${a.dismiss}|${a.anchor??"bottom"}|${a.align??""}|${a.iconPlacement}|${a.kicker??""}|${a.title}|${a.subtitle}`;(d!==wg||a.icon!==Sg)&&(wg=d,Sg=a.icon,Vl({host:xt,iconHolder:_b,kicker:Fb,title:Nb,subtitle:Vb,starterSuggestions:tc},a));let m=a.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${a.message}`;m!==xg&&(xg=m,$l(tn,a.message,o));let f=r??(x?x.getMessages():o.initialMessages);Bv(f);let b=Vc,D=!b&&Ss(a,f),$=D!==$c;if($c=D,Qr){Wo?.cancel(),Wo=null,b!==Uc&&(Uc=b,b?wp(j,xt,null):Cp(j,xt,Qr)),ws(j,xt,!b);return}if($&&!D&&!b&&a.dismiss==="on-first-message"&&zc){Wo=Ay(xt,q=>{Wo===q&&(Wo=null),!$c&&!Qr&&(ws(j,xt,!1),Gr()),q?.cancel()});return}if(Wo){if(!D&&!b)return;Wo.cancel(),Wo=null}let F=!xt.hidden;ws(j,xt,D),!D&&F&&Gr()},qc=[],jc=[],Kc=!1,Ag=null,Mg,Eg=()=>{jc.length=0;let r=qc.splice(0,qc.length);for(let a of r)try{a()}catch(d){console.warn("[persona] renderWelcome cleanup threw",d)}};oe.push(Eg);let Dv=(r,a)=>{let d=up(r,a);if(!d)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),P("span");let m=o.suggestions?.starters,f=gp({item:{...d,behavior:d.behavior??m?.behavior??"send"},index:a,surface:"starter",source:"config",variant:m?.variant??"card",streaming:C?x.isStreaming():!1,config:o,plugins:g,chipsConfig:o.suggestionChipsConfig,session:x,getTextarea:()=>Z,eventTarget:xt,submitPrompt:Ba});return jc.push(f),f},Gc=()=>{if(Kc)return;Kc=!0;let r=Xo();Ag=`${r.variant}|${r.layout}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`,Mg=r.icon;try{Eg(),wp(j,xt,Qr),Qr=null,Uc=!1;let a=x?x.getMessages():o.initialMessages,d=Ss(r,a),m=0,f=null;for(let b of g)if(b.renderWelcome&&(f=b.renderWelcome({config:r,variant:r.variant,visible:d,defaultRenderer:()=>xt,sendMessage:D=>{if(!x||x.isStreaming())return;let $=D.trim();$&&x.sendMessage($)},requestRender:()=>Gc(),renderStarter:D=>Dv(D,m++),storage:E(b.id),onCleanup:D=>{qc.push(D)}}),f))break;f&&f!==xt&&(Qr=f,Cp(j,xt,f))}finally{Kc=!1}oi()},Ov=()=>{let r=Xo();`${r.variant}|${r.layout}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`===Ag&&r.icon===Mg||Gc()},Ta=()=>{oi(),Fr||(Z.placeholder=Bh(ie.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!x?.isStreaming()&&(pe.textContent=o.copy?.sendButtonLabel??"Send")),Z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Z.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},_v=!!o.setStoredConversationId,Xr=r=>$e(a=>{let d={...a};return delete d[r],d}),ka=r=>{let a=S[r];return typeof a=="string"?a:null},Tg=()=>{let r=S.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:()=>ka("sessionId"),setStoredSessionId:r=>{$e(a=>({...a,sessionId:r}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Xr("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>ka("conversationId")),setStoredConversationId:o.setStoredConversationId??(r=>{$e(a=>({...a,conversationId:r}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Xr("conversationId"))});let kg=()=>o.clientToken??null,Pg=r=>cb(r,zi(),o.persistState===!1),Lg=kg(),mn=Lg?Pg(Lg):null,Fv=()=>{let r=S.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")}},Bo={...mn?{visitorStore:mn}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!Gl()?Promise.all([ee,he]).then(()=>{}):ee,getStoredMessageCursor:()=>ka("historyMessageCursor"),setStoredMessageCursor:r=>{if(r===null){Xr("historyMessageCursor");return}$e(a=>({...a,historyMessageCursor:r}))},getPendingDisplayProjections:Fv,setPendingDisplayProjections:r=>{if(!r){Xr("pendingDisplayProjections");return}$e(a=>({...a,pendingDisplayProjections:r}))},getStoredResumableHandle:Tg,setStoredResumableHandle:r=>{if(!r){Xr("durableResume");return}$e(a=>({...a,durableResume:r}))},shouldResumeDurableConversation:()=>T&&Tg()!==null,..._v?{}:{getStoredConversationRevision:()=>ka("conversationRevision"),setStoredConversationRevision:r=>{if(r===null){Xr("conversationRevision");return}$e(a=>({...a,conversationRevision:r}))}}};if(T){let r=o.onExecutionState,a=t.ownerDocument.defaultView,d=!1,m=()=>d=!0,f=()=>d=!1;a?.addEventListener("pagehide",m),a?.addEventListener("pageshow",f),oe.push(()=>{a?.removeEventListener("pagehide",m),a?.removeEventListener("pageshow",f)}),o={...o,reconnectStream:o.reconnectStream??(b=>x.getClient().reconnectClientTokenStream(b)),onExecutionState:b=>{(b||!d)&&Bo.setStoredResumableHandle?.(b?{executionId:b.executionId,after:b.lastEventId}:null),r?.(b)}}}let Nv=()=>{let r=kg();if(r&&mn?.matches(r,zi(),o.persistState===!1)||!r&&!mn)return;mn?.destroy(),mn=r?Pg(r):null;let a={...Bo};mn?a.visitorStore=mn:delete a.visitorStore,Bo=a,x.setHistoryInternals(Bo)},hr=null,Vv=()=>{hr==null&&(hr=setInterval(()=>{let r=ce.querySelectorAll("[data-tool-elapsed]");if(r.length===0){clearInterval(hr),hr=null;return}let a=Date.now();r.forEach(d=>{let m=Number(d.getAttribute("data-tool-elapsed"));m&&(d.textContent=d.closest(".persona-activity-row")?bi(a-m):Qm(a-m))})},100))},Yc=(r,a)=>{if(Object.is(r,a))return!0;if(r===null||a===null||typeof r!="object"||typeof a!="object")return!1;if(Array.isArray(r)||Array.isArray(a))return!Array.isArray(r)||!Array.isArray(a)||r.length!==a.length?!1:r.every((D,$)=>Yc(D,a[$]));let d=r,m=a,f=Object.keys(d),b=Object.keys(m);return f.length===b.length&&f.every(D=>Object.prototype.hasOwnProperty.call(m,D)&&Yc(d[D],m[D]))},Ig=r=>{let{content:a,rawContent:d,llmContent:m,...f}=r;return f},Qc=r=>r.role==="assistant"&&r.streaming===!0&&!r.variant&&!r.toolCall&&!r.tools&&!r.approval&&!r.reasoning&&!r.contentParts&&!r.stopReason&&!Kp(r),$v=(r,a,d)=>{if(r.length!==a.length)return!1;let m=r[d.index],f=a[d.index];return!m||!f||m.id!==d.id||f.id!==d.id?!1:(!Object.is(m.content,f.content)||!Object.is(m.rawContent,f.rawContent)||!Object.is(m.llmContent,f.llmContent))&&Qc(m)&&Qc(f)&&Yc(Ig(m),Ig(f))},Pa=null,Jr=null,yr=null,so=null,Xc=null,zv=r=>{if(!T)return Ur(r);Xc=r,queueMicrotask(()=>{Xc===r&&(Xc=null,Ur(r))})},La=r=>{Pa=r;let a,d;Jr=null;for(let f=r.length-1;f>=0;f-=1){let b=r[f];if(!a&&b.role==="user"&&(a=b),!d&&b.role==="assistant"&&(d=b),!Jr&&Qc(b)&&(Jr={index:f,id:b.id}),a&&d&&Jr)break}gn(ce,r,Jt),yo()?.updateInlineArtifactBlocks(ce,pn.artifacts,{suppressTransition:rn}),Vv(),oi(r),sr(r),Ho(!rn),Tv(r),r.length===0&&(mr(),Ys=!0,ga=!1,zr=null,ma=!1),!Mc||$r?(Mc=!0,pr=a?.id??null,Ec=d?.id??null):a&&a.id!==pr?(pr=a.id,Sv(a.id)):d&&d.id!==Ec&&xv(),d&&(Ec=d.id),Ev(r);let m=we.lastUserMessageId;a&&a.id!==m&&(we.lastUserMessageId=a.id,G.emit("user:message",a)),we.lastUserMessageWasVoice=!!a?.viaVoice,zv(r),Yr()},Jc=()=>{so!==null&&(cancelAnimationFrame(so),so=null);let r=yr;yr=null,r&&La(r)},Hg=()=>{so!==null&&cancelAnimationFrame(so),so=null,yr=null},Uv=r=>{let a=yr??Pa;if(rn&&a&&Jr&&$v(a,r,Jr)){yr=r,so===null&&(so=requestAnimationFrame(()=>{so=null;let d=yr;yr=null,d&&La(d)}));return}if(r.length===0){Hg(),La(r);return}Jc(),La(r)};x=new Al(o,{onMessagesChanged(r){Uv(r)},onStatusChanged(r){let a=o.statusIndicator??{};Ws(Re,(m=>m==="idle"?a.idleText??gt.idle:m==="connecting"?a.connectingText??gt.connecting:m==="connected"?a.connectedText??gt.connected:m==="error"?a.errorText??gt.error:m==="paused"?a.pausedText??gt.paused:m==="resuming"?a.resumingText??gt.resuming:gt[m])(r),a,r),Gi()},onStreamingChanged(r){r||(x?.getMessages().length===0?Hg():Jc()),rn=r,ni(r),Gi(),x&&gn(ce,x.getMessages(),Jt),r||(Ho(!0),Cv(),tg=!0,x&&ng(x.getMessages(),ds(o))),Ht(),Ns(r?"Responding\u2026":"Response complete."),Yr()},onVoiceStatusChanged(r){if(G.emit("voice:status",{status:r,timestamp:Date.now()}),r!=="disconnected"&&!Ot(o.voiceRecognition?.provider))return;let a=x.getVoiceNotice();switch(a&&Wa(a,1e4),r){case"listening":if(!kc){let d=x.getVoiceDisclosure();d&&(kc=!0,Me()?(fa=Z.placeholder,Z.placeholder=d,Ns(d)):Wa(d,1e4))}lo(),ns();break;case"processing":lo(),gC();break;case"speaking":lo(),mC();break;default:r==="idle"&&x.isBargeInActive()?(lo(),ns(),te?.setAttribute("aria-label","End voice session")):(we.active=!1,kc=!1,fa!==null&&(Z.placeholder=fa,fa=null),lo(),oo("system"),ig||Gt());break}},onArtifactsState(r){pn=r,r.artifacts.length===0&&(Nr=!1),yo()?.updateInlineArtifactBlocks(ce,r.artifacts,{suppressTransition:rn}),Tn(),Ur()},onHistoryStateChanged(r){lu(r)},onHistoryNotice(r){cu(r)},onReconnect(r){let{executionId:a,lastEventId:d}=r.handle;r.phase==="paused"?G.emit("stream:paused",{executionId:a,after:d}):r.phase==="resuming"?G.emit("stream:resuming",{executionId:a,after:d,attempt:r.attempt??1}):G.emit("stream:resumed",{executionId:a,after:d})}},Bo),un.current=x,oe.push(()=>x.cancel()),oe.push(()=>{x.destroy(),mn?.destroy(),mn=null});let Zc=null;if(x.onReadAloudChange((r,a)=>{Lu=r,Iu=a,Hu();let d=r??Zc;r&&(Zc=r);let m=d?x.getMessages().find(f=>f.id===d)??null:null;G.emit("message:read-aloud",{messageId:d,message:m,state:a,timestamp:Date.now()}),a==="idle"&&(Zc=null)}),C=!0,Mc=!0,o.voiceRecognition?.enabled===!0&&Ot(o.voiceRecognition.provider))try{x.setupVoice()}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",r)}let tt=null,ed=null,Rg=!1,Wg=x.getHistoryState(),ri=()=>o.features?.history?.enabled===!0,Bg=r=>{r&&(Qn.textContent="",Qn.textContent=r)},td=()=>{h.forEach(d=>d()),h=[];let r=tt,a=r?.railCollapseShortcut();r&&a&&h.push(y.register({id:"history-rail-collapse",combo:a.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Rs&&qi==="rail"&&r.railCollapsible()||r.railTriggerApplies(),run:()=>r.railOverlayMode()?r.toggleRailPinned():r.toggleRailCollapsed()}));for(let d of o.layout?.header?.trailingActions??[])d.shortcut&&h.push(y.register({id:`header-action-${d.id}`,combo:d.shortcut,run:()=>{let m=t.querySelector(`[data-persona-header-action="${d.id}"]`);m?m.click():o.layout?.header?.onAction?.(d.id)}}));for(let d of g)for(let m of d.shortcuts??[])h.push(y.register({...m,id:`${d.id}:${m.id}`}))};td();let Ia=null,Dg=!1,si=()=>{if(!So)return;let r=o.layout?.header?.titleSource==="conversation",a=r&&Ia?.trim()||null;So.textContent=a??o.launcher?.title??"Chat Assistant";let d=So.closest(".persona-combo-btn");if(!d)return;let m=!r||x.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 f=d.querySelector("svg");f&&(f.style.display=m?"":"none")},qv=r=>{r!==Ia&&(Ia=r,si())},jv=r=>{Dg=r?.starred===!0,qv(r&&r.title.trim()||null),si()};si(),re.addEventListener("persona:title-menu-builtin",r=>{let a=r.detail?.actionId,d=x.getActiveConversationId();d&&(a==="delete"?Fn(m=>m.requestDeleteConversation(d)):a==="star"&&x.canUpdateConversations()&&Fn(m=>m.updateHistoryConversation(d,{starred:!Dg})).catch(()=>{}))}),lu=r=>{Wg=r,tt?.historySurface?.view.setNewConversationRequired(r.recovery==="new_conversation_required"),ni(r.sendBlocked||rn),tt?.syncEarlierMessagesPill()},cu=r=>{(r.code==="history_continuity_reset"||r.code==="conversation_deleted_recovered")&&(It.clear(),mr(),On()),Bg(r.message),tt?.historySurface?.view.refresh()};let Kv={get actionManager(){return Ee},get activeConversationTitle(){return Ia},announceHistory:Bg,get applyRailChrome(){return Ki},set applyRailChrome(r){Ki=r},get artifactSplitRoot(){return Zn},get body(){return j},get config(){return o},get container(){return re},get conversationOpenPendingEl(){return Cg},set conversationOpenPendingEl(r){Cg=r},get conversationOpenTakeover(){return Vc},set conversationOpenTakeover(r){Vc=r},currentKeyPrefix:zi,destroyCallbacks:oe,eventBus:G,get footer(){return Ie},get header(){return Ke},get historyChromeSync(){return Gi},set historyChromeSync(r){Gi=r},historyFeatureEnabled:ri,get historyInternals(){return Bo},set historyInternals(r){Bo=r},get historyPresentation(){return qi},set historyPresentation(r){qi=r},get historySessionState(){return Wg},get historyVisible(){return Rs},set historyVisible(r){Rs=r},get isStreaming(){return rn},jumpToBottomInstant:Wc,get lastAppliedMessages(){return Pa},set lastAppliedMessages(r){Pa=r},get launcherEnabled(){return de},get launcherSurfaceInstance(){return ct},maybeFocusInput:Ma,messageCache:It,get messagesWrapper(){return ce},mount:t,get open(){return xe},panel:le,panelElements:We,get persistentMetadata(){return S},set persistentMetadata(r){S=r},plugins:g,get reapplyHistoryHostChrome(){return ji},set reapplyHistoryHostChrome(r){ji=r},repinAnchoredMessage:Gr,resetAnchorState:mr,restoreScrollPosition:Bc,resumeAutoScroll:On,runStorageMutation:ya,get session(){return x},setActiveConversationSummary:jv,storageAdapter:v,get suppressScrollSend(){return $r},set suppressScrollSend(r){$r=r},syncScrollToBottomButton:Ht,updateWelcome:oi,getHistoryProviderFactory:ub,historyErrors:{HistoryClientError:bt,HistoryProviderError:nl},isDockedMountMode:rt,renderLucideIcon:se,loadHistoryView:db,createHeaderIconButton:bs,attachTooltip:Cn},nd=r=>(!tt&&!Rg&&(tt=r.createHistoryShell(Kv),tt.railCollapseShortcut()&&td()),tt),od=()=>{if(tt)return Promise.resolve(tt);let r=Gl();return r?Promise.resolve(nd(r)):(ed??=pb().then(nd,a=>{throw ed=null,a}),ed)},Fn=r=>{let a=Gl(),d=tt??(a?nd(a):null);return d?r(d):od().then(m=>{if(!m)throw new Error("[AgentWidget] The widget was destroyed");return r(m)})},Ha=()=>{tt?.syncHistoryPresentation()};oe.push(()=>{Rg=!0}),ri()&&od().catch(()=>{}).finally(ne),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&x.initClientSession().then(()=>{let r=tt;if(r?.historyAvailable())return x.reconcileBootConversation({scope:r.historyScope()})}).then(()=>{tt?.syncEarlierMessagesPill()}).catch(r=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",r)});let rd=()=>x.warmClientSession(),Og=r=>{let a=o.sessionInit??"input",d=Be?.input??Z,m=r.target;d&&(r.type==="input"?(a==="input"||a==="focus")&&m===d&&r.inputType&&d.value.trim():a==="focus"&&(r.type==="keyup"?m===d&&r.key==="Tab":(Be?.form??Ut)?.contains(m)))&&rd()},_g=["input","pointerdown","keyup"];_g.forEach(r=>t.addEventListener(r,Og));let Fg,sd,Ng=()=>{let r=sd;sd=void 0;try{typeof r=="function"&&r()}catch{}},Vg=()=>{let r=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(r!==Fg){Ng(),Fg=r;try{sd=r?.({warm:rd,mount:t})}catch{}}};Vg(),oe.push(()=>{_g.forEach(r=>t.removeEventListener(r,Og)),Ng()}),(Zt||o.onSSEEvent)&&x.setSSEEventCallback((r,a)=>{o.onSSEEvent?.(r,a),Zl(r,a)});let $g=()=>{let r=o.resume??(T?Bo.getStoredResumableHandle?.():null);r&&typeof o.reconnectStream=="function"&&x.resumeFromHandle(r)};z?z.then(r=>{if(r){if(r.metadata&&(S=Gp(r.metadata),Ee.syncFromMetadata()),r.messages?.length){$r=!0;try{x.hydrateMessages(r.messages)}finally{$r=!1}xa()}r.artifacts?.length&&x.hydrateArtifacts(r.artifacts,r.selectedArtifactId??null),dg(r.draft)}}).catch(r=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",r)}).finally(()=>{zc=!0,W(),$g()}):(dg(ve),$g());let Gv=()=>{!Me()||xe||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Ge(!0,"auto")},Yv=(r,a)=>r?a?{refs:[...r.refs,...a.refs],finalize:async()=>{let[d,m]=await Promise.allSettled([r.finalize(),a.finalize()]),f=[];return d.status==="fulfilled"?f.push(d.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",d.reason),m.status==="fulfilled"?f.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),iA(f)}}:r:a,id=()=>{let a=Z.getInlineMessageFields?.();return a&&a.contentSegments.some(m=>m.kind==="mention")?a.contentSegments:void 0},io=!1,br=null,Ra=()=>{Z.value="",Z.style.height="auto",Rn(),ai()},Zr=null;function Wa(r,a=4e3){Ns(r),!(Me()||!Re)&&(Re.hasAttribute(Ts)||(Re.setAttribute(Ni,""),Re.setAttribute("role","status"),Re.setAttribute("aria-live","polite"),Re.textContent=r,ui(Re,o.statusIndicator??{},"idle"),Zr&&clearTimeout(Zr),Zr=setTimeout(()=>{if(Zr=null,!!Re?.hasAttribute(Ni)&&(Re.removeAttribute(Ni),Re.removeAttribute("role"),Re.removeAttribute("aria-live"),C)){let d=x.getStatus();Ws(Re,ec(d),o.statusIndicator??{},d)}},a)))}function Qv(){let r=ie.getState().pendingSubmission;r&&(Or(void 0),Z&&(Z.value=r.text,Z.dispatchEvent(new Event("input",{bubbles:!0})),Rn()),r.options.selectedModelId&&(ie.setSelectedModelId(r.options.selectedModelId),Ao?.repaint()),r.options.activeModeIds?.length&&ea(r.options.activeModeIds),r.options.quote&&Wn(r.options.quote),Z?.focus())}let Xv=r=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",r)},zg=(r={})=>{let a=(r.overrideText??Z?.value??"").trim();return r.resolveInlineCommand&&a?(lt?.takeInlineCommand(a)??Promise.resolve(null)).then(d=>Ug(r,a,d)):Ug(r,a,null)},Ug=(r,a,d)=>{if(d?.kind==="action"){Ra(),lt?.clear(),Zo();return}let m=d?.kind==="server"?d.mentions:null,f=d?.kind==="prompt"?d.sendText:a,b=r.pending?.contentParts,D=(_e?.hasAttachments()??!1)||(b?.length??0)>0;if(!Kh({text:f,hasAttachments:D,attachmentsReady:_e?.isReady()??!0,hasMentions:lt?.hasMentions()??!1,hasServerMentions:!!m,inputDisabled:_n(),sendDisabled:fr()}))return;let $=x.isStreaming()?cc():"block";if($==="defer-one"&&!r.pending){if(ie.getState().pendingSubmission){Wa("One message is already queued. Edit or remove it first.");return}Jv({intent:r,sendText:f,serverMentions:m});return}let F={text:f,mentionRefs:[...lt?.getMentionRefs()??[],...m?.refs??[]],contentSegments:d?.kind==="prompt"?void 0:id(),options:{...ie.getState().selectedModelId&&{selectedModelId:ie.getState().selectedModelId},...ie.getState().activeModeIds.length>0&&{activeModeIds:[...ie.getState().activeModeIds]},...ie.getState().quote&&{quote:{...ie.getState().quote}}},viaVoice:r.viaVoice};r.pending&&(F.options={...r.pending.options},F.contentSegments=r.pending.contentSegments,F.mentionRefs=[...r.pending.mentionRefs],F.viaVoice=r.pending.viaVoice);let q=()=>{if(b?.length)return[...b];if(!_e?.hasAttachments())return;let De=[..._e.getContentParts()];return F.text&&De.push(zo(F.text)),De};F.contentParts=q();let K=()=>{lr(),Gv();let De=lt?.collectForSubmit()??null,Yt=Yv(De,m),nt=q();r.consumeDraft!==!1&&Ra();let it={selectedModelId:F.options.selectedModelId,activeModeIds:F.options.activeModeIds},Nt=$==="interrupt";Nt&&x.cancel(),x.sendMessage(F.text,{contentParts:nt,mentions:Yt??void 0,contentSegments:F.contentSegments,viaVoice:F.viaVoice,composerOptions:it,...F.options.quote&&{quote:F.options.quote},...Nt&&{interrupt:!0}}),_e?.hasAttachments()&&_e.clearAttachments(),De&&lt?.clear(),Zo();let pt=ie.getState().activeModeIds,ze=Wh(pt,o.composer?.modes);ze.length!==pt.length&&ea(ze),ie.getState().quote&&Wn(void 0),va(),fc.release(),Mn()},X=o.composer?.onBeforeSend;if(!X){K();return}let ae=new AbortController;br=ae;let He=De=>{if(br=null,De.status==="error"){Xv(De.error);return}De.status==="proceed"&&K()},Fe=Gh(X,F,ae.signal);if(!(Fe instanceof Promise)){He(Fe);return}return ie.setPreparing(!0),Fe.then(He).finally(()=>ie.setPreparing(!1))};function Jv(r){let a=ie.getState(),d=_e?.hasAttachments()??!1,m=d?[..._e.getContentParts()]:[];d&&r.sendText&&m.push(zo(r.sendText));let f=tp({text:r.sendText,contentParts:m.length?m:void 0,mentionRefs:[...lt?.getMentionRefs()??[],...r.serverMentions?.refs??[]],contentSegments:id(),options:{...a.selectedModelId&&{selectedModelId:a.selectedModelId},...a.activeModeIds.length>0&&{activeModeIds:[...a.activeModeIds]},...a.quote&&{quote:{...a.quote}}},viaVoice:r.intent.viaVoice});Or(f),r.intent.consumeDraft!==!1&&Ra(),d&&_e.clearAttachments(),lt?.clear(),Zo(),a.quote&&Wn(void 0),va(),fc.release(),Mn(),Ns("Message queued. It sends when the response finishes.")}function Zv(){let r=ie.getState().pendingSubmission;r&&(Or(void 0),Da(r.text,{consumeDraft:!1,pending:r}))}function eC(r){if(o.messageActions?.showEdit!==!0)return;let a=x.getMessages().find(d=>d.id===r);!a||!Ud(a)||ar!==r&&(lr(),ar=r,ko=Fh({messageId:r,initialText:a.content,onSave:d=>tC(r,d),onCancel:()=>lr()}),It.delete(r),gn(ce,x.getMessages(),Jt),ko.focus())}function tC(r,a){let d=ko;if(ar=null,ko=null,d?.destroy(),It.delete(r),!x.resubmitFrom(r,{reason:"edit",replacement:{text:a,mentionRefs:[],options:{}}})){gn(ce,x.getMessages(),Jt);return}Gr()}function nC(r){if(x.isStreaming())return;let a=zd(x.getMessages(),r);a&&(lr(),x.resubmitFrom(a,{reason:"retry"})&&Gr())}ta={regenerate:nC,edit:eC,quote:r=>{let d=x.getMessages().find(m=>m.id===r)?.content?.trim();d&&(Wn({text:d,messageId:r}),Z?.focus())}};let ii=async r=>{if(!io){io=!0;try{await zg({resolveInlineCommand:!0,...r})}finally{io=!1}}};function Ba(r){fr()||(Ra(),Da(r,{consumeDraft:!1}))}let Da=(r,a)=>{if(io)return;io=!0;let d=()=>{io=!1};try{let m=zg({...a,overrideText:r});m instanceof Promise?m.finally(d):d()}catch(m){throw d(),m}},oC=r=>{if(r.preventDefault(),x.isStreaming()){x.cancel(),Sn?.reset(),_t?.update();return}io||ii()},rC=()=>o.features?.composerHistory!==!1,ad={...lp},ld=!1,ai=()=>{ad={...lp}},sC=()=>x.getMessages().filter(r=>r.role==="user").map(r=>r.content??"").filter(r=>r.length>0),iC=r=>{if(!Z)return;ld=!0,Z.value=r,Z.dispatchEvent(new Event("input",{bubbles:!0})),ld=!1;let a=Z.value.length;Z.setSelectionRange(a,a)},aC=r=>{ld||(r.isComposing||lt?.handleInput(r.inputType??void 0),ai())},lC=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Ld(Z)}),cC=r=>{if(Z&&!_n()&&!(!r.isComposing&&lt?.handleKeydown(r))){if(rC()&&(r.key==="ArrowUp"||r.key==="ArrowDown")&&!r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.isComposing){let a=Z.selectionStart===0&&Z.selectionEnd===0,d=oy({direction:r.key==="ArrowUp"?"up":"down",history:sC(),currentValue:Z.value,atStart:a,state:ad});if(ad=d.state,d.handled){r.preventDefault(),d.value!==void 0&&iC(d.value);return}}if(ff(r,lC())){if(x.isStreaming()){if(r.preventDefault(),cc()==="block"||io||fr())return;ai(),ii();return}if(io){r.preventDefault();return}if(fr()){r.preventDefault();return}ai(),r.preventDefault(),pe.click()}}},qg=r=>{if(!(r.key!=="Escape"||r.isComposing)&&r.composedPath().includes(re)){if(br){br.abort(),br=null,r.preventDefault(),r.stopImmediatePropagation();return}x.isStreaming()&&(x.cancel(),Sn?.reset(),_t?.update(),ai(),r.preventDefault(),r.stopImmediatePropagation())}},dC=async r=>{if(o.attachments?.enabled!==!0||!_e||_n())return;let a=nA(r.clipboardData);a.length!==0&&(r.preventDefault(),await _e.handleFiles(a))},fn=null,Nn=!1,es=null,ao=null,cd=()=>o.voiceRecognition?.completionBehavior==="review";function Oa(r){te?.setAttribute("data-state",r),r==="recording"?uC():gd()}let jg="--persona-voice-level",dd=.5,ts=null,pd=-1,_a=0,Kg=()=>{let r=[],a=nn??te?.parentElement??null;return a&&r.push(a),Ie&&r.push(Ie),r},ud=r=>{let a=Math.round(Math.max(0,Math.min(1,r))*100)/100;if(a!==pd){pd=a;for(let d of Kg())d.style.setProperty(jg,String(a))}},pC=()=>{pd=-1,_a=0;for(let r of Kg())r.style.removeProperty(jg)};function uC(){if(ts!==null)return;if(typeof requestAnimationFrame!="function"){ud(C?x.getVoiceLevel()??dd:dd);return}let r=()=>{ts=requestAnimationFrame(r);let a=C?x.getVoiceLevel():null;if(a===null){ud(dd);return}_a+=(a-_a)*.3,ud(_a)};ts=requestAnimationFrame(r)}function gd(){ts!==null&&(cancelAnimationFrame(ts),ts=null),pC()}let Gg=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Fa=(r="user")=>{if(Nn||x.isStreaming())return;let a=Gg();if(!a)return;fn=new a;let d=o.voiceRecognition??{},m=d.pauseDuration??2e3;fn.continuous=d.provider?.browser?.continuous??!0,fn.interimResults=!0,fn.lang=d.provider?.browser?.language??"en-US";let f=Z.value;fn.onresult=b=>{let D="",$="";for(let q=0;q<b.results.length;q++){let K=b.results[q],X=K[0].transcript;K.isFinal?D+=X+" ":$=X}let F=f+D+$;Z.value=F,Rn(),es&&clearTimeout(es),(D||$)&&(es=window.setTimeout(()=>{if(Z.value.trim()&&fn&&Nn){if(Do(),cd())return;ii({viaVoice:!0})}},m))},fn.onerror=b=>{b.error!=="no-speech"&&Do()},fn.onend=()=>{if(Nn){let b=Z.value.trim();!cd()&&b&&b!==f.trim()&&ii({viaVoice:!0}),Do()}};try{if(fn.start(),Nn=!0,we.active=!0,r!=="system"&&(we.manuallyDeactivated=!1),oo(r),Gt(),Mn(),te){let b=o.voiceRecognition??{};ao={backgroundColor:te.style.backgroundColor,color:te.style.color,borderColor:te.style.borderColor,iconName:b.iconName??"mic",iconSize:parseFloat(b.iconSize??"")||qn};let D=b.recordingBackgroundColor,$=b.recordingIconColor,F=b.recordingBorderColor;if(te.classList.add("persona-voice-recording"),Oa("recording"),te.style.backgroundColor=D??"var(--persona-voice-recording-bg, #ef4444)",te.style.color=$??"var(--persona-voice-recording-indicator, #ffffff)",$){let q=te.querySelector("svg");q&&q.setAttribute("stroke",$)}F&&(te.style.borderColor=F),te.setAttribute("aria-label","Stop voice recognition")}}catch{Do("system")}},Do=(r="user")=>{if(Nn){if(Nn=!1,es&&(clearTimeout(es),es=null),fn){try{fn.stop()}catch{}fn=null}if(we.active=!1,oo(r),Gt(),Mn(),te){if(te.classList.remove("persona-voice-recording"),Oa("idle"),ao){te.style.backgroundColor=ao.backgroundColor,te.style.color=ao.color,te.style.borderColor=ao.borderColor;let a=te.querySelector("svg");a&&a.setAttribute("stroke",ao.color||"currentColor"),ao=null}te.setAttribute("aria-label","Start voice recognition")}}},Yg=null,Na=r=>{let a=m=>{Yg??=m.createMicStateStyles({mic:()=>te,config:()=>o,session:()=>x,get original(){return ao},set original(f){ao=f},setMicState:Oa,renderIcon:se,iconFallbackPx:qn}),r(Yg)},d=dh();d?a(d):Si().then(a,()=>{})},ns=()=>Na(r=>r.recording()),gC=()=>Na(r=>r.processing()),mC=()=>Na(r=>r.speaking()),lo=()=>Na(r=>r.reset()),md=()=>{if(!_n()){if(Ot(o.voiceRecognition?.provider)){let r=x.getVoiceStatus(),a=x.getVoiceInterruptionMode();if(a==="none"&&(r==="processing"||r==="speaking"))return;if(a==="cancel"&&(r==="processing"||r==="speaking")){x.stopVoicePlayback();return}if(x.isBargeInActive()){x.stopVoicePlayback(),x.deactivateBargeIn().then(()=>{we.active=!1,we.manuallyDeactivated=!0,Gt(),oo("user"),lo()});return}x.toggleVoice().then(()=>{we.active=Pc(),we.manuallyDeactivated=!we.active,Gt(),oo("user"),we.active?ns():lo()});return}if(Nn){let r=Z.value.trim();we.manuallyDeactivated=!0,Gt(),Do("user"),r&&!cd()&&ii()}else we.manuallyDeactivated=!1,Gt(),Fa("user")}};dc=md;let Qg=()=>x.prewarmVoice(),Xg=()=>{let r=o.voiceRecognition;return r?.enabled!==!0?!1:r.prewarm??(o.clientToken?"hover":!1)},Jg=r=>{Xg()==="hover"&&te?.contains(r.target)&&Qg()},Zg=["pointerover","pointerdown","focusin"];Zg.forEach(r=>t.addEventListener(r,Jg));let em,tm=null,fd,nm=()=>{let r=fd;fd=void 0;try{typeof r=="function"&&r()}catch{}},hd=()=>{let r=Xg(),a=typeof r=="function"&&te?r:void 0,d=a?te:null;if(!(a===em&&d===tm)&&(nm(),em=a,tm=d,!(!a||!d)))try{fd=a({warm:Qg,micButton:d,mount:t})}catch{}};hd(),oe.push(()=>{Zg.forEach(r=>t.removeEventListener(r,Jg)),nm()}),te&&oe.push(()=>{Ot(o.voiceRecognition?.provider)?(x.isVoiceActive()&&x.toggleVoice(),lo()):Do("system")});let fC=G.on("assistant:complete",()=>{ie.getState().pendingSubmission&&setTimeout(()=>{x.isStreaming()||Zv()},0)});oe.push(fC);let hC=G.on("assistant:complete",()=>{sg&&(we.active||we.manuallyDeactivated||sg==="assistant"&&!we.lastUserMessageWasVoice||setTimeout(()=>{!we.active&&!we.manuallyDeactivated&&(Ot(o.voiceRecognition?.provider)?x.toggleVoice().then(()=>{we.active=x.isVoiceActive(),oo("auto"),x.isVoiceActive()&&ns()}):Fa("auto"))},600))});oe.push(hC);let yC=G.on("action:resubmit",()=>{setTimeout(()=>{x&&!x.isStreaming()&&x.continueConversation()},100)});oe.push(yC);let om=()=>{Ge(!xe,"user")},ct=null,Ft=null;if(de&&!Me()){let{instance:r,element:a}=Tp({config:o,plugins:g,onToggle:om});ct=r,r||(Ft=a)}ct?t.appendChild(ct.element):Ft&&t.appendChild(Ft),ti(),sr(),Ta(),Gc(),ni(x.isStreaming()),Bc()||(on()==="follow"?Ho(!0):Wc()),mv(),Ps&&(!de||Me()?setTimeout(()=>Ma(),0):xe&&setTimeout(()=>Ma(),200));let Oo=null,rm=()=>{Oo&&(Oo.disconnect(),Oo.observe(Ie),Oo.observe(re),Oo.observe(xt))},sm=Vs(),li=()=>{if(Me()){Jo(),ti();return}let r=rt(o),a=o.launcher?.sidebarMode??!1,d=t.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640,b=d.innerWidth<=f,D=m&&b&&de;try{if(D){er(),qs=da();return}let $=!1;Xl&&(Xl=!1,er(),$=!0);let F=da();if(!$&&F!==qs&&(er(),$=!0),qs=F,$&&ia(),!de&&!r){le.style.height="",le.style.width="";return}if(!a&&!r){let q=Pr(o);le.style.width=q.width,le.style.maxWidth=q.maxWidth}ca(),zu()}finally{Jo(),Zi();let $=Vs();if($!==sm&&(sm=$,oi(),sr()),ti(),xe&&de){let q=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),K=o.launcher?.sidebarMode??!1,X=o.launcher?.mobileFullscreen??!0,ae=rt(o)&&X&&q,He=K||X&&q&&de||ae;if(He&&!Dn){let Fe=t.getRootNode(),De=Fe instanceof ShadowRoot?Fe.host:t.closest(".persona-host");De&&!Bn&&(Bn=cp(De,o.launcher?.zIndex??Dt)),Dn=dp(t.ownerDocument)}else He||(Bn?.(),Bn=null,Dn?.(),Dn=null)}}};li();let Va=t.ownerDocument.defaultView??window;if(Va.addEventListener("resize",li),oe.push(()=>Va.removeEventListener("resize",li)),typeof ResizeObserver<"u"){Oo=new ResizeObserver(()=>{Zi()}),rm(),oe.push(()=>{Oo?.disconnect(),Oo=null});let r=new ResizeObserver(()=>{Ha()});r.observe(re),oe.push(()=>r.disconnect())}Va.addEventListener("resize",Ha),oe.push(()=>Va.removeEventListener("resize",Ha)),an=j.scrollTop;let im=uo(j),am=()=>{$u();let r=j.scrollTop,a=uo(j),d=a<im;if(im=a,!xo()){an=r,Ht();return}let{action:m,nextLastScrollTop:f}=If({following:sn.isFollowing(),currentScrollTop:r,lastScrollTop:an,nearBottom:Er(j,to),userScrollThreshold:dv,isAutoScrolling:Kt||ua||d,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(an=f,m==="resume"){Ca()||On();return}m==="pause"&&Kr()};if(j.addEventListener("scroll",am,{passive:!0}),oe.push(()=>j.removeEventListener("scroll",am)),typeof ResizeObserver<"u"){let r=new ResizeObserver(()=>{wv(),Od(ce)});r.observe(ce),r.observe(j),oe.push(()=>r.disconnect())}let lm=()=>{xo()&&sn.isFollowing()&&Ca()&&Kr()},cm=j.ownerDocument;cm.addEventListener("selectionchange",lm),oe.push(()=>{cm.removeEventListener("selectionchange",lm)});let bC=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),dm=r=>{bC.has(r.key)&&(Io(),pu()&&xo()&&sn.isFollowing()&&Kr())},pm=r=>{r.target?.closest("a, button, [tabindex], input, textarea, select")&&(Io(),pu()&&xo()&&sn.isFollowing()&&Kr())};j.addEventListener("keydown",dm),j.addEventListener("focusin",pm),oe.push(()=>{j.removeEventListener("keydown",dm),j.removeEventListener("focusin",pm)});let um=r=>{if(r.deltaY!==0&&Io(),!xo())return;let a=Hf({following:sn.isFollowing(),deltaY:r.deltaY,nearBottom:Er(j,to),resumeWhenNearBottom:!0});a==="pause"?Kr():a==="resume"&&!Ca()&&On()};j.addEventListener("wheel",um,{passive:!0}),j.addEventListener("touchmove",Io,{passive:!0}),j.addEventListener("pointerdown",Io,{passive:!0}),oe.push(()=>{j.removeEventListener("touchmove",Io),j.removeEventListener("pointerdown",Io)}),oe.push(()=>j.removeEventListener("wheel",um)),ft.addEventListener("click",()=>{mr(),j.scrollTop=j.scrollHeight,an=j.scrollTop,On(),Ho(!0),Ht()}),oe.push(()=>ft.remove()),oe.push(()=>{ug(),mr()});let gm=()=>{Ae&&(or&&(Ae.removeEventListener("click",or),or=null),Ve()?(Ae.style.display="",or=()=>{Ge(!1,"user")},Ae.addEventListener("click",or)):Ae.style.display="none")};gm(),(()=>{let{clearChatButton:r}=We;r&&r.addEventListener("click",()=>{let a=tt;if(a?.historyAvailable()){a.startNewConversation({focusComposer:!0}).catch(m=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",m)});return}x.clearMessages(),o.layout?.topFade&&(j.scrollTop=0),j.removeAttribute("data-persona-top-fade"),It.clear(),On(),Md(We.composerOverlay);try{localStorage.removeItem(Es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Es}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let d=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(d),v?.clear&&ya(()=>v.clear(),"[AgentWidget] Failed to clear storage adapter:"),S={},Ee.syncFromMetadata(),_e?.clearAttachments(),va(),Or(void 0),Wn(void 0),lr(),Lt?.clear(),Sn?.reset(),_t?.update()})})();let mm=[["keydown",cC],["input",aC],["input",Rn],["input",Zo],["keyup",Zo],["paste",dC],["focus",Jb]],fm=r=>{if(r)for(let[a,d]of mm)Be?.addListener(r,a,d)},vC=r=>{if(r)for(let[a,d]of mm)Be?.removeListener(r,a,d)},hm=()=>{Be&&(Be.addListener(Be.form,"submit",oC),Be.addListener(Be.footer,"click",Zo),fm(Z),te&&Be.addListener(te,"click",md),hd())};hm();let ym=()=>{lt?.onComposerSwap((r,a)=>{vC(a),Z=r,Be&&(Be.input=r),fm(r),uc(),Nc(),Rn()})};ym();let yd=!1;function bm(){if(!yd){yd=!0;try{let r=Z?.value??"",a=Ie.ownerDocument??document,d=Z?a.activeElement===Z:!1;gd(),Be?.destroy(),Be=null,lt?.destroy(),lt=null;let m=null,f=()=>(m=Me()?_l({config:o}):Wi({config:o}),m.footer),b=wu(f)??f();en.replaceComposer(b),Ie=en.composer.footer;let D=m!==null&&b===m.footer;Fr=!D,du=D?m.setSendButtonMode:()=>{},Cu(Ie),xu(Ie),Au(),Mu(),gc(),ym(),Eu(),mc(),Tu(),hm();let $=nr.indexOf(eo);if(eo.destroy(),eo=Hi(wo),$>=0&&(nr[$]=eo),Z&&(Z.value=r),Rn(),Zo(),Ta(),sr(),ni(x.isStreaming()),o.statusIndicator?.mode==="transient"&&!Me()){let F=x.getStatus();Ws(Re,ec(F),o.statusIndicator,F)}we.active&&Oa("recording"),er(),rm(),Jo(),Mn(),Aa(),d&&Z?.focus()}finally{yd=!1}}}let ci=t.ownerDocument??document;ci.addEventListener("keydown",qg,!0);let vm=()=>{Lc()},Cm=()=>{ci.visibilityState==="hidden"&&Lc()};typeof window<"u"&&(window.addEventListener("pagehide",vm),ci.addEventListener("visibilitychange",Cm),oe.push(()=>{window.removeEventListener("pagehide",vm),ci.removeEventListener("visibilitychange",Cm)}));let wm="persona-attachment-drop-active",di=0,bd=()=>{di=0,re.classList.remove(wm)},os=()=>o.attachments?.enabled===!0&&_e!==null&&!_n(),Sm=r=>{!Yl(r.dataTransfer)||!os()||(di++,di===1&&re.classList.add(wm))},xm=r=>{!Yl(r.dataTransfer)||!os()||(di--,di<=0&&bd())},Am=r=>{!Yl(r.dataTransfer)||!os()||(r.preventDefault(),r.dataTransfer.dropEffect="copy")},Mm=r=>{if(!Yl(r.dataTransfer)||!os())return;r.preventDefault(),r.stopPropagation(),bd();let a=Array.from(r.dataTransfer.files??[]);a.length!==0&&_e.handleFiles(a)},_o=!0;re.addEventListener("dragenter",Sm,_o),re.addEventListener("dragleave",xm,_o),t.addEventListener("dragover",Am,_o),t.addEventListener("drop",Mm,_o);let $a=t.ownerDocument,Em=r=>{os()&&r.preventDefault()},Tm=r=>{os()&&r.preventDefault()};$a.addEventListener("dragover",Em),$a.addEventListener("drop",Tm),oe.push(()=>{Be?.destroy(),Be=null,gd(),An?.destroy(),An=null,Xn?.destroy(),Xn=null,Mo?.destroy(),Mo=null,Eo?.destroy(),Eo=null,Ao=null,lc=null,Lc(),Qs.destroy(),Zr&&clearTimeout(Zr),lr(),br?.abort(),br=null,_e?.destroy(),_e=null,ie.destroy(),ci.removeEventListener("keydown",qg,!0),lt?.destroy()}),oe.push(()=>{re.removeEventListener("dragenter",Sm,_o),re.removeEventListener("dragleave",xm,_o),t.removeEventListener("dragover",Am,_o),t.removeEventListener("drop",Mm,_o),$a.removeEventListener("dragover",Em),$a.removeEventListener("drop",Tm),bd()}),oe.push(()=>{x.cancel()}),ct?oe.push(()=>{ct?.destroy()}):Ft&&oe.push(()=>{Ft?.remove()});let dt={update(r){let a=o.future?.v5Defaults===!0,d=o.toolCall,m=o.messageActions,f=o.layout?.messages,b=o.colorScheme,D=o.loadingIndicator,$=o.iterationDisplay,F=o.features?.showReasoning,q=o.features?.showToolCalls,K=o.features?.toolCallDisplay,X=o.features?.reasoningDisplay,ae=o.features?.streamAnimation?.type,He=o.features?.history?.enabled===!0,Fe=o.features?.history?.provider,De=o.getIdentityProof,Yt=o.clientToken,nt=o.contextMentions;o=rb({...o,features:p},r),p=o.features,o=Np(o),u(),wc(),Ti(t,o),Oi(t,o),_i(t,o),Ki(),Tn(),o.colorScheme!==b&&Uu();let it=zp.getForInstance(o.plugins);g.length=0,g.push(...it),td(),de=o.launcher?.enabled??!0,In=o.launcher?.autoExpand??!1,Is=o.features?.showReasoning??!0,Hs=o.features?.showToolCalls??!0,$i=o.features?.scrollToBottom??{};let Nt=on();vo=o.features?.scrollBehavior??{},Nt!==on()&&(mr(),On()),rg(),mu(),Ht();let pt=Zt;if(Zt=o.features?.showEventStreamToggle??!1,Zt&&!pt){if(Lt||(Ui(),x.setSSEEventCallback((N,ke)=>{o.onSSEEvent?.(N,ke),Zl(N,ke)})),!Ne&&Ke){let N=o.features?.eventStream?.classNames,ke="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"+(N?.toggleButton?" "+N.toggleButton:"");Ne=P("button",ke),Ne.style.width="28px",Ne.style.height="28px",Ne.style.color=Vt.actionIconColor,Ne.type="button",Ne.setAttribute("aria-label","Event Stream"),Ne.title="Event Stream";let Pe=yt(bb,"18px","currentColor",1.5);Pe&&Ne.appendChild(Pe);let Oe=We.clearChatButtonWrapper,Ze=We.closeButtonWrapper,Rt=Oe||Ze;Rt&&Rt.parentNode===Ke?Ke.insertBefore(Ne,Rt):Ke.appendChild(Ne),Ne.addEventListener("click",()=>{xn?_r():pc()})}}else!Zt&&pt&&(_r(),Ne&&(Ne.remove(),Ne=null),Lt?.clear(),Rr?.destroy(),Lt=null,Rr=null,Sn?.reset(),Sn=null,Yn=null);if(o.launcher?.enabled===!1&&ct&&(ct.destroy(),ct=null),o.launcher?.enabled===!1&&Ft&&(Ft.remove(),Ft=null),o.launcher?.enabled!==!1&&!ct&&!Ft){let{instance:N,element:ke}=Tp({config:o,plugins:g,onToggle:om});ct=N,N||(Ft=ke),t.appendChild(ke)}ct&&ct.update(o),si(),Yo&&o.launcher?.subtitle!==void 0&&(Yo.textContent=o.launcher.subtitle);let ze=o.layout?.header;if(ze?.layout!==ou&&Ke){let N=ze?Ol(o,ze,{showClose:Ve(),onClose:()=>Ge(!1,"user")}):kr({config:o,showClose:Ve(),onClose:()=>Ge(!1,"user")});en.replaceHeader(N),Ke=en.header.element,at=en.header.iconHolder,So=en.header.headerTitle,Yo=en.header.headerSubtitle,Ae=en.header.closeButton,ou=ze?.layout,si()}else if(ze){if(at&&(at.style.display=ze.showIcon===!1?"none":""),So&&(So.style.display=ze.showTitle===!1?"none":""),Yo&&(Yo.style.display=ze.showSubtitle===!1?"none":""),Ae){let N=Ve()&&ze.showCloseButton!==!1;Ae.style.display=N?"":"none"}if(We.clearChatButtonWrapper){let N=ze.showClearChat;if(N!==void 0){We.clearChatButtonWrapper.style.display=N?"":"none";let{closeButtonWrapper:ke}=We;ke&&!ke.classList.contains("persona-absolute")&&(N?ke.classList.remove("persona-ml-auto"):ke.classList.add("persona-ml-auto"))}}}let $n=o.layout?.showHeader!==!1;Ke&&(Ke.style.display=$n?"":"none");let yn=o.layout?.showFooter!==!1;Ie&&(Ie.style.display=yn?"":"none"),Jo(),Ht(),de!==nu?de?Ge(In,"auto"):(xe=!0,ti()):In!==tu&&Ge(In,"auto"),tu=In,nu=de,li(),gm();let zn=JSON.stringify(o.toolCall)!==JSON.stringify(d),kn=JSON.stringify(o.messageActions)!==JSON.stringify(m),No=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),pi=o.loadingIndicator?.render!==D?.render||o.loadingIndicator?.renderIdle!==D?.renderIdle||o.loadingIndicator?.showBubble!==D?.showBubble,vr=o.iterationDisplay!==$,M=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(K)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(X);(o.future?.v5Defaults===!0!==a||zn||kn||No||pi||vr||M)&&x&&(cr++,gn(ce,x.getMessages(),Jt));let fe=o.features?.streamAnimation?.type;if(fe!==ae&&fe&&fe!=="none"){let N=Ac(fe,o.features?.streamAnimation?.plugins);N&&yi(N,t)}let U=o.launcher??{},Ue=U.headerIconHidden??!1,mt=o.layout?.header?.showIcon,Bt=Ue||mt===!1,At=U.headerIconName,Ye=U.headerIconSize??Ua;if(at){let N=Ke,ke=N?.querySelector(".persona-flex-col");if(Bt)at.style.display="none",N&&ke&&!N.contains(ke)&&N.insertBefore(ke,N.firstChild);else{if(at.style.display="",at.style.height=Ye,at.style.width=Ye,N&&ke&&(N.contains(at)?at.nextSibling!==ke&&(at.remove(),N.insertBefore(at,ke)):N.insertBefore(at,ke)),At){let Oe=parseFloat(Ye)||24,Ze=se(At,Oe*.6,"currentColor",1);Ze?(Ze.style.width=`calc(${Oe}px * var(--persona-components-header-iconScale, 0.6))`,Ze.style.height=`calc(${Oe}px * var(--persona-components-header-iconScale, 0.6))`,at.replaceChildren(Ze)):at.textContent=U.agentIconText??"\u{1F4AC}"}else if(U.iconUrl){let Oe=at.querySelector("img");if(Oe)Oe.src=U.iconUrl,Oe.style.height=Ye,Oe.style.width=Ye;else{let Ze=document.createElement("img");Ze.src=U.iconUrl,Ze.alt="",Ze.className="persona-rounded-xl persona-object-cover",Ze.style.height=Ye,Ze.style.width=Ye,at.replaceChildren(Ze)}}else{let Oe=at.querySelector("svg"),Ze=at.querySelector("img");(Oe||Ze)&&at.replaceChildren(),at.textContent=U.agentIconText??"\u{1F4AC}"}let Pe=at.querySelector("img");Pe&&(Pe.style.height=Ye,Pe.style.width=Ye)}}let ut=o.layout?.header?.showTitle,Ct=o.layout?.header?.showSubtitle;if(So&&(So.style.display=ut===!1?"none":""),Yo&&(Yo.style.display=Ct===!1?"none":""),Ae){let N=Ve()&&o.layout?.header?.showCloseButton!==!1;if(Ae.style.display=N?"":"none",!Me()){let Et=U.closeButtonSize??"";Ae.style.height=Et,Ae.style.width=Et,Ae.style.minWidth=Et,Ae.style.minHeight=Et}let ke=U.closeButtonPlacement??"inline",{closeButtonWrapper:Pe}=We,Oe=ke==="top-right",Ze=Pe?.classList.contains("persona-absolute");if(Pe&&Oe!==Ze)if(Pe.remove(),Oe){Pe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Et=tt?.railColumn??re;Et.style.position="relative",Et.appendChild(Pe)}else{let Et=U.clearChat?.placement??"inline",Tt=U.clearChat?.enabled??!0;Pe.className=Tt&&Et==="inline"?"":"persona-ml-auto",Ke&&Ke.appendChild(Pe)}if(Ae.style.color=U.closeButtonColor||Vt.actionIconColor,U.closeButtonBackgroundColor?(Ae.style.backgroundColor=U.closeButtonBackgroundColor,Ae.classList.remove("hover:persona-bg-gray-100")):(Ae.style.backgroundColor="",Ae.classList.add("hover:persona-bg-gray-100")),U.closeButtonBorderWidth||U.closeButtonBorderColor){let Et=U.closeButtonBorderWidth||"0px",Tt=U.closeButtonBorderColor||"transparent";Ae.style.border=`${Et} solid ${Tt}`,Ae.classList.remove("persona-border-none")}else Ae.style.border="",Ae.classList.add("persona-border-none");U.closeButtonBorderRadius?(Ae.style.borderRadius=U.closeButtonBorderRadius,Ae.classList.remove("persona-rounded-full")):(Ae.style.borderRadius="",Ae.classList.add("persona-rounded-full")),U.closeButtonPaddingX?(Ae.style.paddingLeft=U.closeButtonPaddingX,Ae.style.paddingRight=U.closeButtonPaddingX):(Ae.style.paddingLeft="",Ae.style.paddingRight=""),U.closeButtonPaddingY?(Ae.style.paddingTop=U.closeButtonPaddingY,Ae.style.paddingBottom=U.closeButtonPaddingY):(Ae.style.paddingTop="",Ae.style.paddingBottom=""),Dl(Ae,U.closeButtonIconName??"x",{iconSize:Me()?xp:void 0,iconText:U.closeButtonIconText??"\xD7"});let Rt=U.closeButtonTooltipText??"Close chat",Ln=U.closeButtonShowTooltip??!0;Ae.setAttribute("aria-label",Rt),Pe&&Cn({anchor:Ae,trigger:Pe,text:()=>Ae?.getAttribute("aria-label")??Rt,enabled:Ln})}let{clearChatButton:ue,clearChatButtonWrapper:Qe}=We;if(ue){let N=U.clearChat??{},ke=N.enabled??!0,Pe=o.layout?.header?.showClearChat,Oe=Pe!==void 0?Pe:ke,Ze=N.placement??"inline";if(Qe){Qe.style.display=Oe?"":"none";let{closeButtonWrapper:Rt}=We;!Me()&&Rt&&!Rt.classList.contains("persona-absolute")&&(Oe?Rt.classList.remove("persona-ml-auto"):Rt.classList.add("persona-ml-auto"));let Ln=Ze==="top-right",Et=Qe.classList.contains("persona-absolute");if(!Me()&&Ln!==Et&&Oe){if(Qe.remove(),Ln){Qe.className="persona-absolute persona-top-4 persona-z-50",Qe.style.right="48px";let Un=tt?.railColumn??re;Un.style.position="relative",Un.appendChild(Qe)}else{Qe.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Qe.style.right="";let Un=We.closeButtonWrapper;Ke&&Un&&Un.parentElement===Ke?Ke.insertBefore(Qe,Un):Ke&&Ke.appendChild(Qe)}let Tt=We.closeButtonWrapper;Tt&&!Tt.classList.contains("persona-absolute")&&(Ln?Tt.classList.add("persona-ml-auto"):Tt.classList.remove("persona-ml-auto"))}}if(Oe){if(!Me()){let Tt=N.size??"";ue.style.height=Tt,ue.style.width=Tt,ue.style.minWidth=Tt,ue.style.minHeight=Tt}let Rt=N.iconColor??"";if(ue.style.color=Rt||Vt.actionIconColor,Dl(ue,N.iconName??"refresh-cw",{iconSize:Me()?Ap:void 0}),N.backgroundColor?(ue.style.backgroundColor=N.backgroundColor,ue.classList.remove("hover:persona-bg-gray-100")):(ue.style.backgroundColor="",ue.classList.add("hover:persona-bg-gray-100")),N.borderWidth||N.borderColor){let Tt=N.borderWidth||"0px",Un=N.borderColor||"transparent";ue.style.border=`${Tt} solid ${Un}`,ue.classList.remove("persona-border-none")}else ue.style.border="",ue.classList.add("persona-border-none");N.borderRadius?(ue.style.borderRadius=N.borderRadius,ue.classList.remove("persona-rounded-full")):(ue.style.borderRadius="",ue.classList.add("persona-rounded-full")),N.paddingX?(ue.style.paddingLeft=N.paddingX,ue.style.paddingRight=N.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),N.paddingY?(ue.style.paddingTop=N.paddingY,ue.style.paddingBottom=N.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let Ln=N.tooltipText??"Clear chat",Et=N.showTooltip??!0;ue.setAttribute("aria-label",Ln),Qe&&Cn({anchor:ue,trigger:Qe,text:()=>ue?.getAttribute("aria-label")??Ln,enabled:Et})}}let ye=o.actionParsers&&o.actionParsers.length?o.actionParsers:[qp],wt=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Fi.message,Fi.messageAndClick];Ee=jp({parsers:ye,handlers:wt,getSessionMetadata:Wt,updateSessionMetadata:$e,emit:G.emit,documentRef:typeof document<"u"?document:null}),Jt=Sb(o,Ee,ru),Nv(),x.updateConfig(o),Vg(),(o.features?.history?.enabled===!0!==He||o.features?.history?.provider!==Fe||o.getIdentityProof!==De||o.clientToken!==Yt)&&(tt?.closeHistory({restoreFocus:!1}),tt?.installHistoryProvider()),tt?.syncHistoryChromeImpl(),Ha(),ri()&&!tt&&od().catch(()=>{}),gn(ce,x.getMessages(),Jt),sr(),Ta(),Ov(),ni(x.isStreaming()),nt!==o.contextMentions&&bm();let vn=o.voiceRecognition?.enabled===!0,Mt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),qe=Ot(o.voiceRecognition?.provider);if(vn&&(Mt||qe))if(!te||!nn){let N=gs(o);if(N){te=N.button,nn=N.wrapper;let ke=Hn&&Hn.parentElement===Yi?Hn:null;Yi?Yi.insertBefore(nn,ke):Ut?.appendChild(nn),Be&&(Be.micButton=te),Be?.addListener(te,"click",md),te.disabled=_n()||x.isStreaming()&&!_c()}}else{let N=o.voiceRecognition??{},ke=o.sendButton??{},Pe=N.iconName??"mic",Oe=N.iconSize,Ze=parseFloat(Oe??"")||qn;te.classList.add(Uo),te.classList.toggle(Mr,!Oe),te.style.width=Oe??"",te.style.height=Oe??"",te.style.minWidth=Oe??"",te.style.minHeight=Oe??"";let Rt=N.iconColor??ke.textColor;te.innerHTML="";let Ln=se(Pe,Ze,Rt||"currentColor",1.5);Ln?te.appendChild(Ln):te.textContent="\u{1F3A4}";let Et=N.backgroundColor??ke.backgroundColor;Et?te.style.backgroundColor=Et:te.style.backgroundColor="",Rt?te.style.color=Rt:te.style.color="var(--persona-text, #111827)",N.borderWidth?(te.style.borderWidth=N.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),N.borderColor?te.style.borderColor=N.borderColor:te.style.borderColor="",N.paddingX?(te.style.paddingLeft=N.paddingX,te.style.paddingRight=N.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),N.paddingY?(te.style.paddingTop=N.paddingY,te.style.paddingBottom=N.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Tt=N.tooltipText??"Start voice recognition",Un=N.showTooltip??!1;te.setAttribute("aria-label",Tt),nn&&Cn({anchor:te,trigger:nn,text:()=>te?.getAttribute("aria-label")??Tt,enabled:Un}),nn.style.display="",te.disabled=_n()||x.isStreaming()&&!_c()}else te&&nn&&(nn.style.display="none",Ot(o.voiceRecognition?.provider)?x.isVoiceActive()&&x.toggleVoice():Nn&&Do());if(hd(),o.attachments?.enabled===!0){if(!qt||!st){let N=o.attachments??{};jt||(jt=P("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),jt.style.display="none",(Z.parentElement??Ut).insertBefore(jt,Z)),et||(et=document.createElement("input"),et.type="file",et.accept=(N.allowedTypes??us).join(","),et.multiple=(N.maxFiles??4)>1,et.style.display="none",et.setAttribute("aria-label","Attach files"),(Z.parentElement??Ut).insertBefore(et,Z)),qt=P("div","persona-send-button-wrapper"),st=P("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Uo} ${Mr}`),st.type="button",st.setAttribute("aria-label",N.buttonTooltipText??"Attach file");let ke=N.buttonIconName??"paperclip";st.style.fontSize="18px",st.style.lineHeight="1";let Pe=se(ke,qn,"currentColor",1.5);Pe?st.appendChild(Pe):st.textContent="\u{1F4CE}",st.addEventListener("click",Ze=>{Ze.preventDefault(),et?.click()}),qt.appendChild(st);let Oe=N.buttonTooltipText??"Attach file";Cn({anchor:st,trigger:qt,text:()=>st?.getAttribute("aria-label")??Oe}),nc?nc.append(qt):Ut.appendChild(qt),Be&&(Be.attachmentButton=st,Be.attachmentInput=et??void 0,Be.attachmentPreviews=jt??void 0),!_e&&et&&jt&&(_e=xi.fromConfig(N,fu),_e.setPreviewsContainer(jt),Be?.addListener(et,"change",async()=>{_e&&et?.files&&(await _e.handleFileSelect(et.files),et.value="")}))}else{qt.style.display="";let N=o.attachments??{};et&&(et.accept=(N.allowedTypes??us).join(","),et.multiple=(N.maxFiles??4)>1),_e&&_e.updateConfig({allowedTypes:N.allowedTypes,maxFileSize:N.maxFileSize,maxFiles:N.maxFiles,adapter:N.adapter})}if(re.querySelector(".persona-attachment-drop-overlay")?.remove(),re.appendChild(xb(o.attachments?.dropOverlay)),st){let N=o.attachments??{},ke=N.buttonTooltipText??"Attach file";st.setAttribute("aria-label",ke),st.textContent="";let Pe=se(N.buttonIconName??"paperclip",qn,"currentColor",1.5);Pe?st.appendChild(Pe):st.textContent="\u{1F4CE}",qt&&Cn({anchor:st,trigger:qt,text:()=>st?.getAttribute("aria-label")??ke})}}else qt&&(qt.style.display="none"),_e&&_e.clearAttachments(),re.querySelector(".persona-attachment-drop-overlay")?.remove();let be=o.sendButton??{},Vo=be.useIcon??!1,ht=be.iconText??"\u2191",Qt=be.iconName,co=be.tooltipText??"Send message",vd=be.showTooltip??!1,Cr=be.size,Cd=parseFloat(Cr??"")||bf,po=be.backgroundColor,wr=be.textColor;if(Vo){if(pe.style.width=Cr??"",pe.style.height=Cr??"",pe.style.minWidth=Cr??"",pe.style.minHeight=Cr??"",pe.style.fontSize="18px",pe.style.lineHeight="1",wr?pe.style.color=wr:pe.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!x.isStreaming())if(pe.innerHTML="",Qt){let N=parseFloat(be.iconSize??"")||Math.round(Cd*.5),ke=wr?.trim()||"currentColor",Pe=be.iconStrokeWidth??2,Oe=se(Qt,N,ke,Pe),Ze=se(be.stopIconName??"square",N,ke,Pe);Oe&&Ze?pe.appendChild(vf(Oe,Ze)):Oe?pe.appendChild(Oe):pe.textContent=ht}else pe.textContent=ht;pe.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Uo}`,po?(pe.style.backgroundColor=po,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=o.copy?.sendButtonLabel??"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.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",po?(pe.style.backgroundColor=po,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),wr?pe.style.color=wr:pe.classList.add("persona-text-white");be.borderWidth?(pe.style.borderWidth=be.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),be.borderColor?pe.style.borderColor=be.borderColor:pe.style.borderColor="",be.paddingX?(pe.style.paddingLeft=be.paddingX,pe.style.paddingRight=be.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),be.paddingY?(pe.style.paddingTop=be.paddingY,pe.style.paddingBottom=be.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom=""),x.isStreaming()||pe.setAttribute("aria-label",co),Aa(),Hn&&Cn({anchor:pe,trigger:Hn,text:()=>pe.getAttribute("aria-label")??co,enabled:vd}),ku(),xc();let km=Tl(ie.getState().activeModeIds,o.composer?.modes);ie.setActiveModeIds(km),Br().length>0!==!!Xn&&mc(),Xn?.render(km,Br());for(let N of[...Dr.keys()])El(N,o.composer?.modeGroups)||Dr.delete(N);Dr.forEach(N=>N.repaint()),Ao?.repaint(),An?.resolve();let za=Ko(o,Me());if(Sc(),za){ce.style.maxWidth=za,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",tn.style.maxWidth=za,tn.style.marginLeft="auto",tn.style.marginRight="auto",tn.style.width="100%";for(let N of[Ut,wo,jt,Re])N&&(N.style.maxWidth=za,N.style.marginLeft="auto",N.style.marginRight="auto",N.style.width="100%")}else{ce.style.maxWidth="",ce.style.marginLeft="",ce.style.marginRight="",ce.style.width="",tn.style.maxWidth="",tn.style.marginLeft="",tn.style.marginRight="",tn.style.width="";for(let N of[Ut,wo,jt,Re])N&&(N.style.maxWidth="",N.style.marginLeft="",N.style.marginRight="",N.style.width="")}let Pn=o.statusIndicator??{};if(wd(Re,Ut,Pn),ui(Re,Pn,x?.getStatus()??"idle"),x){let N=x.getStatus();Ws(Re,(Pe=>Pe==="idle"?Pn.idleText??gt.idle:Pe==="connecting"?Pn.connectingText??gt.connecting:Pe==="connected"?Pn.connectedText??gt.connected:Pe==="error"?Pn.errorText??gt.error:Pe==="paused"?Pn.pausedText??gt.paused:Pe==="resuming"?Pn.resumingText??gt.resuming:gt[Pe])(N),Pn,N)}Re.classList.remove("persona-text-left","persona-text-center","persona-text-right");let SC=Pn.align==="left"?"persona-text-left":Pn.align==="center"?"persona-text-center":"persona-text-right";Re.classList.add(SC),uc(),Nc(),Mn(),ji()},open(){Ve()&&Ge(!0,"api")},close(){Ve()&&Ge(!1,"api")},toggle(){Ve()&&Ge(!xe,"api")},reconnect(){x.reconnectNow()},clearChat(){Jn=!1,l.clear(),s.clear(),i.clear(),c.clear(),x.clearMessages(),o.layout?.topFade&&(j.scrollTop=0),j.removeAttribute("data-persona-top-fade"),It.clear(),On();try{localStorage.removeItem(Es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Es}`)}catch(a){console.error("[AgentWidget] Failed to clear default localStorage:",a)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Es)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),v?.clear&&ya(()=>v.clear(),"[AgentWidget] Failed to clear storage adapter:"),S={},Ee.syncFromMetadata(),_e?.clearAttachments(),va(),Or(void 0),Wn(void 0),lr(),Lt?.clear(),Sn?.reset(),_t?.update()},setMessage(r){return!Z||x.isStreaming()||_n()?!1:(!xe&&Ve()&&Ge(!0,"system"),Z.value=r,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(r){if(x.isStreaming()||fr())return!1;let a=r?.trim()||Z.value.trim();return a?(!xe&&Ve()&&Ge(!0,"system"),Z.value="",Z.style.height="auto",Rn(),Da(a,{consumeDraft:!1}),!0):!1},getComposerState(){return ie.getState()},setQuote(r){let a=r?.text?.trim();a&&Wn({...r,text:a})},clearQuote(){Wn(void 0)},startVoiceRecognition(){return x.isStreaming()?!1:Ot(o.voiceRecognition?.provider)?(x.isVoiceActive()||x.isBargeInActive()||(!xe&&Ve()&&Ge(!0,"system"),we.manuallyDeactivated=!1,Gt(),x.toggleVoice().then(()=>{we.active=Pc(),Gt(),oo("user"),we.active&&ns()})),!0):Nn?!0:Gg()?(!xe&&Ve()&&Ge(!0,"system"),we.manuallyDeactivated=!1,Gt(),Fa("user"),!0):!1},stopVoiceRecognition(){return Ot(o.voiceRecognition?.provider)?!x.isVoiceActive()&&!x.isBargeInActive()?!1:((x.isBargeInActive()?x.deactivateBargeIn():x.toggleVoice()).then(()=>{we.active=!1,we.manuallyDeactivated=!0,Gt(),oo("user"),lo()}),!0):Nn?(we.manuallyDeactivated=!0,Gt(),Do("user"),!0):!1},injectMessage(r){return!xe&&Ve()&&Ge(!0,"system"),x.injectMessage(r)},injectAssistantMessage(r){!xe&&Ve()&&Ge(!0,"system");let a=x.injectAssistantMessage(r);return Ls&&(Ls=!1,Hr&&(clearTimeout(Hr),Hr=null),setTimeout(()=>{x&&!x.isStreaming()&&x.continueConversation()},100)),a},injectUserMessage(r){return!xe&&Ve()&&Ge(!0,"system"),x.injectUserMessage(r)},injectSystemMessage(r){return!xe&&Ve()&&Ge(!0,"system"),x.injectSystemMessage(r)},injectMessageBatch(r){return!xe&&Ve()&&Ge(!0,"system"),x.injectMessageBatch(r)},injectComponentDirective(r){return!xe&&Ve()&&Ge(!0,"system"),x.injectComponentDirective(r)},injectTestMessage(r){!xe&&Ve()&&Ge(!0,"system"),x.injectTestEvent(r)},async connectStream(r,a){return x.connectStream(r,a)},__pushEventStreamEvent(r){Zt&&(Ui(),Zl(r.type,r.payload))},showEventStream(){Zt&&pc()},hideEventStream(){xn&&_r()},isEventStreamVisible(){return xn},listConversations(r){return x.listConversations(r)},getActiveConversationId(){return x.getActiveConversationId()},openConversation(r,a){return Fn(d=>d.openHistoryConversation(r,{focusComposer:a?.focus===!0}))},startNewConversation(r){return Fn(a=>a.startNewConversation({focusComposer:r?.focus===!0}))},warmSession(){rd()},deleteConversation(r){return Fn(a=>a.deleteHistoryConversation(r))},renameConversation(r,a){return Fn(d=>d.updateHistoryConversation(r,{title:a}))},setConversationStarred(r,a){return Fn(d=>d.updateHistoryConversation(r,{starred:a}))},clearConversationHistory(r){return Fn(a=>a.clearConversationHistory(r))},resetHistoryIdentity(){return Fn(r=>r.resetHistoryIdentity())},async getVisitorToken(){let r=mn;if(!r)return null;let a=await r.get();return r===mn?a:null},getHistoryIdentityStatus(){let r=tt?.historyProvider;return r?r.getIdentityStatus():ri()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(r){return ri()?Fn(a=>a.openHistory({...r?.returnSurface?{returnSurface:r.returnSurface}:{},...r?.focus!==void 0?{focus:r.focus}:{}})):Promise.resolve()},hideHistory(r){tt?.closeHistory(r?.restoreFocus!==void 0?{restoreFocus:r.restoreFocus}:void 0)},isHistoryVisible(){return Rs},showArtifacts(){zt(o)&&(Jn=!1,Nr=!0,Tn(),Te?.setMobileOpen(!0))},hideArtifacts(){zt(o)&&(Jn=!0,Tn())},upsertArtifact(r){return zt(o)?(as(o.features?.artifacts,{artifactType:r.artifactType,...r.artifactType==="markdown"&&r.file?{file:r.file}:{},...r.presentation?{presentation:r.presentation}:{}})==="panel"&&(Jn=!1,Nr=!0),x.upsertArtifact(r)):null},selectArtifact(r){zt(o)&&x.selectArtifact(r)},clearArtifacts(){zt(o)&&x.clearArtifacts()},getArtifacts(){return x?.getArtifacts()??[]},getSelectedArtifactId(){return x?.getSelectedArtifactId()??null},focusInput(){return de&&!xe&&!Me()||!Z?!1:(Z.focus(),!0)},async resolveApproval(r,a,d){let f=x.getMessages().find(b=>b.variant==="approval"&&b.approval?.id===r);if(!f?.approval)throw new Error(`Approval not found: ${r}`);if(f.approval.toolType==="webmcp"){x.resolveWebMcpApproval(f.id,a);return}return x.resolveApproval(f.approval,a,d)},setFollowUpSuggestions(r){lv(r)},clearFollowUpSuggestions(){og()},getMessages(){return x.getMessages()},getStatus(){return x.getStatus()},getPersistentMetadata(){return{...S}},updatePersistentMetadata(r){$e(r)},on(r,a){return G.on(r,a)},off(r,a){G.off(r,a)},isOpen(){return Ve()&&xe},isVoiceActive(){return we.active},toggleReadAloud(r){x.toggleReadAloud(r)},stopReadAloud(){x.stopSpeaking()},getReadAloudState(r){return x.getReadAloudState(r)},onReadAloudChange(r){return x.onReadAloudChange(r)},getState(){return{open:Ve()&&xe,launcherEnabled:de,voiceActive:we.active,streaming:x.isStreaming()}},showCSATFeedback(r){!xe&&Ve()&&Ge(!0,"system");let a=ce.querySelector(".persona-feedback-container");a&&a.remove();let d=hb({onSubmit:async(m,f)=>{x.isClientTokenMode()&&await x.submitCSATFeedback(m,f),r?.onSubmit?.(m,f)},onDismiss:r?.onDismiss,...r});ce.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(r){!xe&&Ve()&&Ge(!0,"system");let a=ce.querySelector(".persona-feedback-container");a&&a.remove();let d=yb({onSubmit:async(m,f)=>{x.isClientTokenMode()&&await x.submitNPSFeedback(m,f),r?.onSubmit?.(m,f)},onDismiss:r?.onDismiss,...r});ce.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(r,a){return x.submitCSATFeedback(r,a)},async submitNPSFeedback(r,a){return x.submitNPSFeedback(r,a)},destroy(){Jc(),hr!=null&&(clearInterval(hr),hr=null),l.clear(),s.clear(),i.clear(),c.clear(),oe.forEach(r=>r()),Le.remove(),St?.remove(),ct?.destroy(),Ft?.remove(),or&&Ae.removeEventListener("click",or)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let r=window.AgentWidgetBrowser,a={controller:dt,getMessages:dt.getMessages,getStatus:dt.getStatus,getMetadata:dt.getPersistentMetadata,updateMetadata:dt.updatePersistentMetadata,clearHistory:()=>dt.clearChat(),setVoiceActive:d=>d?dt.startVoiceRecognition():dt.stopVoiceRecognition()};window.AgentWidgetBrowser=a,oe.push(()=>{window.AgentWidgetBrowser===a&&(window.AgentWidgetBrowser=r)})}if(typeof window<"u"){let r=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),a=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.focusInput()};if(window.addEventListener("persona:focusInput",a),oe.push(()=>{window.removeEventListener("persona:focusInput",a)}),Zt){let q=X=>{let ae=X.detail;(!ae?.instanceId||ae.instanceId===r)&&dt.showEventStream()},K=X=>{let ae=X.detail;(!ae?.instanceId||ae.instanceId===r)&&dt.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",K),oe.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",K)})}let d=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.showHistory()},m=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.hideHistory()};window.addEventListener("persona:showHistory",d),window.addEventListener("persona:hideHistory",m),oe.push(()=>{window.removeEventListener("persona:showHistory",d),window.removeEventListener("persona:hideHistory",m)});let f=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.showArtifacts()},b=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.hideArtifacts()},D=q=>{let K=q.detail;K?.instanceId&&K.instanceId!==r||K?.artifact&&dt.upsertArtifact(K.artifact)},$=q=>{let K=q.detail;K?.instanceId&&K.instanceId!==r||typeof K?.id=="string"&&dt.selectArtifact(K.id)},F=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.clearArtifacts()};window.addEventListener("persona:showArtifacts",f),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",F),oe.push(()=>{window.removeEventListener("persona:showArtifacts",f),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",F)})}let hn=oA(o.persistState);if(hn&&Ve()){let r=rA(hn.storage),a=`${hn.keyPrefix}widget-open`,d=`${hn.keyPrefix}widget-voice`,m=`${hn.keyPrefix}widget-voice-mode`;if(r){let f=hn.persist?.openState&&r.getItem(a)==="true",b=hn.persist?.voiceState&&r.getItem(d)==="true",D=hn.persist?.voiceState&&r.getItem(m)==="true";if(f&&(ct?.setPanelOpen(!0,"auto"),setTimeout(()=>{dt.open(),setTimeout(()=>{if(b||D)dt.startVoiceRecognition();else if(hn.persist?.focusInput){let $=t.querySelector("textarea");$&&$.focus()}},100)},0)),hn.persist?.openState&&(G.on("widget:opened",()=>{r.setItem(a,"true")}),G.on("widget:closed",()=>{r.setItem(a,"false")})),hn.persist?.voiceState&&(G.on("voice:state",$=>{r.setItem(d,$.active?"true":"false")}),G.on("user:message",$=>{r.setItem(m,$.viaVoice?"true":"false")})),hn.clearOnChatClear){let $=()=>{r.removeItem(a),r.removeItem(d),r.removeItem(m)},F=()=>$();window.addEventListener("persona:clear-chat",F),oe.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}if(Xe&&Ve()&&(ct?.setPanelOpen(!0,"auto"),setTimeout(()=>{dt.open()},0)),Yr(),!cv){let r=Ka(()=>{x&&(cr++,It.clear(),gn(ce,x.getMessages(),Jt))});oe.push(r)}R=()=>{x&&(cr++,It.clear(),gn(ce,x.getMessages(),Jt))},x.getMessages().length>0&&xa(),_=()=>{x&&(cr++,It.clear(),gn(ce,x.getMessages(),Jt))};let CC=Fm(()=>{x&&(cr++,It.clear(),gn(ce,x.getMessages(),Jt))});oe.push(CC);let wC=Dp(()=>{x&&(cr++,It.clear(),gn(ce,x.getMessages(),Jt),yo()?.updateInlineArtifactBlocks(ce,pn.artifacts,{suppressTransition:!0}),Tn())});return oe.push(wC),dt};var Mb=(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},aA=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},lA=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},cA=(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.")},Eb=(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"},Jp=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=""},Tb=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Jp(t)},Yp=t=>{t.style.transition=""},Qp=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=""},Xp=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Ql=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},dA=(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))},pA=(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)},uA=t=>{let e=ho(t),n=e.components?.panel,o=(s,i)=>s==null||s===""?i:Pt(e,s)??s;return{inset:o(n?.inset,Il),canvasBackground:o(n?.canvasBackground,Hl)}},kb=(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},gA=(t,e,n,o,s,i,l,c)=>{let u=wn(i),p=u.reveal==="push",g=c!=null,y=c?.inset??"",h=c?.canvasBackground??"";dA(t,e,n,o,p),pA(t,e,n,o,u.side,p),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=u.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 C=t.ownerDocument.defaultView,E=i?.launcher?.mobileFullscreen??!0,A=i?.launcher?.mobileBreakpoint??640,I=C!=null?C.innerWidth<=A:!1;if(E&&I&&l){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Qp(e),Yp(o),Tb(o),Xp(n),Ql(s,o),kb(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??Dt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(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"),Tb(o),aA(o,u.maxHeight),kb(o,g&&l,y,h),u.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Qp(e),Yp(o),Xp(n),Ql(s,o);let k=u.animate?"transform 180ms ease":"none",R=u.side==="right"?"translateX(100%)":"translateX(-100%)",B=l?"translateX(0)":R;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=u.width,o.style.maxWidth=u.width,o.style.minWidth=u.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=k,o.style.transform=B,o.style.pointerEvents=l?"auto":"none",o.style.zIndex="2",u.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(u.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Yp(o),Jp(o),Ql(s,o);let k=Mb(u.width,t.clientWidth),R=Math.max(0,t.clientWidth),B=u.animate?"margin-left 180ms ease":"none",O=u.side==="right"?l?-k:0:l?0:-k;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=`${R+k}px`,e.style.transition=B,e.style.marginLeft=`${O}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${R}px`,n.style.maxWidth=`${R}px`,n.style.minWidth=`${R}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=u.width,o.style.minWidth=u.width,o.style.maxWidth=u.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="",Qp(e),Jp(o),Xp(n),Ql(s,o);let k=u.reveal==="emerge";k?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let R=l?u.width:"0px",B=u.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${g?", padding 180ms ease":""}`:"none",O=!l;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${R}`,o.style.width=R,o.style.maxWidth=R,o.style.minWidth=R,o.style.minHeight="0",lA(o,u.maxHeight),o.style.overflow=k||O?"hidden":"visible",o.style.transition=B,k){o.style.alignItems=u.side==="right"?"flex-start":"flex-end";let V=g?`calc(${Mb(u.width,t.clientWidth)}px - (2 * ${y}))`:u.width;s.style.width=V,s.style.minWidth=V,s.style.maxWidth=V,s.style.boxSizing="border-box"}}},mA=(t,e)=>{let n=t.ownerDocument.createElement("div");return Eb(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Eb(n,o)},destroy(){n.remove()}}},fA=(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"),u=n.createElement("div"),p=n.createElement("aside"),g=n.createElement("div"),y=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;c.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",p.appendChild(g),o.insertBefore(l,t),u.appendChild(t);let h=null,C=()=>{h?.disconnect(),h=null},E=null,A=()=>{E=e?.launcher?.detachedPanel===!0?uA(e):null};A();let I=()=>{gA(l,c,u,p,g,e,y,E)},L=null,k=()=>{L?.(),L=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(L=Rl(()=>{A(),I()}))},R=()=>{C(),wn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{I()}),h.observe(l)))},B=!1,O=()=>{I(),R(),y&&!B&&l.dataset.personaDockMobileFullscreen!=="true"&&(B=!0,cA(l,wn(e)))},V=l.ownerDocument.defaultView,J=()=>{O()};return V?.addEventListener("resize",J),wn(e).reveal==="push"?(c.appendChild(u),c.appendChild(p),l.appendChild(c)):(l.appendChild(u),l.appendChild(p)),O(),k(),{mode:"docked",host:g,shell:l,syncWidgetState(_){let Q=_.launcherEnabled?_.open:!0;y!==Q&&(y=Q,O())},updateConfig(_){e=_,(e?.launcher?.enabled??!0)===!1&&(y=!0),A(),O(),k()},destroy(){V?.removeEventListener("resize",J),L?.(),L=null,C(),o.isConnected&&(i&&i.parentNode===o?o.insertBefore(t,i):o.appendChild(t)),l.remove()}}},Pb=(t,e)=>rt(e)?fA(t,e):mA(t,e);var Vi={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Lb=.15,Ib=1.5,Zp="persona-preview-shell-theme",hA={load:()=>null,save:()=>{},clear:()=>{}},yA=["How do I get started?","Pricing & plans","Talk to support"];function eu(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function bA(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 Hb(t){let e=bA(t);return`* { box-sizing: border-box; }
125
125
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
126
126
  html { color-scheme: ${t}; }
127
127
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
@@ -145,7 +145,7 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
145
145
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
146
146
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
147
147
  .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}; }
148
- .preview-workspace-card.short { height: 96px; }`}function Lb(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Xp);o||(o=n.createElement("style"),o.id=Xp,n.head.appendChild(o)),o.textContent=Pb(e)}var fA=`
148
+ .preview-workspace-card.short { height: 96px; }`}function Rb(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Zp);o||(o=n.createElement("style"),o.id=Zp,n.head.appendChild(o)),o.textContent=Hb(e)}var vA=`
149
149
  <div class="preview-iframe-mock" aria-hidden="true">
150
150
  <div class="preview-iframe-chrome">
151
151
  <span class="preview-iframe-dot"></span>
@@ -164,7 +164,7 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
164
164
  <div class="preview-iframe-line body"></div>
165
165
  <div class="preview-iframe-line body"></div>
166
166
  </div>
167
- </div>`,hA=`
167
+ </div>`,CA=`
168
168
  <div class="preview-workspace-content-shell" aria-hidden="true">
169
169
  <div class="preview-iframe-line hero"></div>
170
170
  <div class="preview-iframe-line body"></div>
@@ -177,8 +177,8 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
177
177
  <div class="preview-workspace-card short"></div>
178
178
  <div class="preview-workspace-card short"></div>
179
179
  </div>
180
- </div>`;function Ib(t,e,n,o){let s=`
181
- ${fA}
180
+ </div>`;function Wb(t,e,n,o){let s=`
181
+ ${vA}
182
182
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,i=`
183
183
  <div class="preview-workspace-shell">
184
184
  <div class="preview-workspace-topbar">
@@ -190,7 +190,7 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
190
190
  </div>
191
191
  <div class="preview-workspace-body">
192
192
  <div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
193
- ${hA}
193
+ ${CA}
194
194
  </div>
195
195
  </div>
196
196
  </div>`;return`<!DOCTYPE html>
@@ -198,16 +198,16 @@ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n
198
198
  <head>
199
199
  <meta charset="UTF-8">
200
200
  <meta name="viewport" content="width=device-width, initial-scale=1">
201
- <link rel="stylesheet" href="${Jp(o)}">
202
- <style id="${Xp}">${Pb(e)}</style>
201
+ <link rel="stylesheet" href="${eu(o)}">
202
+ <style id="${Zp}">${Hb(e)}</style>
203
203
  </head>
204
204
  <body>
205
205
  ${n?i:s}
206
206
  </body>
207
- </html>`}var yA=()=>[{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()}],bA=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function vA(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"&&bA(e)?[...yA(),...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 CA(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},s={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:gA:t.suggestionChips,initialMessages:vA(e,t,n),storageAdapter:uA};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 wA(t,e){let n=Wm(t.config),o=t.config?.future,s=t.theme?ys(t.theme,{validate:!1,future:o}):ys(void 0,{future:o});return{...n,...t.config,theme:s,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function ks(t,e){let n=t.scene??"conversation";return CA(wA(t,e),n,t.appendedMessages??[])}function Hb(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:ks(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:ks(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:ks(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:ks(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:ks(t,n),shellMode:n}]}function SA(t,e){let n={...e},o=[],s=[],i=null,l=!1,c=1,u=1,p=0;function g(){return n.device??"desktop"}function y(){return n.zoom??c}function h(){let k=getComputedStyle(t),R=parseFloat(k.paddingLeft)+parseFloat(k.paddingRight),B=parseFloat(k.paddingTop)+parseFloat(k.paddingBottom),O=40,V=(n.compareMode??"off")!=="off",J=(t.clientWidth-R-O)/(V?2:1),_=t.clientHeight-B-O;if(J<=0||_<=0)return 1;let Q=Ni[g()]??Ni.desktop;return Math.min(J/Q.w,_/Q.h,1)}function C(){c=h();let k=Math.max(Tb,Math.min(kb,y()));u=k;let R=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let B of R){let O=B.dataset.device??"desktop",V=Ni[O]??Ni.desktop;B.style.width=`${V.w*k}px`,B.style.height=`${V.h*k}px`,O==="mobile"&&(B.style.borderRadius=`${32*k}px`);let J=B.querySelector("iframe");J&&(J.style.width=`${V.w}px`,J.style.height=`${V.h}px`,J.style.transformOrigin="top left",J.style.transition="none",J.style.transform=`scale(${k})`)}n.onScaleChange?.(k)}function E(){n.onBeforeDestroy?.();for(let k of o)k.destroy();for(let k of s)k();o=[],s=[]}function A(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function I(){if(l)return;E();let k=++p,R=Hb(n),B=g(),O=(n.compareMode??"off")!=="off",V=(n.scene??"conversation")==="minimized",J=n.widgetCssPath??"/widget-dist/widget.css",_=n.buildSrcdoc??Ib,Q=B==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",G=W=>`<div class="${Q}" data-mount-id="${W.mountId}" data-device="${B}" data-shell-mode="${W.shellMode}">
208
- ${O?`<div class="preview-frame-meta"><span class="preview-frame-label">${Jp(W.label)}</span></div>`:""}
207
+ </html>`}var wA=()=>[{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()}],SA=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function xA(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"&&SA(e)?[...wA(),...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 AA(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},s={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:yA:t.suggestionChips,initialMessages:xA(e,t,n),storageAdapter:hA};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 MA(t,e){let n=Om(t.config),o=t.config?.future,s=t.theme?ys(t.theme,{validate:!1,future:o}):ys(void 0,{future:o});return{...n,...t.config,theme:s,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function ks(t,e){let n=t.scene??"conversation";return AA(MA(t,e),n,t.appendedMessages??[])}function Bb(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:ks(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:ks(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:ks(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:ks(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:ks(t,n),shellMode:n}]}function EA(t,e){let n={...e},o=[],s=[],i=null,l=!1,c=1,u=1,p=0;function g(){return n.device??"desktop"}function y(){return n.zoom??c}function h(){let k=getComputedStyle(t),R=parseFloat(k.paddingLeft)+parseFloat(k.paddingRight),B=parseFloat(k.paddingTop)+parseFloat(k.paddingBottom),O=40,V=(n.compareMode??"off")!=="off",J=(t.clientWidth-R-O)/(V?2:1),_=t.clientHeight-B-O;if(J<=0||_<=0)return 1;let Q=Vi[g()]??Vi.desktop;return Math.min(J/Q.w,_/Q.h,1)}function C(){c=h();let k=Math.max(Lb,Math.min(Ib,y()));u=k;let R=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let B of R){let O=B.dataset.device??"desktop",V=Vi[O]??Vi.desktop;B.style.width=`${V.w*k}px`,B.style.height=`${V.h*k}px`,O==="mobile"&&(B.style.borderRadius=`${32*k}px`);let J=B.querySelector("iframe");J&&(J.style.width=`${V.w}px`,J.style.height=`${V.h}px`,J.style.transformOrigin="top left",J.style.transition="none",J.style.transform=`scale(${k})`)}n.onScaleChange?.(k)}function E(){n.onBeforeDestroy?.();for(let k of o)k.destroy();for(let k of s)k();o=[],s=[]}function A(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function I(){if(l)return;E();let k=++p,R=Bb(n),B=g(),O=(n.compareMode??"off")!=="off",V=(n.scene??"conversation")==="minimized",J=n.widgetCssPath??"/widget-dist/widget.css",_=n.buildSrcdoc??Wb,Q=B==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",G=W=>`<div class="${Q}" data-mount-id="${W.mountId}" data-device="${B}" data-shell-mode="${W.shellMode}">
208
+ ${O?`<div class="preview-frame-meta"><span class="preview-frame-label">${eu(W.label)}</span></div>`:""}
209
209
  <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${W.mountId}"></iframe>
210
- </div>`,w=O?`<div class="preview-compare-grid">${R.map(W=>`<div class="preview-compare-cell">${G(W)}</div>`).join("")}</div>`:`<div class="preview-single">${G(R[0])}</div>`;n.morphContainer?n.morphContainer(t,w):t.innerHTML=w,C();let v=A(),T=0,x=v.length,z=()=>{if(l||k!==p)return;for(let ee of v){let ne=ee.dataset.mountId;if(!ne||!ee.contentDocument)continue;let he=R.find($e=>$e.mountId===ne);if(!he)continue;let ve=()=>{},Xe=rt(he.config),Je=Xe?(()=>{let $e=ee.contentDocument?.getElementById(`preview-content-${ne}`);if(!$e)return null;let Ce=Eb($e,he.config),H=ee.contentDocument.createElement("div");H.id=ne,H.style.height="100%",H.style.display="flex",H.style.flexDirection="column",H.style.flex="1",H.style.minHeight="0",Ce.host.appendChild(H);let Me=()=>Ce.syncWidgetState(Wt.getState()),de=ve;return ve=()=>{Ce.destroy(),de()},H.__syncDock=Me,H.__hostLayout=Ce,H})():ee.contentDocument.getElementById(ne);if(!Je)continue;let Wt=wb(Je,he.config);if(o.push(Wt),Xe&&Je.__syncDock){let $e=Je.__syncDock,Ce=Wt.on("widget:opened",$e),H=Wt.on("widget:closed",$e),Me=ve;ve=()=>{Ce(),H(),Me()},$e()}s.push(ve),V&&Wt.close()}let W=n.scene??"conversation";if(W==="messages")for(let ee of o)ee.showHistory({focus:!1});if(W==="artifact"||n.config?.features?.artifacts?.enabled)for(let ee of o)ee.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
210
+ </div>`,w=O?`<div class="preview-compare-grid">${R.map(W=>`<div class="preview-compare-cell">${G(W)}</div>`).join("")}</div>`:`<div class="preview-single">${G(R[0])}</div>`;n.morphContainer?n.morphContainer(t,w):t.innerHTML=w,C();let v=A(),T=0,S=v.length,z=()=>{if(l||k!==p)return;for(let ee of v){let ne=ee.dataset.mountId;if(!ne||!ee.contentDocument)continue;let he=R.find($e=>$e.mountId===ne);if(!he)continue;let ve=()=>{},Xe=rt(he.config),Je=Xe?(()=>{let $e=ee.contentDocument?.getElementById(`preview-content-${ne}`);if(!$e)return null;let Ce=Pb($e,he.config),H=ee.contentDocument.createElement("div");H.id=ne,H.style.height="100%",H.style.display="flex",H.style.flexDirection="column",H.style.flex="1",H.style.minHeight="0",Ce.host.appendChild(H);let Ee=()=>Ce.syncWidgetState(Wt.getState()),de=ve;return ve=()=>{Ce.destroy(),de()},H.__syncDock=Ee,H.__hostLayout=Ce,H})():ee.contentDocument.getElementById(ne);if(!Je)continue;let Wt=Ab(Je,he.config);if(o.push(Wt),Xe&&Je.__syncDock){let $e=Je.__syncDock,Ce=Wt.on("widget:opened",$e),H=Wt.on("widget:closed",$e),Ee=ve;ve=()=>{Ce(),H(),Ee()},$e()}s.push(ve),V&&Wt.close()}let W=n.scene??"conversation";if(W==="messages")for(let ee of o)ee.showHistory({focus:!1});if(W==="artifact"||n.config?.features?.artifacts?.enabled)for(let ee of o)ee.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
211
211
 
212
212
  This is a preview of the artifact sidebar.
213
213
 
@@ -215,4 +215,4 @@ This is a preview of the artifact sidebar.
215
215
 
216
216
  - Markdown rendering
217
217
  - Document toolbar
218
- - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:v,controllers:[...o]})};for(let W of v){let ee=W.dataset.mountId;if(!ee)continue;let ne=R.find(he=>he.mountId===ee);ne&&(W.addEventListener("load",()=>{T++,T>=x&&z()},{once:!0}),W.srcdoc=_(ee,ne.shellMode,rt(ne.config),J))}x===0&&z()}function L(){if(l)return;let k=Hb(n);if(o.length!==k.length){I();return}if(k.some(B=>{let O=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!O||O.dataset.shellMode!==B.shellMode})){I();return}o.forEach((B,O)=>{B.update(k[O].config),(n.scene??"conversation")==="minimized"&&B.close()});for(let B of k){let O=t.querySelector(`iframe[data-mount-id="${B.mountId}"]`);O&&Lb(O,B.shellMode)}n.onAfterUpdate?.({iframes:A(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(i=new ResizeObserver(()=>{l||C()}),i.observe(t)),I(),{update(k){if(l)return;let R=k.device!==void 0&&k.device!==n.device||k.scene!==void 0&&k.scene!==n.scene||k.compareMode!==void 0&&k.compareMode!==n.compareMode||k.widgetCssPath!==void 0&&k.widgetCssPath!==n.widgetCssPath;n={...n,...k},R?I():L()},destroy(){l||(l=!0,E(),i?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){l||(n={...n,zoom:void 0},C())},getIframes(){return A()},getScale(){return u},setZoom(k){l||(n={...n,zoom:k},C())}}}export{SA as createThemePreview};
218
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:v,controllers:[...o]})};for(let W of v){let ee=W.dataset.mountId;if(!ee)continue;let ne=R.find(he=>he.mountId===ee);ne&&(W.addEventListener("load",()=>{T++,T>=S&&z()},{once:!0}),W.srcdoc=_(ee,ne.shellMode,rt(ne.config),J))}S===0&&z()}function L(){if(l)return;let k=Bb(n);if(o.length!==k.length){I();return}if(k.some(B=>{let O=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!O||O.dataset.shellMode!==B.shellMode})){I();return}o.forEach((B,O)=>{B.update(k[O].config),(n.scene??"conversation")==="minimized"&&B.close()});for(let B of k){let O=t.querySelector(`iframe[data-mount-id="${B.mountId}"]`);O&&Rb(O,B.shellMode)}n.onAfterUpdate?.({iframes:A(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(i=new ResizeObserver(()=>{l||C()}),i.observe(t)),I(),{update(k){if(l)return;let R=k.device!==void 0&&k.device!==n.device||k.scene!==void 0&&k.scene!==n.scene||k.compareMode!==void 0&&k.compareMode!==n.compareMode||k.widgetCssPath!==void 0&&k.widgetCssPath!==n.widgetCssPath;n={...n,...k},R?I():L()},destroy(){l||(l=!0,E(),i?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){l||(n={...n,zoom:void 0},C())},getIframes(){return A()},getScale(){return u},setZoom(k){l||(n={...n,zoom:k},C())}}}export{EA as createThemePreview};