@runtypelabs/persona 4.28.2 → 4.29.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/approval-ui.cjs +3 -3
- package/dist/approval-ui.d.cts +1 -1
- package/dist/approval-ui.d.ts +1 -1
- package/dist/approval-ui.js +3 -3
- package/dist/artifacts-ui.d.cts +2 -2
- package/dist/artifacts-ui.d.ts +2 -2
- package/dist/chunk-B1-_pp-Y.js +4 -0
- package/dist/{chunk-DrYAfpvk.js → chunk-BcLIgi1h.js} +1 -1
- package/dist/chunk-BkW8s3fj.js +2 -0
- package/dist/chunk-Bm2-bemv.js +1 -0
- package/dist/chunk-BvhTpG6k.js +1 -0
- package/dist/chunk-Csks3Qw1.js +1 -0
- package/dist/chunk-D5B629Mj.js +1 -0
- package/dist/chunk-DGlFKA0r.js +9 -0
- package/dist/chunk-DO9_WSpy.js +1 -0
- package/dist/chunk-DTDHeUsG.js +1 -0
- package/dist/chunk-DjFpGFGA.js +1 -0
- package/dist/{chunk-dRBlrLd7.js → chunk-DtmtfIkd.js} +1 -1
- package/dist/chunk-lA5CJCgK.js +1 -0
- package/dist/client-history.js +1 -1
- package/dist/client-stream.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/{composer-input-C39npJaz.d.cts → composer-input-B0P4OtNi.d.cts} +1 -1
- package/dist/{composer-input-C39npJaz.d.ts → composer-input-B0P4OtNi.d.ts} +1 -1
- package/dist/{context-mention-manager-DLCB1l9E.d.cts → context-mention-manager-DmLI_RM6.d.cts} +1 -1
- package/dist/{context-mention-manager-DLCB1l9E.d.ts → context-mention-manager-DmLI_RM6.d.ts} +1 -1
- package/dist/context-mentions-inline.d.cts +2 -2
- package/dist/context-mentions-inline.d.ts +2 -2
- package/dist/context-mentions.d.cts +3 -3
- package/dist/context-mentions.d.ts +3 -3
- package/dist/{defaults-DiAgWHXy.d.cts → defaults-DVo1wbZs.d.cts} +1 -1
- package/dist/{defaults-DiAgWHXy.d.ts → defaults-DVo1wbZs.d.ts} +1 -1
- package/dist/event-stream-view.d.cts +1 -1
- package/dist/event-stream-view.d.ts +1 -1
- package/dist/{fallback-speech-engine-C5_PUZjH.d.cts → fallback-speech-engine-BMnlmKnY.d.cts} +1 -1
- package/dist/{fallback-speech-engine-C5_PUZjH.d.ts → fallback-speech-engine-BMnlmKnY.d.ts} +1 -1
- package/dist/forms-ui.d.cts +2 -2
- package/dist/forms-ui.d.ts +2 -2
- package/dist/history-view.d.cts +1 -1
- package/dist/history-view.d.ts +1 -1
- package/dist/index.cjs +50 -49
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.global.js +2 -3
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +38 -37
- package/dist/index.js.map +1 -1
- package/dist/{markdown-parsers-loader-BBdyIEU7.d.cts → markdown-parsers-loader-CeovcyYf.d.cts} +1 -1
- package/dist/{markdown-parsers-loader-BBdyIEU7.d.ts → markdown-parsers-loader-CeovcyYf.d.ts} +1 -1
- package/dist/{preview-Chjb0bmI.d.cts → preview-Bkb4UrQC.d.cts} +2 -2
- package/dist/{preview-Chjb0bmI.d.ts → preview-Bkb4UrQC.d.ts} +2 -2
- package/dist/session-actions.js +1 -1
- package/dist/{session-a_qIp4xp.d.ts → session-iLyKipoM.d.cts} +28 -10
- package/dist/{session-a_qIp4xp.d.cts → session-iLyKipoM.d.ts} +28 -10
- package/dist/session-reconnect.cjs +1 -1
- package/dist/session-reconnect.d.cts +8 -2
- package/dist/session-reconnect.d.ts +8 -2
- package/dist/session-reconnect.js +1 -1
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +61 -60
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +40 -40
- package/dist/theme-editor.d.cts +2 -2
- package/dist/theme-editor.d.ts +2 -2
- package/dist/theme-reference.d.cts +2 -2
- package/dist/theme-reference.d.ts +2 -2
- package/dist/{types-BdO1jNRm.d.cts → types-BuDirJkQ.d.cts} +200 -23
- package/dist/{types-BdO1jNRm.d.ts → types-BuDirJkQ.d.ts} +200 -23
- package/dist/voice-client-tools.cjs +1 -0
- package/dist/voice-client-tools.d.cts +13 -0
- package/dist/voice-client-tools.d.ts +13 -0
- package/dist/voice-client-tools.js +1 -0
- package/dist/voice-runtime.cjs +3 -3
- package/dist/voice-runtime.d.cts +15 -5
- package/dist/voice-runtime.d.ts +15 -5
- package/dist/voice-runtime.js +5 -5
- package/dist/voice-worklet-player.d.cts +2 -2
- package/dist/voice-worklet-player.d.ts +2 -2
- package/dist/{webmcp-runtime-entry-B6bpVWSa.d.ts → webmcp-runtime-entry-CXLjRt1k.d.cts} +26 -5
- package/dist/{webmcp-runtime-entry-B6bpVWSa.d.cts → webmcp-runtime-entry-CXLjRt1k.d.ts} +26 -5
- package/dist/webmcp-runtime.cjs +2 -1
- package/dist/webmcp-runtime.d.cts +1 -1
- package/dist/webmcp-runtime.d.ts +1 -1
- package/dist/webmcp-runtime.js +2 -1
- package/dist/widget.css +1 -1
- package/package.json +6 -1
- package/src/client-approve.test.ts +17 -1
- package/src/client-resume.ts +15 -3
- package/src/client.interrupt.test.ts +21 -0
- package/src/client.ts +61 -4
- package/src/client.voice-tools.test.ts +65 -0
- package/src/components/activity-row.ts +3 -2
- package/src/components/approval-actions.test.ts +8 -0
- package/src/components/approval-actions.ts +6 -2
- package/src/components/approval-bubble.test.ts +14 -0
- package/src/components/approval-bubble.ts +8 -1
- package/src/components/tool-bubble.ts +8 -5
- package/src/generated/runtype-openapi-contract.ts +39 -1
- package/src/index-core.ts +11 -0
- package/src/index-global.ts +6 -0
- package/src/resume-dedupe-local-only.test.ts +273 -0
- package/src/runtime/persist-state.test.ts +86 -0
- package/src/session-actions.ts +20 -6
- package/src/session-reconnect.ts +18 -1
- package/src/session.restored-browser-tools.test.ts +272 -0
- package/src/session.test.ts +26 -0
- package/src/session.ts +185 -31
- package/src/session.voice.test.ts +212 -0
- package/src/styles/widget.css +4 -2
- package/src/types.ts +178 -22
- package/src/ui.restored-browser-tools.test.ts +128 -0
- package/src/ui.ts +32 -18
- package/src/utils/formatting.test.ts +9 -1
- package/src/utils/formatting.ts +4 -0
- package/src/utils/local-only-message.ts +15 -0
- package/src/utils/restored-browser-state.ts +50 -0
- package/src/utils/storage.ts +12 -1
- package/src/utils/voice-prior-tool-results.ts +37 -0
- package/src/voice/runtype-voice-provider.ts +94 -7
- package/src/voice/session-voice-wiring.ts +27 -3
- package/src/voice/voice-client-tools-session.ts +116 -0
- package/src/voice/voice-delegation.ts +19 -3
- package/src/voice/voice.test.ts +396 -0
- package/src/voice-client-tools-bundle.test.ts +37 -0
- package/src/voice-client-tools-loader.ts +24 -0
- package/src/voice-client-tools.ts +9 -0
- package/src/webmcp-bridge.test.ts +152 -1
- package/src/webmcp-bridge.ts +5 -6
- package/src/webmcp-polyfill.integration.test.ts +5 -1
- package/src/webmcp-runtime-entry.ts +151 -26
- package/dist/chunk-B6zZsT6F.js +0 -1
- package/dist/chunk-CztSjKHK.js +0 -9
- package/dist/chunk-DbhxjyOB.js +0 -4
- package/dist/chunk-DsdqLStH.js +0 -1
- package/dist/chunk-GIqbL2Eg.js +0 -1
- package/dist/chunk-HUOUif-P.js +0 -1
- package/dist/chunk-UlcxdHef.js +0 -1
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as a,H as o,L as s,M as c,N as l,O as u,P as d,R as f,S as p,T as m,U as h,V as g,W as _,_ as v,a as y,b,c as x,d as S,f as C,g as w,h as T,i as E,j as D,k as O,l as k,m as ee,n as te,o as ne,p as re,r as ie,s as ae,t as oe,u as se,v as ce,w as le,x as ue,y as de,z as fe}from"./chunk-BIhTjsVQ.js";import{i as pe,r as A,t as j}from"./chunk-D5BxWOFB.js";import{a as me,n as M,r as he,t as ge}from"./chunk-BypiAEpx.js";import{c as _e,d as ve,f as ye,i as be,l as xe,m as Se,n as Ce,p as we,r as Te,t as Ee,u as De}from"./chunk-SE7Q9NmG.js";import{_ as Oe,a as ke,b as Ae,c as je,d as Me,f as Ne,g as Pe,i as Fe,m as Ie,n as Le,o as Re,p as ze,r as Be,s as Ve,t as He,u as Ue,v as We,y as Ge}from"./chunk-dRBlrLd7.js";import{f as Ke,r as qe,s as Je,u as Ye}from"./chunk-CD4-AYdH.js";import{a as Xe,i as Ze,r as Qe}from"./chunk-CfNME4R9.js";import{a as $e,i as et,n as tt,r as nt,t as rt}from"./chunk-CPdEltCR.js";import{t as N}from"./chunk-UlcxdHef.js";import{a as it,c as at,d as P,l as ot,n as st,o as ct,t as lt,u as ut}from"./chunk-BlTD-Wgn.js";import{a as dt,n as ft,r as pt,s as mt,t as ht}from"./chunk-DpyghsEW.js";import{i as gt,n as _t}from"./chunk-Bb41bKyp.js";import{t as vt}from"./chunk-C8560fIY.js";import{i as yt,n as bt,r as xt,t as St}from"./chunk-lwPt6bL9.js";import{t as Ct}from"./chunk-CQw6A6rt.js";import{n as wt}from"./chunk-py2YB6PV.js";import{a as Tt,c as Et,i as Dt,l as Ot,n as kt,o as At,r as jt,s as Mt,t as Nt}from"./chunk-CVMIncEY.js";import{a as Pt,c as Ft,i as It,l as Lt,n as Rt,o as zt,r as Bt,s as Vt,t as Ht,u as Ut}from"./chunk-BExOAPZb.js";import{Activity as Wt,ArrowRight as Gt,Check as Kt,ChevronDown as qt,ChevronUp as Jt,Circle as Yt,Clock as Xt,Copy as Zt,File as Qt,FileCode as $t,FileSpreadsheet as en,FileText as tn,MessageSquare as nn,X as rn}from"lucide";import"partial-json";import{Idiomorph as an}from"idiomorph";const on=[`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`],sn=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),cn=(e,t)=>{let n=j(`div`,[`persona-message-bubble`,e,...on].join(` `));return n.id=`bubble-${t}`,n.setAttribute(`data-message-id`,t),n},ln=e=>{let t=j(`button`,e.expandable?`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`:`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`);return t.type=`button`,e.expandable&&(t.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),t.setAttribute(`data-expand-header`,`true`)),t.setAttribute(`data-bubble-type`,e.bubbleType),t},un=(t,n,r)=>{t.innerHTML=``;let i=e(n?Jt:qt,16,r,2);i?t.appendChild(i):t.textContent=n?`Hide`:`Show`},dn=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let r=j(`div`,`persona-flex persona-items-center`);un(r,n.expanded,n.iconColor);let i=j(`div`,n.metaGap?`persona-flex persona-items-center persona-gap-2 persona-ml-auto`:`persona-flex persona-items-center persona-ml-auto`);return i.append(r),e.append(t,i),r},fn=e=>{let t=j(`div`,`persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted`);if(t.setAttribute(`data-persona-collapsed-preview`,e.previewKind),t.style.display=`none`,t.style.whiteSpace=`pre-wrap`,!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();sn(t,n)||(t.textContent=e.previewText),t.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},pn=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&un(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?``:`none`,e.collapsedPreview.style.display=e.expanded?`none`:e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?``:`none`},mn=(e,t,n)=>{let r=n.stateSet.has(e),i=t.querySelector(`button[data-expand-header="true"]`),a=t.querySelector(`.persona-border-t`),o=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!i||!a)return;i.setAttribute(`aria-expanded`,r?`true`:`false`);let s=i.querySelector(`.persona-ml-auto`)?.querySelector(`:scope > .persona-flex.persona-items-center`);s&&un(s,r,n.iconColor),a.style.display=r?``:`none`,o&&(o.style.display=r?`none`:o.textContent||o.childNodes.length?``:`none`)};function hn(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[n]:{...t===`tool`?c:D,...e?.future?.v5Defaults===!0?u.features?.[n]:{},...e?.features?.[n]}}}}function gn(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[n]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function _n(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?`a moment`:t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function vn(t,n,r,i){if(gn(r,i)!==`row`)return t;t.className=`persona-message-bubble persona-${i}-bubble persona-activity-row`,t.dataset.activityKind=i,i===`tool`&&r.toolCall?.shadow===void 0&&(t.style.boxShadow=`var(--persona-tool-bubble-shadow, none)`);let a=t.querySelector(`:scope > button`);if(!a)return t;a.className=`persona-activity-header`;let o=i===`tool`?n.toolCall:n.reasoning,s=o?.status!==`complete`,c=n.approval?.status??n.toolCall?.approvalStatus,l=c===`denied`?`denied`:c===`pending`?`awaiting-approval`:n.toolCall?.success===!1?`error`:s?o?.status===`pending`?`pending`:`running`:`done`;t.dataset.activityState=l;let u=j(`span`,`persona-activity-icon`);u.dataset.activityIcon=l;let d={pending:`circle`,running:`loader-circle`,done:`check`,error:`x`,denied:`x`,"awaiting-approval":`clock`},f=i===`reasoning`?r.features?.reasoningDisplay?.iconName:void 0,p=f?M(f,16,`currentColor`,2):l===`pending`?e(Yt,16,`currentColor`,2):l===`awaiting-approval`?e(Xt,16,`currentColor`,2):M(d[l],16,`currentColor`,2);p&&u.appendChild(p),a.querySelector(`.persona-reasoning-header-icon`)?.remove();let m=i===`tool`?`toolCallDisplay`:`reasoningDisplay`,h=r.features?.[m]?.iconVisibility??(r.future?.v5Defaults?`active`:`always`);if((h===`always`||h===`active`&&l!==`done`)&&a.prepend(u),i===`tool`&&o){let e=j(`span`,`persona-activity-duration`);s&&o.startedAt&&e.setAttribute(`data-tool-elapsed`,String(o.startedAt));let t=(i===`tool`?n.toolCall?.duration:void 0)??o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0);e.textContent=t===void 0?``:_n(t),a.appendChild(e)}a.querySelector(`:scope > div:not(.persona-ml-auto)`)?.classList.add(`persona-activity-label`),a.querySelector(`.persona-ml-auto`)?.classList.add(`persona-activity-chevron`);let g=t.querySelector(`:scope > .persona-border-t`);return g?.classList.add(`persona-activity-body`),g&&(g.id=`activity-details-${n.id}`,a.setAttribute(`aria-controls`,g.id)),t}function yn(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{clearTimeout(i.get(e)),i.delete(e)};return{observe(a,o,s,c={}){let l=o===`tool`?a.toolCall:a.reasoning;if(l&&!n.has(a.id)&&(!t.has(a.id)&&l.status!==`complete`&&l.chunks?.some(Boolean)&&(t.add(a.id),c.autoExpand!==!1&&s.add(a.id)),t.has(a.id)&&l.status===`complete`&&!r.has(a.id))){if(r.add(a.id),c.autoCollapseDelay===!1)return;i.set(a.id,setTimeout(()=>{i.delete(a.id),s.delete(a.id),e(a.id,o)},c.autoCollapseDelay??1e3))}},manual(e){n.add(e),a(e)},prune(e){for(let i of/* @__PURE__ */ new Set([...t,...n,...r]))e.has(i)||(a(i),t.delete(i),n.delete(i),r.delete(i))},clear(){for(let e of i.keys())a(e);t.clear(),n.clear(),r.clear()}}}function bn(e,t,n,r){let i=j(`div`,``);i.id=`bubble-${e.id}`,i.dataset.messageId=e.id;let a=j(`button`,``);a.type=`button`,a.dataset.expandHeader=`true`,a.dataset.bubbleType=`tool`,a.setAttribute(`aria-expanded`,String(n));let o=j(`div`,``);typeof r==`string`?o.textContent=r:o.appendChild(r),dn(a,o,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||`currentColor`,metaGap:!0});let s=j(`div`,`persona-border-t`);return s.id=`activity-details-${e.id}`,s.style.display=n?``:`none`,a.setAttribute(`aria-controls`,s.id),i.append(a,s),vn(i,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:`row`}}},`tool`),i.dataset.personaToolGroup=`true`,t.features?.toolCallDisplay?.loadingAnimation===`shimmer`&&(i.dataset.activityGroupShimmer=`true`),{bubble:i,body:s}}function xn(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Sn(e){return e?.type===`runtype`||e?.type===`custom`}const F=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function I(e){try{if(e?.type===`custom`&&e.custom){let t=e.custom,n=typeof t==`function`?t():t;return!!n&&typeof n.startListening==`function`}return e?.type===`runtype`&&e.runtype?!0:F()}catch{return!1}}const Cn=/^\s*\|?[\s:|-]*-[\s:|-]*$/,L=e=>e.includes(`|`),R=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},z=e=>`| ${e.join(` | `)} |`,B=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,wn=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),Tn=e=>{if(!e||!e.includes(`|`))return e;let t=e.split(`
|
|
2
|
-
`),n=!1;for(let e=0;e<t.length-1;e++){let r=t[e],i=t[e+1];if(!
|
|
3
|
-
`):e},En=`var(--persona-md-table-scroll-fade, 24px)`,V=/* @__PURE__ */ new WeakSet;function Dn(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(`persona-table-scroll`))return;let t=document.createElement(`div`);t.className=`persona-table-scroll`,e.replaceWith(t),t.appendChild(e)})}function H(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute(`data-persona-scroll-x`);return}e.setAttribute(`data-persona-scroll-x`,``);let n=getComputedStyle(e).direction===`rtl`?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty(`--persona-fade-l`,n<=1?`0px`:En),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:En)}function On(e){V.has(e)||(V.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&H(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(H)}const{setLoader:kn,load:U,provide:An,getSync:jn}=me({fallbackImport:()=>import(`./chunk-DbhxjyOB.js`)}),Mn=U,Nn=jn,{setLoader:Pn,load:Fn}=me({fallbackImport:()=>import(`./chunk-HUOUif-P.js`)}),In=Fn;function W(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function Ln(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=W(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=W(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw 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 Rn(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function zn(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Bn(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}const G=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),Vn=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Hn=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=G(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:Vn(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},Un=(e,t)=>{let n=[],r=[],i=[],a=``,o,s=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let c of e){let e=Hn(c);if(e){let t=c.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&s(),r.length===0&&(a=c.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let l=t(c);l&&(s(),n.push(l))}return s(),n},{setLoader:Wn,load:Gn,provide:K}=me({fallbackImport:()=>import(`./chunk-DrYAfpvk.js`)}),Kn=Gn;var qn=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const Jn=e=>`reason`in e?e.reason:void 0,Yn=(e,t)=>e instanceof qn&&e.code===t,Xn=e=>!e.voiceCaption&&!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),Zn=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),Qn=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function $n(e){switch(e){case`json`:return Be;case`regex-json`:return ke;case`xml`:return Re;default:return Fe}}var er=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#l=null,this.clientSession=null,this.#u=null,this.#d=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null,this.#p=!1,this.#m=!1,this.#h=!1,this.#g=null,this.#_=/* @__PURE__ */ new Set,this.#v=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#y=null,this.#H=null,this.#W=null,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":N,...e.headers},this.debug=!!e.debug,this.#n=e.streamParser??$n(e.parserType),this.#r=e.contextProviders??[],this.#i=e.requestMiddleware,this.#a=e.customFetch,this.#o=e.parseSSEEvent,this.#s=e.getHeaders,e.webmcp?.enabled===!0&&(this.#y=this.#x(e.webmcp))}#x(e){return In().then(t=>{let n=new t.WebMcpBridge(e,{recordToolDisplayTitles:Ae,getToolDisplayTitle:Oe,loadPolyfill:Ge});return this.#b!==void 0&&n.setConfirmHandler(this.#b),this.webMcpBridge=n,n}).catch(e=>(this.#y=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#S(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled===!0?(this.#y||=this.#x(this.config.webmcp),this.#y):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#b=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,t,n){return this.config.webmcp?.enabled===!0?this.#S().then(r=>r?r.executeToolCall(e,t,n):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.config;if(!n)return{agentId:e,flowId:t};let i=Ln(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#w(){return this.config.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#T(e){return`${this.#w()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new qn(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#w()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":N,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await Kn();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await Kn()).historyErrorFor(this.#G(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#u||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#d===e?null:(this.#d=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#u)return this.#u;let e=this.#u=this.#N().then(t=>this.#u===e?(this.clientSession=t,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#u===e&&(this.#u=null)});return e}#E(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#p}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#D(){if(!this.#p){this.#j({state:`unavailable`,reason:`history_disabled`}),this.#p=!0,!this.#m&&typeof console<`u`&&(this.#m=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#v])e(!1)}}getHistoryIdentityStatus(){return this.#g??this.#O()}subscribeHistoryIdentityStatus(e){return this.#_.add(e),()=>{this.#_.delete(e)}}subscribeHistoryAvailability(e){return this.#v.add(e),this.#p&&e(!1),()=>{this.#v.delete(e)}}#O(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#p?{state:`unavailable`,reason:`history_disabled`}:this.#k():{state:`unavailable`,reason:`ineligible_mode`}}#k(){let e=this.#g;return e?.state===`browser_only`?e:this.#A()}#A(){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`}}#j(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&Jn(t)===Jn(e);if(this.#g=e,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#_])t(e)}}async#M(e){let t=this.#E()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let i=this.#C(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.#T(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":N},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.#D(),o)throw new qn(`history_disabled`,`Visitor history is disabled for this surface`);return this.#M({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new qn(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new qn(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new qn(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async#N(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#E()&&!t)return this.#P(e,!1);let n=await this.readVisitorToken();if(e&&n)try{let n=await this.#M({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#R(n,e,!1)}catch(n){if(!Yn(n,`not_found`)&&!Yn(n,`visitor_required`)&&!Yn(n,`history_disabled`))throw n;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#P(e,!0)}return this.#P(e,!1)}async#P(e,t){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let n=this.config.getStoredSessionId?.()||null,r=await this.#M({storedSessionId:n}),i=await this.#L(r);return this.#R(i,e,t)}async#I(e){let t=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.#M({storedSessionId:t,identityProof:e}),i=this.#R(r,n,!1);return this.clientSession=i,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint(),i}async#L(e){if(!e.visitor?.token||this.#h||!this.#E()&&e.durableRecovery?.enabled!==!0)return e;this.#h=!0;try{return await this.#M({storedSessionId:e.sessionId})}catch{return e}finally{this.#h=!1}}#R(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#z(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#d=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#E())throw new qn(`history_disabled`,`Visitor history is disabled for this surface`);await this.historyInternals.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new qn(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#M({conversationId:e,identityProof:n});return this.#z(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.historyInternals.historyBootstrapReady;let e=await this.#M({});return this.#z(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#E()&&this.#j(this.#A())}clearClientSession(){this.clientSession=null,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null}#B(){return`${this.#w()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},n=await fetch(this.#B(),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":N},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.clientSession=null,this.#d=!1,this.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#V(e){e?.throwIfAborted();let t=this.config.identityProvider;if(t===void 0)return;let n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#H;#U(){let e=this;return this.#H??={get config(){return e.config},headers:this.#t,getHeaders:this.#s,debug:this.debug,clientApiBase:()=>e.#w(),getClientApiUrl:t=>e.#T(t),getWebMcpBridge:()=>e.#S(),sendWithClientToolsDiff:(t,n,r,i)=>e.#Y(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#W;#G(){let e=this;return this.#W??={HistoryClientError:qn,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#w(),setHistoryIdentityStatus:t=>e.#j(t),browserOnlyStatus:()=>e.#k(),derivedBrowserOnly:()=>e.#A(),reinitWithProof:t=>e.#I(t),isHistoryCapable:()=>e.#E(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await Kn()).listConversations(this.#G(),e)}async getConversation(e,t){return(await Kn()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await Kn()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await Kn()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await Kn()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await Kn()).resetVisitor(this.#G())}async dispatch(e,t){return e.signal?.throwIfAborted(),Mn().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#q(e,t)}async#K(e,t){let n=Bn();this.#l=n;let r=()=>this.#l===n,i=e=>{r()&&t(e)};t({type:`status`,status:`connecting`});try{let t=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException(`Turn superseded`,`AbortError`)},a=this.clientSession??await this.initSession();t();let o=async()=>{t();let n=a,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.#M({...r||this.#E()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);a=this.#R(i,n.conversationId??null,!1),this.clientSession=a,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await o();let s=await this.#te(e.messages),c=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,l=this.#E(),u={sessionId:a.sessionId,messages:e.messages.filter(Xn).map(e=>{let t=l?dt(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0}}},d=async()=>{t();let n=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return t(),this.#Y(a.sessionId,s.clientTools,async r=>{t();let i=await this.#V(e.signal);t();let o={...u,sessionId:a.sessionId,...r,...i&&{identityProof:i}};return this.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.#T(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":N,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},f=await d();if(t(),f.response.status===401){let e=await f.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await o(),f=await d(),t())}let{response:p,commit:m}=f;if(!p.ok){let e=await p.json().catch(()=>({error:`Chat request failed`}));if(p.status===401&&e.error===`invalid_identity_proof`){let e=new qn(`invalid_identity_proof`,`The identity proof was rejected`);throw i({type:`error`,error:e}),e}if(p.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw i({type:`error`,error:e}),e}if(p.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw i({type:`error`,error:t}),t}if(p.status===410&&e.error===`conversation_deleted`){let e=new qn(`conversation_deleted`,`This conversation was deleted`);throw i({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw i({type:`error`,error:t}),t}if(!p.body){let e=/* @__PURE__ */ Error(`No response body received`);throw i({type:`error`,error:e}),e}m(),i({type:`status`,status:`connected`});try{await this.#ne(p.body,i,e.assistantMessageId)}finally{i({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof qn)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&i({type:`error`,error:t}),t}}async#q(e,t){t({type:`status`,status:`connecting`});let n=await this.#te(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t)}finally{t({type:`status`,status:`idle`})}}async#J(e,t){t({type:`status`,status:`connecting`});let n=await this.#ee(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t,e.assistantMessageId)}finally{t({type:`status`,status:`idle`})}}async processStream(e,t,n,r){t({type:`status`,status:`connected`});try{await this.#ne(e,t,n,r)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t){return(await Mn()).resolveApproval(this.#U(),e,t)}async#Y(e,t,n,r){let i=!!(t&&t.length>0),a=i?Pe(t):void 0,o=this.clientToolsFingerprintSessionId===e,s=i&&o&&this.lastSentClientToolsFingerprint===a,c=!i&&r?.emptyMeansReplace===!0&&this.#f===e,l=!1,u;for(let e=0;u=await n({...i&&(l||!s)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&e===0&&i&&(await u.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)l=!0,this.lastSentClientToolsFingerprint=null;return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,i?this.#f=e:c&&(this.#f=null)}}}async resumeFlow(e,t,n){return(await Mn()).resumeFlow(this.#U(),e,t,n)}#X(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#Z(e){let t={};this.#r.length&&await Promise.all(this.#r.map(async n=>{try{let r=await n({messages:e,config:this.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#X(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#Q(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#$(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#ee(e,t){let n=this.#C().agentId;if(!this.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=Un(Zn(e),e=>Xn(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?Qn(e):null),i=this.#Q(t),a={agent:this.#$(this.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.config.agentOptions}};i&&(a.composerOptions=i);let o=[...$e(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#Z(e);return s&&(a.context=s),a}async#te(e,t){let n=Un(Zn(e),e=>Xn(e)?Qn(e):null),r=this.#C(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...$e(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#Z(e);o&&(i.context=o);let s=this.#Q(t);if(s&&(i.composerOptions=s),this.#i)try{let e=await this.#i({payload:{...i},config:this.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}async#ne(e,t,n,r){let{streamResponse:i}=Nn()??await Mn();return i({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#o,onSSEEvent:(e,t)=>this.#c?.(e,t)},e,t,n,r)}};const{setLoader:tr,load:nr,provide:rr,getSync:ir}=me({fallbackImport:()=>import(`./chunk-U_UTkSiO.js`)}),ar=nr,or=ir,{setLoader:sr,load:cr,provide:lr,getSync:ur}=me({fallbackImport:()=>import(`./chunk-DsdqLStH.js`)}),dr=cr,fr=ur,pr=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function mr(e){let t=e?.text?.trim()??``;return t?yt(pr(e),t):``}function hr(e){let t=mr(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[it(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
1
|
+
import{_ as e,a as t,b as n,c as r,d as i,f as a,g as o,i as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h,v as g,y as _}from"./chunk-DtmtfIkd.js";import{n as v,r as y}from"./chunk-D5B629Mj.js";import{t as b}from"./chunk-BtTP1Wgi.js";import{B as x,C as S,D as C,E as w,F as T,H as E,L as D,M as ee,N as te,O as ne,P as re,R as ie,S as ae,T as oe,U as se,V as O,W as ce,_ as le,a as ue,b as de,c as fe,d as k,f as pe,g as me,h as he,i as ge,j as _e,k as ve,l as ye,m as A,n as be,o as xe,p as Se,r as Ce,s as we,t as Te,u as Ee,v as De,w as Oe,x as ke,y as Ae,z as je}from"./chunk-BIhTjsVQ.js";import{i as Me,r as j,t as M}from"./chunk-D5BxWOFB.js";import{a as Ne,n as N,r as Pe,t as Fe}from"./chunk-BypiAEpx.js";import{c as Ie,d as Le,f as Re,i as ze,l as Be,m as Ve,n as He,p as Ue,r as We,t as Ge,u as Ke}from"./chunk-SE7Q9NmG.js";import{n as qe,r as Je,t as Ye}from"./chunk-BvhTpG6k.js";import{f as Xe,r as Ze,s as Qe,u as $e}from"./chunk-CD4-AYdH.js";import{a as et,i as tt,r as nt}from"./chunk-CfNME4R9.js";import{a as P,i as rt,n as it,r as F,t as at}from"./chunk-CPdEltCR.js";import{t as ot}from"./chunk-Csks3Qw1.js";import{a as st,c as ct,d as lt,l as ut,n as dt,o as ft,t as pt,u as mt}from"./chunk-BlTD-Wgn.js";import{a as ht,n as gt,r as _t,s as vt,t as yt}from"./chunk-DpyghsEW.js";import{n as bt}from"./chunk-DTDHeUsG.js";import{i as xt,n as St}from"./chunk-Bb41bKyp.js";import{t as Ct}from"./chunk-C8560fIY.js";import{i as wt,n as Tt,r as Et,t as Dt}from"./chunk-lwPt6bL9.js";import{t as Ot}from"./chunk-CQw6A6rt.js";import{n as kt}from"./chunk-py2YB6PV.js";import{a as At,c as jt,i as Mt,l as Nt,n as Pt,o as Ft,r as It,s as Lt,t as Rt}from"./chunk-CVMIncEY.js";import{a as zt,c as Bt,i as Vt,l as Ht,n as Ut,o as Wt,r as Gt,s as Kt,t as qt,u as Jt}from"./chunk-BExOAPZb.js";import{Activity as Yt,ArrowRight as Xt,Check as Zt,ChevronDown as Qt,ChevronUp as $t,Circle as en,Clock as tn,Copy as nn,File as rn,FileCode as an,FileSpreadsheet as on,FileText as sn,MessageSquare as cn,X as ln}from"lucide";import"partial-json";import{Idiomorph as un}from"idiomorph";const dn=[`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`],fn=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),pn=(e,t)=>{let n=M(`div`,[`persona-message-bubble`,e,...dn].join(` `));return n.id=`bubble-${t}`,n.setAttribute(`data-message-id`,t),n},mn=e=>{let t=M(`button`,e.expandable?`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`:`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`);return t.type=`button`,e.expandable&&(t.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),t.setAttribute(`data-expand-header`,`true`)),t.setAttribute(`data-bubble-type`,e.bubbleType),t},hn=(e,t,n)=>{e.innerHTML=``;let r=b(t?$t:Qt,16,n,2);r?e.appendChild(r):e.textContent=t?`Hide`:`Show`},gn=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let r=M(`div`,`persona-flex persona-items-center`);hn(r,n.expanded,n.iconColor);let i=M(`div`,n.metaGap?`persona-flex persona-items-center persona-gap-2 persona-ml-auto`:`persona-flex persona-items-center persona-ml-auto`);return i.append(r),e.append(t,i),r},_n=e=>{let t=M(`div`,`persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted`);if(t.setAttribute(`data-persona-collapsed-preview`,e.previewKind),t.style.display=`none`,t.style.whiteSpace=`pre-wrap`,!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();fn(t,n)||(t.textContent=e.previewText),t.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},I=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&hn(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?``:`none`,e.collapsedPreview.style.display=e.expanded?`none`:e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?``:`none`},L=(e,t,n)=>{let r=n.stateSet.has(e),i=t.querySelector(`button[data-expand-header="true"]`),a=t.querySelector(`.persona-border-t`),o=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!i||!a)return;i.setAttribute(`aria-expanded`,r?`true`:`false`);let s=i.querySelector(`.persona-ml-auto`)?.querySelector(`:scope > .persona-flex.persona-items-center`);s&&hn(s,r,n.iconColor),a.style.display=r?``:`none`,o&&(o.style.display=r?`none`:o.textContent||o.childNodes.length?``:`none`)};function vn(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[n]:{...t===`tool`?ee:_e,...e?.future?.v5Defaults===!0?ne.features?.[n]:{},...e?.features?.[n]}}}}function yn(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[n]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function bn(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?`a moment`:t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function R(e,t,n,r){if(yn(n,r)!==`row`)return e;e.className=`persona-message-bubble persona-${r}-bubble persona-activity-row`,e.dataset.activityKind=r,r===`tool`&&n.toolCall?.shadow===void 0&&(e.style.boxShadow=`var(--persona-tool-bubble-shadow, none)`);let i=e.querySelector(`:scope > button`);if(!i)return e;i.className=`persona-activity-header`;let a=r===`tool`?t.toolCall:t.reasoning,o=a?.status!==`complete`,s=t.approval?.status??t.toolCall?.approvalStatus,c=t.toolCall?.interrupted?`interrupted`:s===`denied`?`denied`:s===`pending`?`awaiting-approval`:t.toolCall?.success===!1?`error`:o?a?.status===`pending`?`pending`:`running`:`done`;e.dataset.activityState=c;let l=M(`span`,`persona-activity-icon`);l.dataset.activityIcon=c;let u={pending:`circle`,running:`loader-circle`,done:`check`,error:`x`,denied:`x`,interrupted:`x`,"awaiting-approval":`clock`},d=r===`reasoning`?n.features?.reasoningDisplay?.iconName:void 0,f=d?N(d,16,`currentColor`,2):c===`pending`?b(en,16,`currentColor`,2):c===`awaiting-approval`?b(tn,16,`currentColor`,2):N(u[c],16,`currentColor`,2);f&&l.appendChild(f),i.querySelector(`.persona-reasoning-header-icon`)?.remove();let p=r===`tool`?`toolCallDisplay`:`reasoningDisplay`,m=n.features?.[p]?.iconVisibility??(n.future?.v5Defaults?`active`:`always`);if((m===`always`||m===`active`&&c!==`done`)&&i.prepend(l),r===`tool`&&a){let e=M(`span`,`persona-activity-duration`);o&&a.startedAt&&e.setAttribute(`data-tool-elapsed`,String(a.startedAt));let n=(r===`tool`?t.toolCall?.duration:void 0)??a.durationMs??(a.completedAt!==void 0&&a.startedAt!==void 0?a.completedAt-a.startedAt:void 0);e.textContent=n===void 0?``:bn(n),i.appendChild(e)}i.querySelector(`:scope > div:not(.persona-ml-auto)`)?.classList.add(`persona-activity-label`),i.querySelector(`.persona-ml-auto`)?.classList.add(`persona-activity-chevron`);let h=e.querySelector(`:scope > .persona-border-t`);return h?.classList.add(`persona-activity-body`),h&&(h.id=`activity-details-${t.id}`,i.setAttribute(`aria-controls`,h.id)),e}function xn(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{clearTimeout(i.get(e)),i.delete(e)};return{observe(a,o,s,c={}){let l=o===`tool`?a.toolCall:a.reasoning;if(l&&!n.has(a.id)&&(!t.has(a.id)&&l.status!==`complete`&&l.chunks?.some(Boolean)&&(t.add(a.id),c.autoExpand!==!1&&s.add(a.id)),t.has(a.id)&&l.status===`complete`&&!r.has(a.id))){if(r.add(a.id),c.autoCollapseDelay===!1)return;i.set(a.id,setTimeout(()=>{i.delete(a.id),s.delete(a.id),e(a.id,o)},c.autoCollapseDelay??1e3))}},manual(e){n.add(e),a(e)},prune(e){for(let i of/* @__PURE__ */ new Set([...t,...n,...r]))e.has(i)||(a(i),t.delete(i),n.delete(i),r.delete(i))},clear(){for(let e of i.keys())a(e);t.clear(),n.clear(),r.clear()}}}function Sn(e,t,n,r){let i=M(`div`,``);i.id=`bubble-${e.id}`,i.dataset.messageId=e.id;let a=M(`button`,``);a.type=`button`,a.dataset.expandHeader=`true`,a.dataset.bubbleType=`tool`,a.setAttribute(`aria-expanded`,String(n));let o=M(`div`,``);typeof r==`string`?o.textContent=r:o.appendChild(r),gn(a,o,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||`currentColor`,metaGap:!0});let s=M(`div`,`persona-border-t`);return s.id=`activity-details-${e.id}`,s.style.display=n?``:`none`,a.setAttribute(`aria-controls`,s.id),i.append(a,s),R(i,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:`row`}}},`tool`),i.dataset.personaToolGroup=`true`,t.features?.toolCallDisplay?.loadingAnimation===`shimmer`&&(i.dataset.activityGroupShimmer=`true`),{bubble:i,body:s}}function z(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Cn(e){return e?.type===`runtype`||e?.type===`custom`}const B=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function V(e){try{if(e?.type===`custom`&&e.custom){let t=e.custom,n=typeof t==`function`?t():t;return!!n&&typeof n.startListening==`function`}return e?.type===`runtype`&&e.runtype?!0:B()}catch{return!1}}const wn=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Tn=e=>e.includes(`|`),En=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},H=e=>`| ${e.join(` | `)} |`,U=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,Dn=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),W=e=>{if(!e||!e.includes(`|`))return e;let t=e.split(`
|
|
2
|
+
`),n=!1;for(let e=0;e<t.length-1;e++){let r=t[e],i=t[e+1];if(!Tn(r)||wn.test(r)||!wn.test(i))continue;let a=En(r).length;if(a<1)continue;let o=U(a);t[e+1]!==o&&(t[e+1]=o,n=!0);let s=e+2;for(;s<t.length;s++){let e=t[s];if(e.trim()===``||!Tn(e))break;let r=H(Dn(En(e),a));t[s]!==r&&(t[s]=r,n=!0)}e=s-1}return n?t.join(`
|
|
3
|
+
`):e},On=`var(--persona-md-table-scroll-fade, 24px)`,kn=/* @__PURE__ */ new WeakSet;function An(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(`persona-table-scroll`))return;let t=document.createElement(`div`);t.className=`persona-table-scroll`,e.replaceWith(t),t.appendChild(e)})}function jn(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute(`data-persona-scroll-x`);return}e.setAttribute(`data-persona-scroll-x`,``);let n=getComputedStyle(e).direction===`rtl`?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty(`--persona-fade-l`,n<=1?`0px`:On),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:On)}function Mn(e){kn.has(e)||(kn.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&jn(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(jn)}const{setLoader:Nn,load:Pn,provide:Fn,getSync:G}=Ne({fallbackImport:()=>import(`./chunk-B1-_pp-Y.js`)}),In=Pn,Ln=G,{setLoader:Rn,load:zn}=Ne({fallbackImport:()=>import(`./chunk-BkW8s3fj.js`)}),Bn=zn,{setLoader:K,load:Vn}=Ne({fallbackImport:()=>import(`./chunk-lA5CJCgK.js`)}),Hn=Vn;function Un(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function Wn(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=Un(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=Un(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw 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.`)}const Gn=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),q=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Kn=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=Gn(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:q(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},qn=(e,t)=>{let n=[],r=[],i=[],a=``,o,s=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let c of e){let e=Kn(c);if(e){let t=c.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&s(),r.length===0&&(a=c.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let l=t(c);l&&(s(),n.push(l))}return s(),n},{setLoader:Jn,load:Yn,provide:Xn}=Ne({fallbackImport:()=>import(`./chunk-BcLIgi1h.js`)}),Zn=Yn;var Qn=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const $n=e=>`reason`in e?e.reason:void 0,er=(e,t)=>e instanceof Qn&&e.code===t,tr=e=>e.voiceCaption||bt(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),nr=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),rr=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function ir(e){switch(e){case`json`:return f;case`regex-json`:return t;case`xml`:return u;default:return s}}var ar=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#l=null,this.clientSession=null,this.#u=null,this.#d=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null,this.#p=!1,this.#m=!1,this.#h=!1,this.#g=null,this.#_=/* @__PURE__ */ new Set,this.#v=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#y=null,this.#H=null,this.#W=null,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":ot,...e.headers},this.debug=!!e.debug,this.#n=e.streamParser??ir(e.parserType),this.#r=e.contextProviders??[],this.#i=e.requestMiddleware,this.#a=e.customFetch,this.#o=e.parseSSEEvent,this.#s=e.getHeaders,e.webmcp?.enabled===!0&&(this.#y=this.#x(e.webmcp))}#x(t){return Bn().then(r=>{let i=new r.WebMcpBridge(t,{recordToolDisplayTitles:n,getToolDisplayTitle:e,loadPolyfill:_});return this.#b!==void 0&&i.setConfirmHandler(this.#b),this.webMcpBridge=i,i}).catch(e=>(this.#y=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#S(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled===!0?(this.#y||=this.#x(this.config.webmcp),this.#y):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#b=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}getVoiceClientTools(){if(this.config.webmcp?.enabled!==!0)return null;let e=()=>this.#S(),t={open:async e=>(await Hn()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:o(t)}},onChange:t=>{let n=null,r=!1;return e().then(e=>{e&&!r&&(n=e.watchToolChanges(t))}),()=>{r=!0,n?.()}},execute:async(t,n,r)=>{let i=await e();return i?i.executeVoiceToolCall(t,n,r):{status:`failed`,error:{message:`WebMCP runtime failed to load.`}}}};return t}executeWebMcpToolCall(e,t,n){return this.config.webmcp?.enabled===!0?this.#S().then(r=>r?r.executeToolCall(e,t,n):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.config;if(!n)return{agentId:e,flowId:t};let i=Wn(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#w(){return this.config.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#T(e){return`${this.#w()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new Qn(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#w()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":ot,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await Zn();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await Zn()).historyErrorFor(this.#G(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#u||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#d===e?null:(this.#d=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#u)return this.#u;let e=this.#u=this.#N().then(t=>this.#u===e?(this.clientSession=t,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#u===e&&(this.#u=null)});return e}#E(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#p}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#D(){if(!this.#p){this.#j({state:`unavailable`,reason:`history_disabled`}),this.#p=!0,!this.#m&&typeof console<`u`&&(this.#m=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#v])e(!1)}}getHistoryIdentityStatus(){return this.#g??this.#O()}subscribeHistoryIdentityStatus(e){return this.#_.add(e),()=>{this.#_.delete(e)}}subscribeHistoryAvailability(e){return this.#v.add(e),this.#p&&e(!1),()=>{this.#v.delete(e)}}#O(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#p?{state:`unavailable`,reason:`history_disabled`}:this.#k():{state:`unavailable`,reason:`ineligible_mode`}}#k(){let e=this.#g;return e?.state===`browser_only`?e:this.#A()}#A(){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`}}#j(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&$n(t)===$n(e);if(this.#g=e,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#_])t(e)}}async#M(e){let t=this.#E()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let i=this.#C(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.#T(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":ot},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.#D(),o)throw new Qn(`history_disabled`,`Visitor history is disabled for this surface`);return this.#M({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new Qn(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new Qn(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new Qn(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async#N(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#E()&&!t)return this.#P(e,!1);let n=await this.readVisitorToken();if(e&&n)try{let n=await this.#M({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#R(n,e,!1)}catch(n){if(!er(n,`not_found`)&&!er(n,`visitor_required`)&&!er(n,`history_disabled`))throw n;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#P(e,!0)}return this.#P(e,!1)}async#P(e,t){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let n=this.config.getStoredSessionId?.()||null,r=await this.#M({storedSessionId:n}),i=await this.#L(r);return this.#R(i,e,t)}async#I(e){let t=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.#M({storedSessionId:t,identityProof:e}),i=this.#R(r,n,!1);return this.clientSession=i,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint(),i}async#L(e){if(!e.visitor?.token||this.#h||!this.#E()&&e.durableRecovery?.enabled!==!0)return e;this.#h=!0;try{return await this.#M({storedSessionId:e.sessionId})}catch{return e}finally{this.#h=!1}}#R(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#z(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#d=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#E())throw new Qn(`history_disabled`,`Visitor history is disabled for this surface`);await this.historyInternals.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new Qn(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#M({conversationId:e,identityProof:n});return this.#z(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.historyInternals.historyBootstrapReady;let e=await this.#M({});return this.#z(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#E()&&this.#j(this.#A())}clearClientSession(){this.clientSession=null,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null}#B(){return`${this.#w()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},n=await fetch(this.#B(),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":ot},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.clientSession=null,this.#d=!1,this.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#V(e){e?.throwIfAborted();let t=this.config.identityProvider;if(t===void 0)return;let n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#H;#U(){let e=this;return this.#H??={get config(){return e.config},headers:this.#t,getHeaders:this.#s,debug:this.debug,clientApiBase:()=>e.#w(),getClientApiUrl:t=>e.#T(t),getWebMcpBridge:()=>e.#S(),sendWithClientToolsDiff:(t,n,r,i)=>e.#Y(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#W;#G(){let e=this;return this.#W??={HistoryClientError:Qn,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#w(),setHistoryIdentityStatus:t=>e.#j(t),browserOnlyStatus:()=>e.#k(),derivedBrowserOnly:()=>e.#A(),reinitWithProof:t=>e.#I(t),isHistoryCapable:()=>e.#E(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await Zn()).listConversations(this.#G(),e)}async getConversation(e,t){return(await Zn()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await Zn()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await Zn()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await Zn()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await Zn()).resetVisitor(this.#G())}async dispatch(e,t){return e.signal?.throwIfAborted(),In().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#q(e,t)}async#K(e,t){let n=qe();this.#l=n;let r=()=>this.#l===n,i=e=>{r()&&t(e)};t({type:`status`,status:`connecting`});try{let t=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException(`Turn superseded`,`AbortError`)},a=this.clientSession??await this.initSession();t();let o=async()=>{t();let n=a,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.#M({...r||this.#E()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);a=this.#R(i,n.conversationId??null,!1),this.clientSession=a,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await o();let s=await this.#te(e.messages),c=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,l=this.#E(),u={sessionId:a.sessionId,messages:e.messages.filter(tr).map(e=>{let t=l?ht(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},d=async()=>{t();let n=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return t(),this.#Y(a.sessionId,s.clientTools,async r=>{t();let i=await this.#V(e.signal);t();let o={...u,sessionId:a.sessionId,...r,...i&&{identityProof:i}};return this.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.#T(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":ot,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},f=await d();if(t(),f.response.status===401){let e=await f.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await o(),f=await d(),t())}let{response:p,commit:m}=f;if(!p.ok){let e=await p.json().catch(()=>({error:`Chat request failed`}));if(p.status===401&&e.error===`invalid_identity_proof`){let e=new Qn(`invalid_identity_proof`,`The identity proof was rejected`);throw i({type:`error`,error:e}),e}if(p.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw i({type:`error`,error:e}),e}if(p.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw i({type:`error`,error:t}),t}if(p.status===410&&e.error===`conversation_deleted`){let e=new Qn(`conversation_deleted`,`This conversation was deleted`);throw i({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw i({type:`error`,error:t}),t}if(!p.body){let e=/* @__PURE__ */ Error(`No response body received`);throw i({type:`error`,error:e}),e}m(),i({type:`status`,status:`connected`});try{await this.#ne(p.body,i,e.assistantMessageId)}finally{i({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof Qn)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&i({type:`error`,error:t}),t}}async#q(e,t){t({type:`status`,status:`connecting`});let n=await this.#te(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t)}finally{t({type:`status`,status:`idle`})}}async#J(e,t){t({type:`status`,status:`connecting`});let n=await this.#ee(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t,e.assistantMessageId)}finally{t({type:`status`,status:`idle`})}}async processStream(e,t,n,r){t({type:`status`,status:`connected`});try{await this.#ne(e,t,n,r)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t,n){return(await In()).resolveApproval(this.#U(),e,t,n)}async#Y(e,t,n,r){let i=!!(t&&t.length>0),a=i?o(t):void 0,s=this.clientToolsFingerprintSessionId===e,c=i&&s&&this.lastSentClientToolsFingerprint===a,l=!i&&r?.emptyMeansReplace===!0&&this.#f===e,u=!1,d;for(let e=0;d=await n({...i&&(u||!c)&&t?{clientTools:t}:{},...l?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),d.status===409&&e===0&&i&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,i?this.#f=e:l&&(this.#f=null)}}}async resumeFlow(e,t,n){return(await In()).resumeFlow(this.#U(),e,t,n)}#X(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#Z(e){let t={};this.#r.length&&await Promise.all(this.#r.map(async n=>{try{let r=await n({messages:e,config:this.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#X(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#Q(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#$(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#ee(e,t){let n=this.#C().agentId;if(!this.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=qn(nr(e),e=>tr(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?rr(e):null),i=this.#Q(t),a={agent:this.#$(this.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.config.agentOptions}};i&&(a.composerOptions=i);let o=[...P(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#Z(e);return s&&(a.context=s),a}async#te(e,t){let n=qn(nr(e),e=>tr(e)?rr(e):null),r=this.#C(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...P(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#Z(e);o&&(i.context=o);let s=this.#Q(t);if(s&&(i.composerOptions=s),this.#i)try{let e=await this.#i({payload:{...i},config:this.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}async#ne(e,t,n,r){let{streamResponse:i}=Ln()??await In();return i({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#o,onSSEEvent:(e,t)=>this.#c?.(e,t)},e,t,n,r)}};const{setLoader:or,load:sr,provide:cr,getSync:lr}=Ne({fallbackImport:()=>import(`./chunk-U_UTkSiO.js`)}),ur=sr,dr=lr,{setLoader:fr,load:pr,provide:mr,getSync:hr}=Ne({fallbackImport:()=>import(`./chunk-DjFpGFGA.js`)}),gr=pr,_r=hr,vr=e=>typeof e==`object`&&!!e&&!Array.isArray(e),yr=(e,t)=>{let n=/* @__PURE__ */ new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!vr(e))return[];let{toolCallId:r,name:i}=e;if(typeof r!=`string`||!r||typeof i!=`string`||!i||n.has(r))return[];n.add(r);let a=vr(e.arguments)?e.arguments:{},o=e.result??null;return[{id:`voice-tool-${r}`,role:`assistant`,variant:`tool`,content:``,createdAt:t,streaming:!1,toolCall:{id:r,name:i,status:`complete`,args:a,result:o},agentMetadata:{clientToolAnswer:{toolCallId:r,toolName:i,args:a,result:o}}}]})},br=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function xr(e){let t=e?.text?.trim()??``;return t?wt(br(e),t):``}function Sr(e){let t=xr(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[st(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
4
4
|
|
|
5
|
-
`)}:{}}function
|
|
5
|
+
`)}:{}}function Cr(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function wr(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1||e[n].role!==`user`)return null;let r=n+1;for(;r<e.length&&e[r].role!==`user`;)r+=1;return{start:n,end:r}}function Tr(e,t){let n=e.findIndex(e=>e.id===t);if(n<=0)return null;for(let t=n-1;t>=0;--t)if(e[t].role===`user`)return e[t].id;return null}function Er(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`||n.streaming)return null;if(!(n.role!==`assistant`||n.variant))return Tr(e,n.id)?n.id:null}return null}function Dr(e){return e.role!==`user`||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content==`string`&&e.content.length>0}function Or(e){for(let t of[`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)`]){let n=e.find(e=>e.name===t);if(n)return n}return e.find(e=>e.lang.startsWith(`en`))??e[0]}var kr=class e{constructor(e={}){this.options=e,this.id=`browser`,this.supportsPause=!0}static isSupported(){return typeof window<`u`&&`speechSynthesis`in window}speak(t,n){if(!e.isSupported()){n.onError?.(/* @__PURE__ */ Error(`Web Speech API is unavailable`));return}let r=window.speechSynthesis;r.cancel();let i=new SpeechSynthesisUtterance(t.text),a=r.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(i.voice=e)}else a.length>0&&(i.voice=this.options.pickVoice?this.options.pickVoice(a):Or(a));t.rate!==void 0&&(i.rate=t.rate),t.pitch!==void 0&&(i.pitch=t.pitch),i.onend=()=>n.onEnd?.(),i.onerror=e=>{let t=e.error;t===`canceled`||t===`interrupted`?n.onEnd?.():n.onError?.(Error(t||`Speech synthesis failed`))},setTimeout(()=>{r.speak(i),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},Ar=class{#e=null;#t=null;#n=`idle`;#r=/* @__PURE__ */ new Set;#i=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#n:`idle`}activeMessageId(){return this.#t}onChange(e){return this.#r.add(e),()=>this.#r.delete(e)}toggle(e,t){if(this.#t===e){if(this.#n===`playing`){this.#e?.supportsPause?(this.#e.pause(),this.#o(e,`paused`)):this.stop();return}if(this.#n===`paused`){this.#e?.resume(),this.#o(e,`playing`);return}if(this.#n===`loading`){this.stop();return}}this.play(e,t)}async play(e,t){let n=++this.#i;this.#e?.stop(),this.#o(e,`loading`);try{if(!this.#e){let e=await this.#a();if(n!==this.#i)return;if(!e){this.#o(null,`idle`);return}this.#e=e}this.#e.speak(t,{onStart:()=>{n===this.#i&&this.#o(e,`playing`)},onEnd:()=>{n===this.#i&&this.#o(null,`idle`)},onError:()=>{n===this.#i&&this.#o(null,`idle`)}})}catch{n===this.#i&&this.#o(null,`idle`)}}stop(){this.#i++,this.#e?.stop(),this.#o(null,`idle`)}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#r.clear()}#o(e,t){this.#t=t===`idle`?null:e,this.#n=t;for(let e of this.#r)e(this.#t,this.#n)}},jr=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!this.#t&&(!e||!this.#e||e===this.#e)}};const{setLoader:Mr,load:Nr,getSync:J}=Ne({fallbackImport:()=>import(`./chunk-DGlFKA0r.js`)}),Pr=Nr,Fr=J;function Ir(e){if(!e)return``;let t=Lr(e);return Rr(t===null?e:t)}function Lr(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith(`{`))return null;try{let e=JSON.parse(t);if(e&&typeof e==`object`&&typeof e.text==`string`)return e.text}catch{}return null}function Rr(e){if(!e)return``;let t=e;return t=t.replace(/```[\s\S]*?```/g,` `),t=t.replace(/~~~[\s\S]*?~~~/g,` `),t=t.replace(/`([^`]+)`/g,`$1`),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,`$1`),t=t.replace(/<\/?[a-zA-Z][^>]*>/g,` `),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,``),t=t.replace(/^[ \t]*>[ \t]?/gm,``),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,``),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,``),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm,` `),t=t.replace(/(\*\*|__)(.*?)\1/g,`$2`),t=t.replace(/(\*|_)(.*?)\1/g,`$2`),t=t.replace(/~~(.*?)~~/g,`$1`),t=t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/ /g,` `),t=t.replace(/[ \t]+/g,` `),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
6
6
|
`),t=t.replace(/\n{2,}/g,`
|
|
7
|
-
`),t.trim()}const Nr=()=>import(`./chunk-59UOGW9N.js`),{setLoader:q,load:Pr}=me({fallbackImport:()=>import(`./chunk-B6zZsT6F.js`)}),J=Pr,Fr=/* @__PURE__ */ `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`.split(`.`);function Ir(e,t){return Fr.some(n=>e[n]!==t[n])}var Lr=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function Rr(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`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?`${r}\n\n_Details: ${n.message}_`:r}const zr=e=>We(e)||e===`suggest_replies`;var Br=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.streaming=!1,this.#e=/* @__PURE__ */ new Map,this.abortController=null,this.#n=Date.now(),this.clientSession=null,this.agentExecution=null,this.#r=null,this.#i=null,this.#a=!1,this.#o=null,this.#s=null,this.#c=null,this.artifacts=/* @__PURE__ */ new Map,this.#l=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#u=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#d=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#f=null,this.#p=null,this.#m=0,this.#h=0,this.#g=!1,this.#_=`disconnected`,this.#v=null,this.#y=null,this.#b=null,this.#x=0,this.#S=!1,this.#C=null,this.#w=!1,this.#T=null,this.#E=/* @__PURE__ */ new Map,this.#D=null,this.#O=/* @__PURE__ */ new Map,this.#k=null,this.#A=null,this.#j=!1,this.#M=null,this.#N=null,this.#P=!1,this.#F=null,this.#R=null,this.#z=null,this.#B=new wr,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Cr(()=>this.#W()),this.#Fe=null,this.#Ie=0,this.handleEvent=e=>{let t=this.#U,n=!1;if(t&&(e.type===`error`||e.type===`status`&&e.status===`error`?t.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),n=!0)),e.type===`message`){this.upsertMessage(e.message),n&&t.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#e.set(e.message.id,this.#t),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&dr().catch(()=>{});let r=e.message.toolCall,i=!!r?.name&&(We(r.name)||r.name===`suggest_replies`&&Xe(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&i&&this.#Re(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.#qe(e.id);else if(e.type===`status`){if(e.status===`idle`&&!e.terminal&&this.#Je()){this.#Xe();return}if(this.#rt(e.status),e.status===`connecting`)this.#it(!0);else if(e.status===`idle`||e.status===`error`){this.#Ye()||this.#tt(),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null,this.#De(),this.#Se());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#ze()}}else e.type===`error`?(this.#rt(`error`),this.#tt(),this.webMcpResolveControllers.size===0&&(this.#it(!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.#Ke(e)},this.historyInternals=this.#X(n),this.messages=[...e.initialMessages??[]].map(e=>({...e,sequence:e.sequence??this.#ut()})),this.messages=this.#dt(this.messages),this.client=new er(e,this.historyInternals),this.#pe(),this.#Pe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#l=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ge(),this.callbacks.onStatusChanged(this.status),this.#L(),this.#I()}#I(){this.config.voiceRecognition?.provider&&Or().catch(()=>{})}#L(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&Nr().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 I(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#g}getVoiceStatus(){return this.#_}getVoiceNotice(){return this.#f?.takeNotice?.()??null}getVoiceDisclosure(){return this.#f?.getDisclosure?.()??null}getVoiceLevel(){return this.#f?.onLevel?this.#h:null}getVoiceInterruptionMode(){return this.#f?.getInterruptionMode?this.#f.getInterruptionMode():`none`}stopVoicePlayback(){this.#f?.stopPlayback&&(this.#B.cancel(),this.#H?.cancel(),this.#f.stopPlayback())}isBargeInActive(){return this.#f?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#f?.deactivateBargeIn&&await this.#f.deactivateBargeIn()}#R;#z;#B;#V;#H;#U;#W(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Sr.isSupported()?new Sr({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return Nr().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#V,r=++this.#m;this.#p=Or().then(async e=>{await n,r===this.#m&&this.#G(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#m&&(this.#p=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#G(e,t){this.#f=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#f,generation:()=>n.#m,get keyed(){return n.#H},set keyed(e){n.#H=e},get pendingUser(){return n.#R},set pendingUser(e){n.#R=e},get pendingAssistant(){return n.#z},set pendingAssistant(e){n.#z=e},turns:()=>n.#B,busy:()=>n.#K(),setStreaming:e=>n.#it(e),setDelegation:e=>{n.#U=e},setLevel:e=>{n.#h=e},setStatus:e=>{n.#_=e,n.#g=e===`listening`},settlePending:e=>n.#J(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#f&&this.#p&&await this.#p,!this.#f)console.error(`Voice not configured`);else if(this.#g)await this.#f.stopListening();else{this.stopSpeaking();try{await this.#f.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}prewarmVoice(){if(!Sn(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#m,t=()=>{let t=this.#f;t?.prewarm&&e===this.#m&&(this.#g||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#f&&this.#p?this.#p.then(t,()=>{}):t()}#K(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||this.status===`resuming`}cleanupVoice(){let e=this.#f!==null;if(this.#m++,this.#p=null,this.#f){let e=this.#f;this.#f=null,this.#V=this.#q(e)}this.#g=!1,this.#_=`disconnected`,this.#J(!0),this.#H?.settle(),this.#H=null,this.#B=new wr,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#q(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#J(e){let t=e?this.#R:null,n=this.#z;(t||n)&&(n&&this.#B.cancel(),e&&(this.#R=null),this.#z=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#it(!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.#A=this.historyInternals.getStoredConversationRevision?.()??null,this.#j=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#Y(e,t)}#Y(e,t=!this.messages.length){if(this.#S||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#ut()};this.#ct(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#X(e),this.client.setHistoryInternals(this.historyInternals),this.#pe()}destroy(){this.cleanupVoice(),this.#M?.(),this.#M=null,this.#N=null}#X(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#fe(e),t?.(e)}}}get#Z(){return this.historyInternals.historyProvider??null}#Q(){let e=this.#Z;if(!e)throw new Lr(`history_unavailable`,`No conversation history provider is installed`);return e}#$(e){let t=this.#Q(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new vt(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#v,conversationRevision:this.#y,nextMessageCursor:this.#b,recovery:this.#C,sendBlocked:this.#w}}getActiveConversationId(){return this.#v}#ee(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#te(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#T;e&&await e.catch(()=>{});let t=this.#D;t&&await t.catch(()=>{})}#ne(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new Lr(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#Q().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#$(e?.scope)})}async openConversation(e,t){let n=this.#Q();this.#ne();let r=this.#$(t?.scope);await this.awaitHistorySettled();let i=++this.#x,a=await n.getPage(e,{context:r});if(i!==this.#x)throw new Lr(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new Lr(`superseded`,`A later selection won`);this.#S=!0;try{await this.#ce(o)}finally{this.#S=!1}this.#v=o.conversationId||e,this.#y=o.conversationRevision||a.conversationRevision||null,this.#b=a.nextCursor,this.#C=null,this.#w=!1,this.#ue();for(let e of a.messages)this.#O.set(e.id,e.content);return this.#le(),this.hydrateMessages(a.messages),this.#ee(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,n){let r=this.#Q(),i=this.#$(n?.scope),a=t??this.#b;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#E.get(o);if(s)return s;let c=this.#re(r,e,a,i).finally(()=>{this.#E.delete(o)});return this.#E.set(o,c),c}async#re(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#v&&this.#v!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=mt(this.messages,a.messages);this.messages=this.#dt(o.map(e=>this.#lt(e))),this.#b=a.nextCursor;for(let e of a.messages)this.#O.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#ee(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=++this.#x,i=await t.prepareStartNew({context:n});if(r!==this.#x)throw i.discard(),new Lr(`superseded`,`A later action won`);await this.#ie(i)}async#ie(e){this.#de(),await this.#ce(e),this.#v=e.conversationId||null,this.#y=e.conversationRevision||null,this.#b=null,this.#C=null,this.#w=!1,this.#le(),this.#ee()}async deleteConversation(e,t){let n=this.#Q(),r=this.#$(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),e===this.#v&&await this.#ae(r)}async updateConversation(e,t,n){let r=this.#Q();if(!r.update)throw new Lr(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#$(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#Z?.update==`function`}async clearConversationHistory(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return await this.#ae(n),r}async resetHistoryDevice(){let e=this.#Q();if(!e.resetDevice)throw new Lr(`history_unavailable`,`This history provider cannot reset the device`);this.#x+=1,this.#D=null;try{return await e.resetDevice()}finally{this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#w=!1,this.#ee()}}async#ae(e){this.#x+=1,this.#D=null,this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#w=!0,this.#C=null,this.#ee(),await this.#oe(e)}async#oe(e){let t=this.#Z;if(!t)this.#w=!1,this.#ee();else try{let n=await t.prepareStartNew({context:e});await this.#ie(n)}catch{this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#se(){if(this.#C===`new_conversation_required`&&this.#Z&&(this.#C=null,await this.#oe(this.#$()),this.#C===`new_conversation_required`))throw new Lr(`new_conversation_required`,`A new conversation is required before sending`)}async#ce(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#v=e.conversationId,this.#y=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#S||this.#Y(e)}#le(){this.#v?this.config.setStoredConversationId?.(this.#v):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#y),this.historyInternals.setStoredMessageCursor?.(this.#b)}#ue(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#O.clear(),this.#ye(null)}#de(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.messages=[],this.#ue(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}#fe(e){this.#x+=1,this.#D=null,this.#w=!0,this.#de(),this.#v=e.conversationId,this.#y=null,this.#b=null,this.#C=null,this.#ee(),this.#te(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#T=Promise.resolve().then(()=>{this.#w=!1,this.#T=null,this.#ee()})}#pe(){let e=this.historyInternals.visitorStore??null;e!==this.#N&&(this.#M?.(),this.#M=null,this.#N=e,e&&(this.#M=e.subscribe(e=>this.#me(e))))}#me(e){if(e.source!==`external`||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#D=null,this.#P=!0,this.#F=null;let t=this.messages.length>0;t||this.#v!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#de():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#ye(null)),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#ee(),t&&this.#te(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#he(){return this.#P?(this.#F||=this.#ge().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#ge(){if(!this.isClientTokenMode())this.#P=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#P=!1}catch{}}reconcileBootConversation(e){let t=this.#Z,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#v;if(!t||!n)return Promise.resolve();let r=this.#$(e?.scope);this.#w=!0,this.#ee();let i=this.#_e(t,n,r).finally(()=>{this.#w=this.#C!==null,this.#T===i&&(this.#T=null),this.#ee()});return this.#T=i,i}async#_e(e,t,n){this.#v=t;let r=this.clientSession?.conversationRevision??this.#y??null,i=this.#j?this.#A:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#j=!1,this.#b=this.historyInternals.getStoredMessageCursor?.()??this.#b,await this.replayPendingProjections(),r&&i&&r===i){this.#y=r;return}let a=await e.getPage(t,{context:n}),o=new Set(a.messages.map(e=>e.id)),s=this.messages.some(e=>o.has(e.id)),c=a.messages[0]?.createdAt,l;if(!s)l=a.messages.map(e=>this.#lt(e));else{let e=this.#r?this.#i:null,t=this.messages.filter(t=>o.has(t.id)||t.id===e?!0:c!==void 0&&t.createdAt<c);l=mt(t,a.messages).map(e=>this.#lt(e))}this.#b=a.nextCursor,this.#y=a.conversationRevision||r||null,this.#O.clear();for(let e of a.messages)this.#O.set(e.id,e.content);this.#le(),this.messages=this.#dt(l),this.callbacks.onMessagesChanged([...this.messages])}#ve(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#ye(e){this.#k=e,this.historyInternals.setPendingDisplayProjections?.(e)}#be(){return this.historyInternals.getPendingDisplayProjections?.()??this.#k}#xe(e){if(this.#ve())for(let t of e){let e=dt(t);e!==void 0&&this.#O.set(t.id,e)}}#Se(){if(!this.#ve())return;let e=this.#v;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=dt(e);n!==void 0&&this.#O.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#ye({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Ce(e,t))}#Ce(e,t){let n=(this.#D??Promise.resolve()).catch(()=>{}).then(()=>this.#we(e,t,!1)).finally(()=>{this.#D===n&&(this.#D=null)});this.#D=n}async#we(e,t,n){if(this.#v!==e)return;let r=t.filter(e=>this.#O.get(e.id)!==e.displayContent);if(r.length===0)this.#Ee(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#O.set(e.id,e.displayContent);this.#v===e&&n&&(this.#y=n),this.#Ee(e,t)}catch(i){if(!n&&this.#Te(i)){await this.#we(e,r,!0);return}if(i instanceof qn&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#Ee(e,t);return}this.#te(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Te(e){return e instanceof qn?e.code===`request_failed`:e instanceof Error}#Ee(e,t){let n=this.#be();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#ye(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ve())return;let e=this.#be();if(!e)return;if(this.#v&&e.conversationId!==this.#v){this.#ye(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#ye(null):(this.#Ce(e.conversationId,t),await this.#D?.catch(()=>{}))}#De(){this.#v&&(this.#y=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Oe(){await this.awaitHistorySettled(),await this.#he(),this.#C===`new_conversation_required`&&await this.#se()}static#ke(e){return e instanceof qn&&e.code===`conversation_deleted`}async#Ae(t,n,r,i,a){this.#xe(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken},this.handleEvent);return}catch(t){if(!e.#ke(t))throw t;let o=await this.#je(i);if(!o)throw t;this.#xe([o]),await this.client.dispatch({messages:[o],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken},this.handleEvent)}}async#je(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#x+=1,this.#D=null,this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#S=!0;try{let e=this.#Z;if(e){let t=await e.prepareStartNew({context:this.#$()});await this.#ie(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#S=!1}return this.#ct(n),this.#it(!0),this.#te(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=xn(this.config,n),i=Ir(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&Sn(n.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#Ue();return}this.#Ve(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.client=new er(this.config,this.historyInternals),a&&this.#Ue(),this.#Pe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e,f={id:a??(t===`user`?Rn():t===`assistant`?zn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#ut(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d}};return this.upsertMessage(f),f}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 t=[];for(let n of e){let{role:e,content:r,llmContent:i,contentParts:a,id:o,createdAt:s,sequence:c,streaming:l=!1,voiceProcessing:u,rawContent:d}=n,f={id:o??(e===`user`?Rn():e===`assistant`?zn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:r,createdAt:s??(/* @__PURE__ */ new Date()).toISOString(),sequence:c??this.#ut(),streaming:l,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...d!==void 0&&{rawContent:d}};t.push(f)}return this.messages=this.#dt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}async#Me(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
|
|
7
|
+
`),t.trim()}const zr=()=>import(`./chunk-59UOGW9N.js`),{setLoader:Br,load:Vr}=Ne({fallbackImport:()=>import(`./chunk-DO9_WSpy.js`)}),Hr=Vr,Ur=/* @__PURE__ */ `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`.split(`.`);function Wr(e,t){return Ur.some(n=>e[n]!==t[n])}var Gr=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function Kr(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`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?`${r}\n\n_Details: ${n.message}_`:r}const qr=e=>g(e)||e===`suggest_replies`;var Jr=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.streaming=!1,this.#e=/* @__PURE__ */ new Map,this.abortController=null,this.#n=Date.now(),this.clientSession=null,this.agentExecution=null,this.#r=null,this.#i=null,this.#a=!1,this.#o=null,this.#s=null,this.#c=null,this.artifacts=/* @__PURE__ */ new Map,this.#l=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#u=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#d=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#f=null,this.#p=null,this.#m=0,this.#h=0,this.#g=!1,this.#_=`disconnected`,this.#v=null,this.#y=null,this.#b=null,this.#x=0,this.#S=!1,this.#C=null,this.#w=!1,this.#T=null,this.#E=/* @__PURE__ */ new Map,this.#D=null,this.#O=/* @__PURE__ */ new Map,this.#k=null,this.#A=null,this.#j=!1,this.#M=null,this.#N=null,this.#P=!1,this.#F=null,this.#R=null,this.#z=null,this.#B=new jr,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Ar(()=>this.#W()),this.#Ie=null,this.#Le=0,this.handleEvent=e=>{let t=this.#U,n=!1;if(t&&(e.type===`error`||e.type===`status`&&e.status===`error`?t.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),n=!0)),e.type===`message`){this.upsertMessage(e.message),n&&t.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#e.set(e.message.id,this.#t),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&gr().catch(()=>{});let r=e.message.toolCall,i=!!r?.name&&(g(r.name)||r.name===`suggest_replies`&&et(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&i&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#ze(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.#Je(e.id);else if(e.type===`status`){if(e.status===`idle`&&!e.terminal&&this.#Ye()){this.#Ze();return}if(this.#st(e.status),e.status===`connecting`)this.#ct(!0);else if(e.status===`idle`||e.status===`error`){this.#Xe()||this.#at(),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null,this.#Oe(),this.#Ce());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#Be()}}else e.type===`error`?(this.#st(`error`),this.#at(),this.webMcpResolveControllers.size===0&&(this.#ct(!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.#qe(e)},this.historyInternals=this.#X(n),this.messages=[...e.initialMessages??[]].map(e=>({...y(e),sequence:e.sequence??this.#mt()})),this.messages=this.#ht(this.messages),this.client=new ar(e,this.historyInternals),this.#me(),this.#Fe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#l=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ke(),this.callbacks.onStatusChanged(this.status),this.#L(),this.#I()}#I(){this.config.voiceRecognition?.provider&&Pr().catch(()=>{})}#L(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&zr().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 V(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#g}getVoiceStatus(){return this.#_}getVoiceNotice(){return this.#f?.takeNotice?.()??null}getVoiceDisclosure(){return this.#f?.getDisclosure?.()??null}getVoiceLevel(){return this.#f?.onLevel?this.#h:null}getVoiceInterruptionMode(){return this.#f?.getInterruptionMode?this.#f.getInterruptionMode():`none`}stopVoicePlayback(){this.#f?.stopPlayback&&(this.#B.cancel(),this.#H?.cancel(),this.#f.stopPlayback())}isBargeInActive(){return this.#f?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#f?.deactivateBargeIn&&await this.#f.deactivateBargeIn()}#R;#z;#B;#V;#H;#U;#W(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=kr.isSupported()?new kr({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return zr().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#V,r=++this.#m;this.#p=Pr().then(async e=>{await n,r===this.#m&&this.#G(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#m&&(this.#p=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#G(e,t){this.#f=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#f,generation:()=>n.#m,get keyed(){return n.#H},set keyed(e){n.#H=e},get pendingUser(){return n.#R},set pendingUser(e){n.#R=e},get pendingAssistant(){return n.#z},set pendingAssistant(e){n.#z=e},turns:()=>n.#B,busy:()=>n.#K(),setStreaming:e=>n.#ct(e),setDelegation:e=>{n.#U=e},setLevel:e=>{n.#h=e},setStatus:e=>{n.#_=e,n.#g=e===`listening`},settlePending:e=>n.#J(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#f&&this.#p&&await this.#p,!this.#f)console.error(`Voice not configured`);else if(this.#g)await this.#f.stopListening();else{this.stopSpeaking();try{await this.#f.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}prewarmVoice(){if(!Cn(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#m,t=()=>{let t=this.#f;t?.prewarm&&e===this.#m&&(this.#g||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#f&&this.#p?this.#p.then(t,()=>{}):t()}#K(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||this.status===`resuming`}cleanupVoice(){let e=this.#f!==null;if(this.#m++,this.#p=null,this.#f){let e=this.#f;this.#f=null,this.#V=this.#q(e)}this.#g=!1,this.#_=`disconnected`,this.#J(!0),this.#H?.settle(),this.#H=null,this.#B=new jr,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#q(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#J(e){let t=e?this.#R:null,n=this.#z;(t||n)&&(n&&this.#B.cancel(),e&&(this.#R=null),this.#z=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#ct(!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.#A=this.historyInternals.getStoredConversationRevision?.()??null,this.#j=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#Y(e,t)}#Y(e,t=!this.messages.length){if(this.#S||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#mt()};this.#ft(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#X(e),this.client.setHistoryInternals(this.historyInternals),this.#me()}destroy(){this.cleanupVoice(),this.#M?.(),this.#M=null,this.#N=null}#X(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#pe(e),t?.(e)}}}get#Z(){return this.historyInternals.historyProvider??null}#Q(){let e=this.#Z;if(!e)throw new Gr(`history_unavailable`,`No conversation history provider is installed`);return e}#$(e){let t=this.#Q(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new Ct(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#v,conversationRevision:this.#y,nextMessageCursor:this.#b,recovery:this.#C,sendBlocked:this.#w}}getActiveConversationId(){return this.#v}#ee(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#te(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#T;e&&await e.catch(()=>{});let t=this.#D;t&&await t.catch(()=>{})}#ne(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new Gr(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#Q().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#$(e?.scope)})}async openConversation(e,t){let n=this.#Q();this.#ne();let r=this.#$(t?.scope);await this.awaitHistorySettled();let i=++this.#x,a=await n.getPage(e,{context:r});if(i!==this.#x)throw new Gr(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new Gr(`superseded`,`A later selection won`);this.#S=!0;try{await this.#le(o)}finally{this.#S=!1}this.#v=o.conversationId||e,this.#y=o.conversationRevision||a.conversationRevision||null,this.#b=a.nextCursor,this.#C=null,this.#w=!1,this.#de();for(let e of a.messages)this.#O.set(e.id,e.content);return this.#ue(),this.hydrateMessages(a.messages),this.#ee(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,n){let r=this.#Q(),i=this.#$(n?.scope),a=t??this.#b;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#E.get(o);if(s)return s;let c=this.#re(r,e,a,i).finally(()=>{this.#E.delete(o)});return this.#E.set(o,c),c}async#re(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#v&&this.#v!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ie(a.messages),s=vt(this.messages,o);this.messages=this.#ht(s.map(e=>this.#pt(e))),this.#b=a.nextCursor;for(let e of a.messages)this.#O.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#ee(),{messages:o,nextMessageCursor:a.nextCursor}}#ie(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&v(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return y(e)})}async startNewConversation(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=++this.#x,i=await t.prepareStartNew({context:n});if(r!==this.#x)throw i.discard(),new Gr(`superseded`,`A later action won`);await this.#ae(i)}async#ae(e){this.#fe(),await this.#le(e),this.#v=e.conversationId||null,this.#y=e.conversationRevision||null,this.#b=null,this.#C=null,this.#w=!1,this.#ue(),this.#ee()}async deleteConversation(e,t){let n=this.#Q(),r=this.#$(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),e===this.#v&&await this.#oe(r)}async updateConversation(e,t,n){let r=this.#Q();if(!r.update)throw new Gr(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#$(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#Z?.update==`function`}async clearConversationHistory(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return await this.#oe(n),r}async resetHistoryDevice(){let e=this.#Q();if(!e.resetDevice)throw new Gr(`history_unavailable`,`This history provider cannot reset the device`);this.#x+=1,this.#D=null;try{return await e.resetDevice()}finally{this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#w=!1,this.#ee()}}async#oe(e){this.#x+=1,this.#D=null,this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#w=!0,this.#C=null,this.#ee(),await this.#se(e)}async#se(e){let t=this.#Z;if(!t)this.#w=!1,this.#ee();else try{let n=await t.prepareStartNew({context:e});await this.#ae(n)}catch{this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#ce(){if(this.#C===`new_conversation_required`&&this.#Z&&(this.#C=null,await this.#se(this.#$()),this.#C===`new_conversation_required`))throw new Gr(`new_conversation_required`,`A new conversation is required before sending`)}async#le(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#v=e.conversationId,this.#y=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#S||this.#Y(e)}#ue(){this.#v?this.config.setStoredConversationId?.(this.#v):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#y),this.historyInternals.setStoredMessageCursor?.(this.#b)}#de(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#O.clear(),this.#be(null)}#fe(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.messages=[],this.#de(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}#pe(e){this.#x+=1,this.#D=null,this.#w=!0,this.#fe(),this.#v=e.conversationId,this.#y=null,this.#b=null,this.#C=null,this.#ee(),this.#te(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#T=Promise.resolve().then(()=>{this.#w=!1,this.#T=null,this.#ee()})}#me(){let e=this.historyInternals.visitorStore??null;e!==this.#N&&(this.#M?.(),this.#M=null,this.#N=e,e&&(this.#M=e.subscribe(e=>this.#he(e))))}#he(e){if(e.source!==`external`||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#D=null,this.#P=!0,this.#F=null;let t=this.messages.length>0;t||this.#v!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#fe():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#be(null)),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#ee(),t&&this.#te(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#ge(){return this.#P?(this.#F||=this.#_e().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#_e(){if(!this.isClientTokenMode())this.#P=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#P=!1}catch{}}reconcileBootConversation(e){let t=this.#Z,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#v;if(!t||!n)return Promise.resolve();let r=this.#$(e?.scope);this.#w=!0,this.#ee();let i=this.#ve(t,n,r).finally(()=>{this.#w=this.#C!==null,this.#T===i&&(this.#T=null),this.#ee()});return this.#T=i,i}async#ve(e,t,n){this.#v=t;let r=this.clientSession?.conversationRevision??this.#y??null,i=this.#j?this.#A:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#j=!1,this.#b=this.historyInternals.getStoredMessageCursor?.()??this.#b,await this.replayPendingProjections(),r&&i&&r===i){this.#y=r;return}let a=await e.getPage(t,{context:n}),o=this.#ie(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#pt(e));else{let e=this.#r?this.#i:null,t=this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l);u=vt(t,o).map(e=>this.#pt(e))}this.#b=a.nextCursor,this.#y=a.conversationRevision||r||null,this.#O.clear();for(let e of a.messages)this.#O.set(e.id,e.content);this.#ue(),this.messages=this.#ht(u),this.callbacks.onMessagesChanged([...this.messages])}#ye(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#be(e){this.#k=e,this.historyInternals.setPendingDisplayProjections?.(e)}#xe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#k}#Se(e){if(this.#ye())for(let t of e){let e=ht(t);e!==void 0&&this.#O.set(t.id,e)}}#Ce(){if(!this.#ye())return;let e=this.#v;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=ht(e);n!==void 0&&this.#O.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#be({conversationId:e,messageIds:t.map(e=>e.id)}),this.#we(e,t))}#we(e,t){let n=(this.#D??Promise.resolve()).catch(()=>{}).then(()=>this.#Te(e,t,!1)).finally(()=>{this.#D===n&&(this.#D=null)});this.#D=n}async#Te(e,t,n){if(this.#v!==e)return;let r=t.filter(e=>this.#O.get(e.id)!==e.displayContent);if(r.length===0)this.#De(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#O.set(e.id,e.displayContent);this.#v===e&&n&&(this.#y=n),this.#De(e,t)}catch(i){if(!n&&this.#Ee(i)){await this.#Te(e,r,!0);return}if(i instanceof Qn&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#De(e,t);return}this.#te(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Ee(e){return e instanceof Qn?e.code===`request_failed`:e instanceof Error}#De(e,t){let n=this.#xe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#be(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ye())return;let e=this.#xe();if(!e)return;if(this.#v&&e.conversationId!==this.#v){this.#be(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#be(null):(this.#we(e.conversationId,t),await this.#D?.catch(()=>{}))}#Oe(){this.#v&&(this.#y=null,this.historyInternals.setStoredConversationRevision?.(null))}async#ke(){await this.awaitHistorySettled(),await this.#ge(),this.#C===`new_conversation_required`&&await this.#ce()}static#Ae(e){return e instanceof Qn&&e.code===`conversation_deleted`}async#je(t,n,r,i,a){this.#Se(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent);return}catch(t){if(!e.#Ae(t))throw t;let o=await this.#Me(i);if(!o)throw t;this.#Se([o]),await this.client.dispatch({messages:[o],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent)}}async#Me(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#x+=1,this.#D=null,this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#S=!0;try{let e=this.#Z;if(e){let t=await e.prepareStartNew({context:this.#$()});await this.#ae(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#S=!1}return this.#ft(n),this.#ct(!0),this.#te(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=z(this.config,n),i=Wr(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&Cn(n.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#We();return}this.#He(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.client=new ar(this.config,this.historyInternals),a&&this.#We(),this.#Fe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e,f={id:a??(t===`user`?Je():t===`assistant`?Ye():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#mt(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d}};return this.upsertMessage(f),f}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 t=[];for(let n of e){let{role:e,content:r,llmContent:i,contentParts:a,id:o,createdAt:s,sequence:c,streaming:l=!1,voiceProcessing:u,rawContent:d}=n,f={id:o??(e===`user`?Je():e===`assistant`?Ye():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:r,createdAt:s??(/* @__PURE__ */ new Date()).toISOString(),sequence:c??this.#mt(),streaming:l,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...d!==void 0&&{rawContent:d}};t.push(f)}return this.messages=this.#ht([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}async#Ne(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
|
|
8
8
|
|
|
9
9
|
`),a=[i,t].filter(Boolean).join(`
|
|
10
10
|
|
|
11
|
-
`),o=Array.isArray(e.contentParts)&&e.contentParts.length>0,s=r.contentParts.length>0;if(o){let t=[];i&&t.push(it(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(it(a)),t.push(...r.contentParts),e.contentParts=t}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,t){let n=e.trim(),r=!!t?.replayFields&&(t.replayFields.llmContent!==void 0||t.replayFields.rawContent!==void 0||(t.replayFields.contextMentions?.length??0)>0);if(!n&&(!t?.contentParts||t.contentParts.length===0)&&(!t?.mentions||t.mentions.refs.length===0)&&!r)return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#T||this.#D||this.#w||this.#P)&&await this.#Oe(),this.stopSpeaking(),this.abortController?.abort(),this.#Ve(),this.#Ie++,this.#et();let i=t?.voiceTurn?.userMessageId,a=i?this.messages.find(e=>e.id===i&&e.role===`user`):void 0,o=a?.id??Rn(),s=zn();this.#i=null;let c=t?.contentParts&&ot(t.contentParts)?st:``,l={id:o,role:`user`,content:n||c,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#ut(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==n&&(a.llmContent=n),this.callbacks.onMessagesChanged([...this.messages])):this.#ct(l),this.#it(!0);let u=new AbortController;if(this.abortController=u,t?.mentions){let e=this.messages.find(e=>e.id===o)??l;if(await this.#Me(e,n,t.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===o)??l,n=hr({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});n.contentParts&&(e.contentParts=n.contentParts),n.llmContent!==void 0&&(e.llmContent=n.llmContent),(n.contentParts||n.llmContent!==void 0)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let d=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:(/* @__PURE__ */ new Date()).toISOString()}]:[...this.messages];try{await this.#Ae(d,u,s,o,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn})}catch(e){if(this.status===`resuming`||this.#a)return;this.#U&&(this.#U.failed=!0);let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));if(!t){let t=Rr(e,this.config.errorMessage);if(t){let e={id:s,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:t,sequence:this.#ut()};this.#ct(e)}}this.#rt(`idle`),this.#it(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let n=_r(this.messages,e);if(!n)return!1;let r=this.messages[n.start],i=t.replacement,a=i?i.text:r.content,o=i?i.contentParts:r.contentParts;if(!(a?.trim()||(o?.length??0)>0||!i&&(r.llmContent?.trim()?.length??0)>0))return!1;let s=i?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},c=i?this.#Ne(i.options):r.composerOptions,l=i?i.contentSegments:r.contentSegments,u=i?i.options?.quote:void 0,d=i?i.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(a??``,{...o?.length?{contentParts:[...o]}:{},...l?.length?{contentSegments:[...l]}:{},...c?{composerOptions:c}:{},...u?{quote:u}:{},...s&&Object.keys(s).length>0?{replayFields:s}:{},viaVoice:d===!0}),!0}#Ne(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#T||this.#D||this.#w||this.#P)&&await this.#Oe(),this.abortController?.abort(),this.#et();let e=zn();this.#i=null,this.#it(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if(this.status===`resuming`||this.#a)return;let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));if(!n){let n=Rr(t,this.config.errorMessage);if(n){let t={id:e,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:n,sequence:this.#ut()};this.#ct(t)}}this.#rt(`idle`),this.#it(!1),this.abortController=null,n||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#i=t.assistantMessageId);let n=t?.preserveAssistantId?t.assistantMessageId:void 0,r=!1;for(let e of this.messages)e.streaming&&e.id!==n&&(e.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#it(!0);let i={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=i;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#at(i)}catch(e){if(this.status===`resuming`||this.#a){this.#ot(i);return}this.#at(i),this.#rt(`error`),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Pe(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.#d}`,status:`pending`,agentId:``,executionId:``,toolName:e.toolName,toolType:`webmcp`,description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},n=`approval-${t.id}`;return this.upsertMessage({id:n,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,approval:t}),new Promise(e=>{this.webMcpApprovalResolvers.set(n,e)})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(t=>t.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:t,resolvedAt:Date.now()}}),n(t===`approved`)}#Fe;#Ie;#Le(e){let t=this.#Fe??={s:this,setStreaming:e=>this.#it(e),appendMessage:e=>this.#ct(e),nextSequence:()=>this.#ut(),settleApprovalPausedToolCall:e=>this.#st(e),resumeAfter:e=>this.#r?.executionId===e?this.#r.lastEventId:void 0},n=fr();if(n)return e(n,t);let r=this.#Ie;return dr().then(n=>r===this.#Ie?e(n,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,n){return this.#Le((r,i)=>r.resolveApproval(i,e,t,n))}resolveAskUserQuestion(e,t){return this.#Le((n,r)=>n.resolveAskUserQuestion(r,e,t))}resolveWebMcpToolCall(e){return this.#Le((t,n)=>t.resolveWebMcpToolCall(n,e))}persistAskUserQuestionProgress(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#Re(e){let t=e.agentMetadata?.executionId,n=e.toolCall?.id;if(!t||!n){let t=this.#u;queueMicrotask(()=>{t===this.#u&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(t);r||(r={snapshots:[],seen:/* @__PURE__ */ new Set},this.webMcpAwaitBatches.set(t,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(e))}#ze(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#u;queueMicrotask(()=>{if(e===this.#u)for(let e of[...this.webMcpAwaitBatches.keys()])this.#Be(e)})}#Be(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.#Le((t,r)=>t.resolveWebMcpToolCallBatch(r,e,n))}#Ve(){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.#u++}cancel(){this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#it(!1),this.#rt(`idle`)}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.messages=[],this.agentExecution=null,this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#l}selectArtifact(e){this.#l=e,this.#Ge()}clearArtifacts(){this.#We()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=e.artifactType===`markdown`?{id:t,artifactType:`markdown`,title:e.title,status:`complete`,markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:`component`,title:e.title,status:`complete`,component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,n),this.#l=t,this.#Ge(),e.transcript!==!1&&this.#He(n),n}#He(e){let t=`artifact-ref-${e.id}`,n=et(this.config.features?.artifacts,e),r=rt(n,{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(e=>e.id===t);i?(i.rawContent=r,i.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:``,rawContent:r})}#Ue(){let e=!1;for(let t of this.artifacts.values()){let n=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!n)continue;let r=et(this.config.features?.artifacts,t),i=rt(r,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown===void 0?{}:{markdown:t.markdown}});n.rawContent!==i&&(n.rawContent=i,n.streaming=t.status===`streaming`,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#We(){(this.artifacts.size!==0||this.#l!==null)&&(this.artifacts.clear(),this.#l=null,this.#Ge())}#Ge(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#l})}#Ke(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.#l=e.id;break;case`artifact_delta`:{let t=this.artifacts.get(e.id);t?.artifactType===`markdown`&&(t.markdown=(t.markdown??``)+e.artDelta);break}case`artifact_update`:{let t=this.artifacts.get(e.id);t?.artifactType===`component`&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case`artifact_complete`:{let t=this.artifacts.get(e.id);t&&(t.status=`complete`);break}default:return}this.#Ge()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#dt(e.map(e=>({...e,streaming:!1,sequence:e.sequence??this.#ut()}))),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:`complete`});this.#l=t,this.#Ge()}#qe(e){let t=this.agentExecution?.executionId;if(!t||!this.#i||this.agentExecution?.status!==`running`)return;let n=this.#r===null;this.#r={executionId:t,lastEventId:e,assistantMessageId:this.#i,status:`running`},this.#nt(n)}#Je(){return this.#r!==null&&typeof this.config.reconnectStream==`function`&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Ye()}#Ye(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant===`approval`&&e.approval?.status===`pending`)}#Xe(){this.#a||this.#r&&typeof this.config.reconnectStream==`function`&&(this.#a=!0,this.callbacks.onReconnect?.({phase:`paused`,handle:this.#r}),this.#it(!0),this.#rt(`resuming`),this.#Ze().then(e=>{this.#a&&this.#r&&e.begin()}))}#Ze(){return this.#o?Promise.resolve(this.#o):(this.#s||(this.#s=J().then(({createReconnectController:e})=>{let t=e(this.#Qe());return this.#o=t,t}),this.#s.catch(()=>{this.#s=null})),this.#s)}#Qe(){let e=this;return{get config(){return e.config},getResumable:()=>e.#r,clearResumable:()=>e.#tt(),getStatus:()=>e.status,setStatus:t=>e.#rt(t),setStreaming:t=>e.#it(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,n,r)=>e.connectStream(t,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:t=>e.#ct(t),nextSequence:()=>e.#ut(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>Rr(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#o?.wake():this.#Xe()}resumeFromHandle(e){if(typeof this.config.reconnectStream!=`function`||this.#a)return;let t=this.#$e();t||(t=zn(),this.#ct({id:t,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:this.#ut()})),this.#i=t,this.agentExecution||={executionId:e.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:`running`},this.#Xe()}#$e(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role===`assistant`&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role===`user`)break}return null}#et(){this.#a=!1,this.#o?.teardown(),this.#tt()}#tt(){this.#c&&=(clearTimeout(this.#c),null);let e=this.#r!==null;this.#r=null,e&&this.config.onExecutionState?.(null)}#nt(e){let t=this.config.onExecutionState;t&&(e?(this.#c&&=(clearTimeout(this.#c),null),t(this.#r)):this.#c||=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#r)},500))}getResumableHandle(){return this.#r}#rt(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#it(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#at(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider===`browser`||t.provider===`runtype`&&t.browserFallback))return;let n=[...this.messages].reverse().find(e=>e.role===`assistant`&&e.content&&!e.voiceProcessing);if(!n||e&&!e.includes(n.id))return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Ar(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return xr(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=Ar(t.content||``);if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.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()}#at(e){for(let[t,n]of[...this.#e])n===e&&(this.#e.delete(t),this.#st(t))}#ot(e){for(let[t,n]of this.#e)n===e&&this.#e.set(t,void 0)}#st(e){let t=this.messages.find(t=>t.id===e)?.approval,n=t?.toolCallId,r=n&&this.messages.find(e=>e.toolCall?.id===n),i=r&&r.toolCall;if(!i||i.status===`complete`||t.status===`pending`)return;let a={...i,status:`complete`,approvalStatus:t.status,completedAt:Date.now(),...t.status===`approved`?{superseded:!0}:{success:!1,error:t.status===`denied`?`Denied`:`Approval timed out`}};this.upsertMessage({...r,streaming:!1,toolCall:a})}#ct(e){let t=this.#lt(e);this.messages=this.#dt([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#lt(e),n=this.messages.findIndex(e=>e.id===t.id);n===-1?this.#ct(t):(this.messages=this.messages.map((e,r)=>{if(r!==n)return e;let i={...e,...t};e.agentMetadata?.askUserQuestionAnswered===!0&&t.agentMetadata&&(i.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),e.agentMetadata?.suggestRepliesResolved===!0&&t.agentMetadata&&(i.agentMetadata={...i.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let n=e.approval,r=t.approval;i.approval={...n,...r,executionId:r.executionId||n.executionId,toolName:r.toolName||n.toolName,description:r.description||n.description,toolType:r.toolType??n.toolType,reason:r.reason??n.reason,parameters:r.parameters??n.parameters,toolCallId:r.toolCallId??n.toolCallId}}let o=t.toolCall?.name,s=t.agentMetadata?.executionId,c=t.toolCall?.id;if(o&&zr(o)&&s&&c&&t.agentMetadata?.awaitingLocalTool===!0){let t=`${s}:${c}`,n=this.webMcpInflightKeys.has(t),r=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,o=e.agentMetadata?.executionId===s&&e.toolCall?.id===c&&a!==void 0&&zr(a)&&e.toolCall?.status===`complete`;(n||r||o)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=e.toolCall,i.streaming=e.streaming)}return i}),this.messages=this.#dt(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#lt(e){return e.sequence===void 0?{...e,sequence:this.#ut()}:{...e}}#ut(){return this.#n++}#dt(e){return[...e].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}};const Vr={add:e=>ct(e)},Hr=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Ur={allowedTypes:lt,maxFileSize:10485760,maxFiles:4};function Wr(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Gr(e){return e===`application/pdf`||e.startsWith(`text/`)||e.includes(`word`)?tn:e.includes(`excel`)||e.includes(`spreadsheet`)?en:e===`application/json`?$t:Qt}var Kr=class t{#e;#t;#n;constructor(e={}){this.attachments=[],this.#e=null,this.#t=/* @__PURE__ */ new Map,this.#n=!1,this.config={allowedTypes:e.allowedTypes??Ur.allowedTypes,maxFileSize:e.maxFileSize??Ur.maxFileSize,maxFiles:e.maxFiles??Ur.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#r(){return typeof this.config.adapter?.add==`function`}#i(){return this.#r()?this.config.adapter:Vr}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML=``;for(let e of this.attachments)this.#l(e)}this.#f()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ur.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.#n)return;let t=[];for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,`count`);continue}let e=P(n,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes(`type`)?`type`:`size`;this.config.onFileRejected?.(n,t);continue}let r={id:Wr(),file:n,previewUrl:ut(n)?URL.createObjectURL(n):null,contentPart:null,status:this.#r()?`uploading`:`processing`,progress:this.#r()?0:void 0};this.attachments.push(r),this.#l(r),t.push(r)}this.#f(),this.#c(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let n=()=>this.#n||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let r=await this.#i().add(e.file,{signal:t.signal,onProgress:t=>{n()||e.status!==`uploading`||(e.progress=Hr(t),this.#u(e),this.#c())}});if(n())return;e.contentPart=r,e.status=`ready`,e.progress=void 0,e.error=void 0}catch(t){if(n())return;e.status=`error`,e.progress=void 0,e.error=t instanceof Error?t.message:String(t??`Upload failed`)}finally{this.#t.get(e.id)===t&&this.#t.delete(e.id)}this.#u(e),this.#c()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||t.status!==`error`||this.#n||(t.status=this.#r()?`uploading`:`processing`,t.progress=this.#r()?0:void 0,t.error=void 0,this.#u(t),this.#c(),this.#a(t))}#o(e){let t=this.#t.get(e);t&&(this.#t.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(t===-1)return;let n=this.attachments[t];this.#o(e),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let r=this.#e?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),n.status===`ready`&&n.contentPart&&this.#s(n.contentPart),this.#f(),this.#c()}#s(e){let t=this.config.adapter?.remove;if(t)try{let n=t(e,{signal:new AbortController().signal});n&&typeof n.catch==`function`&&n.catch(e=>{console.error(`[AttachmentManager] adapter.remove failed:`,e)})}catch(e){console.error(`[AttachmentManager] adapter.remove failed:`,e)}}clearAttachments(){for(let e of this.attachments)this.#o(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=``),this.#f(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let e of this.#t.values())e.abort();this.#t.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#l(t){if(!this.#e)return;let n=ut(t.file),r=j(`div`,`persona-attachment-preview persona-relative persona-inline-block`);if(r.setAttribute(`data-attachment-id`,t.id),r.style.width=`48px`,r.style.height=`48px`,n&&t.previewUrl){let e=j(`img`);e.src=t.previewUrl,e.alt=t.file.name,e.className=`persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200`,e.style.width=`48px`,e.style.height=`48px`,e.style.objectFit=`cover`,e.style.borderRadius=`8px`,r.appendChild(e)}else{let n=j(`div`);n.style.width=`48px`,n.style.height=`48px`,n.style.borderRadius=`8px`,n.style.backgroundColor=`var(--persona-container, #f3f4f6)`,n.style.border=`1px solid var(--persona-border, #e5e7eb)`,n.style.display=`flex`,n.style.flexDirection=`column`,n.style.alignItems=`center`,n.style.justifyContent=`center`,n.style.gap=`2px`,n.style.overflow=`hidden`;let i=Gr(t.file.type),a=e(i,20,`var(--persona-muted, #6b7280)`,1.5);a&&n.appendChild(a);let o=j(`span`);o.textContent=at(t.file.type,t.file.name),o.style.fontSize=`8px`,o.style.fontWeight=`600`,o.style.color=`var(--persona-muted, #6b7280)`,o.style.textTransform=`uppercase`,o.style.lineHeight=`1`,n.appendChild(o),r.appendChild(n)}let i=A(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),a=j(`div`,`persona-attachment-progress`);a.appendChild(j(`div`,`persona-attachment-progress__bar`));let o=A(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),s=M(`rotate-cw`,12,`var(--persona-text-inverse, #ffffff)`,2);s?o.appendChild(s):o.textContent=`↻`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.retryAttachment(t.id)}),i.append(a,o),r.appendChild(i);let c=j(`button`,`persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center`);c.type=`button`,c.setAttribute(`aria-label`,`Remove attachment`),c.style.position=`absolute`,c.style.top=`-4px`,c.style.insetInlineEnd=`-4px`,c.style.width=`18px`,c.style.height=`18px`,c.style.borderRadius=`50%`,c.style.backgroundColor=`var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))`,c.style.border=`none`,c.style.cursor=`pointer`,c.style.display=`flex`,c.style.alignItems=`center`,c.style.justifyContent=`center`,c.style.padding=`0`;let l=e(rn,10,`var(--persona-text-inverse, #ffffff)`,2);l?c.appendChild(l):(c.textContent=`×`,c.style.color=`var(--persona-text-inverse, #ffffff)`,c.style.fontSize=`14px`,c.style.lineHeight=`1`),c.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(c),this.#e.appendChild(r),this.#d(r,t)}#u(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#d(t,e)}#d(e,t){e.dataset.status=t.status;let n=t.status!==`ready`&&t.status!==`error`;e.setAttribute(`aria-busy`,n?`true`:`false`),e.title=t.status===`error`?`${t.file.name}: ${t.error??`Upload failed`}`:t.file.name;let r=e.querySelector(`.persona-attachment-progress__bar`);if(r){let e=t.progress;r.style.width=typeof e==`number`?`${Math.round(e*100)}%`:``}}#f(){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})}};const qr=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Jr=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.name===r.name&&e.mimeType===r.mimeType&&e.size===r.size&&e.status===r.status&&e.progress===r.progress&&e.error===r.error});function Yr(){let e={text:``,attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=/* @__PURE__ */ new Set,n=null,r=!1,i=!1,a=()=>e.preparing?`preparing`:e.streaming?`streaming`:`idle`,o=()=>{let t=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:t,inputDisabled:e.inputDisabled,sendDisabled:t!==`idle`||e.sendDisabled||e.inputDisabled})},s=()=>(n||=o(),n),c=()=>{if(r=!1,i||t.size===0)return;let e=s();for(let n of[...t])try{n(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] composer state listener failed:`,e)}},l=()=>{n=null,!(i||r)&&(r=!0,queueMicrotask(c))};return{getState:s,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,l())},setAttachments:t=>{Jr(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{qr(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{qr(e.activeModeIds,t)||(e.activeModeIds=[...t],l())},setQuote:t=>{let n=e.quote;(n?.text!==t?.text||n?.messageId!==t?.messageId||n?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,l())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,l())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,l())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,l())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,l())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,l())},flush:()=>{r&&c()},destroy:()=>{i=!0,r=!1,t.clear()}}}const Xr=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},Zr=(e,t)=>{let n=j(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function Qr(e,t={}){let n=Xr(e,`[data-persona-composer-form]`),r=Xr(e,`[data-persona-composer-input]`);if(!n||!r){let e=`[Persona] composer surface is missing required element(s): ${[!n&&`form`,!r&&`input`].filter(Boolean).join(`, `)}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||r))throw Error(e);return typeof console<`u`&&console.warn(e),null}let i={header:Xr(e,`[data-persona-composer-header]`),body:Xr(e,`[data-persona-composer-body]`),actionsStart:Xr(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:Xr(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:Xr(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:Xr(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:Xr(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=Zr(`persona-widget-composer__header`,`data-persona-composer-header`),n.parentNode?n.parentNode.insertBefore(o,n):e.appendChild(o));let s=i.body??r.parentElement??n,c=(e,t,n,r,i)=>{if(t)return t;a.add(e);let o=Zr(n,r);return i.appendChild(o),o},l=c(`actionsStart`,i.actionsStart,`persona-widget-composer__left-actions`,`data-persona-composer-actions-start`,n),u=c(`actionsEnd`,i.actionsEnd,`persona-widget-composer__right-actions`,`data-persona-composer-actions-end`,n),d=c(`suggestions`,i.suggestions,`persona-widget-composer__suggestions`,`data-persona-composer-suggestions`,e),f=c(`status`,i.status,`persona-widget-composer__status`,`data-persona-composer-status`,e),p=[],m=(e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler,h=Xr(e,`[data-persona-composer-attachment-input]`,`input[type="file"]`)??void 0;return{footer:e,form:n,input:r,header:o,body:s,actionsStart:l,actionsEnd:u,suggestions:d,status:f,attachmentInput:h,attachmentPreviews:Xr(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:Xr(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:Xr(e,`[data-persona-composer-submit]`)??void 0,micButton:Xr(e,`[data-persona-composer-mic]`)??void 0,synthesized:a,found:i,addListener:(e,t,n,r)=>{e.addEventListener(t,n,r),p.push({target:e,type:t,handler:n,options:r})},removeListener:(e,t,n,r)=>{e.removeEventListener(t,n,r),p=p.filter(r=>!m(r,{target:e,type:t,handler:n}))},destroy:()=>{for(let e of p)e.target.removeEventListener(e.type,e.handler,e.options);p=[]}}}const $r=[`--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`],ei=`data-persona-menu-focus`,ti=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function ni(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const ri=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function ii(e){let t=e.label,n=!1,r=j(`div`,`persona-send-button-wrapper`),i=A(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${y} ${ne}`,attrs:{type:`button`,"aria-haspopup":`menu`,"aria-expanded":`false`,"data-persona-composer-overflow-trigger":``}});r.appendChild(i);let a=A(`div`,{className:`persona-composer-overflow-menu`,attrs:{role:`menu`,tabindex:`-1`,"data-persona-composer-overflow-menu":``}}),o=()=>{let t=e.getButtonSize?.()??``;i.style.width=t,i.style.height=t,i.style.minWidth=t,i.style.minHeight=t,i.style.lineHeight=`1`,i.replaceChildren();let n=M(`plus`,24,`currentColor`,1.5);n?i.appendChild(n):i.textContent=`+`},s=()=>{i.setAttribute(`aria-label`,t),i.setAttribute(`title`,t),a.setAttribute(`aria-label`,t)};s(),o();let c=[],l=-1,u=!1,d=()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null},f=()=>{let e=d();for(let t of c){let n=!!e&&ni(t)===e;t.toggleAttribute(ei,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(ni).filter(e=>!ri(e)),m=(e,t)=>{e.forEach((e,n)=>{e.setAttribute(`tabindex`,n===t?`0`:`-1`)})},h=e=>{let t=p();if(t.length===0)return;let n=(e%t.length+t.length)%t.length;l=n,m(t,n),t[n].focus(),f()},g=()=>r.ownerDocument??document,_=null,v=null,b=null,x=()=>{_&&=(g().removeEventListener(`focusin`,_,!0),null)},S=()=>{v&&=(a.removeEventListener(`focusin`,v),null),b&&=(a.removeEventListener(`pointerdown`,b,!0),null)},C=null,w=()=>(C||=Ct({anchor:i,content:a,placement:`top-start`,offset:6,onDismiss:()=>{i.setAttribute(`aria-expanded`,`false`),x()}}),C),T=()=>C?.isOpen===!0,E=(e=!1)=>{if(T()){C?.close(),i.setAttribute(`aria-expanded`,`false`),x(),S(),l=-1,u=!1;for(let e of c)e.removeAttribute(ei);e&&i.focus()}},D=(e=0,t=!1)=>{if(n||T())return;u=t,ee(i,a,$r),w().open(),i.setAttribute(`aria-expanded`,`true`);let o=p();m(o,-1),h(e<0?o.length-1:e),_=e=>{let t=typeof e.composedPath==`function`?e.composedPath():[];t.includes(a)||t.includes(r)||E()},g().addEventListener(`focusin`,_,!0),v=()=>f(),a.addEventListener(`focusin`,v),b=()=>{u=!1},a.addEventListener(`pointerdown`,b,!0)},O=e=>{e.preventDefault(),e.stopPropagation(),T()?E(!0):D(0)},k=e=>{e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),u=!0,T()?h(0):D(0,!0)):e.key===`ArrowUp`&&(e.preventDefault(),u=!0,T()?h(-1):D(-1,!0))},te=e=>{switch(ti.has(e.key)&&(u=!0),e.key){case`ArrowDown`:e.preventDefault(),h(l+1);return;case`ArrowUp`:e.preventDefault(),h(l-1);return;case`Home`:e.preventDefault(),h(0);return;case`End`:e.preventDefault(),h(p().length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),E(!0);return;case`Tab`:E(!0);return}};return i.addEventListener(`click`,O),i.addEventListener(`keydown`,k),a.addEventListener(`keydown`,te),{trigger:r,triggerButton:i,panel:a,setItems:e=>{for(let t of c)e.includes(t)||t.removeAttribute(ei);if(c=[...e],!T())return;let t=p();m(t,Math.min(l,t.length-1)),f()},isOpen:T,open:()=>D(0),close:E,setLabel:e=>{e!==t&&(t=e,s())},applyButtonSize:o,destroy:()=>{n=!0,x(),S(),i.removeEventListener(`click`,O),i.removeEventListener(`keydown`,k),a.removeEventListener(`keydown`,te),C?.destroy(),C=null,r.remove(),a.remove(),c=[]}}}const ai={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},oi=`data-persona-composer-action`,si=`data-persona-composer-disable-when-streaming`,ci=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function li(e,t){if(e===void 0)return null;if(typeof e==`number`)return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let r=j(`div`);r.style.position=`absolute`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`,r.style.height=`0`,r.style.width=e,t.appendChild(r);let i=r.getBoundingClientRect().width;return r.remove(),Number.isFinite(i)&&i>0?i:Number.isFinite(n)?n:null}function ui(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let r=n.getComputedStyle(e),i=(Number.parseFloat(r.paddingLeft)||0)+(Number.parseFloat(r.paddingRight)||0);return Math.max(0,t-i)}const di=(e,t)=>{e&&typeof console<`u`&&console.warn(t)},fi=(e,t)=>t.includes(`:`)?t:`${e}:${t}`;function pi(e){let{debug:t}=e,n=[],r=/* @__PURE__ */ new Map,i=0,a=e=>{let i=r.get(e.id);i?di(t,`[Persona] composer action "${e.id}" is already contributed by ${mi(i)}; the ${mi(e)} copy is ignored.`):(r.set(e.id,e),n.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:`bar`,order:t.order,sequence:i++,source:`core`,builtIn:t});let o=(e,n,r)=>{let o=r?fi(r,e.id):e.id,s=e.order??ai.custom;e.placement===`end`&&s>=ai.send&&(di(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${ai.send-1}.`),s=ai.send-1),a({id:o,placement:e.placement,presentation:e.presentation??`bar`,order:s,sequence:i++,source:n,pluginId:r,action:e})};for(let t of e.configActions??[])o(t,`config`);for(let t of e.plugins){if(!t.contributeComposerActions)continue;let n;try{n=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<`u`&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of n??[])o(e,`plugin`,t.id)}return n.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}const mi=e=>e.source===`plugin`?`plugin "${e.pluginId}"`:e.source===`config`?`composer.actions`:`a core built-in`,hi=(e,t,n)=>e===void 0?n:typeof e==`function`?e(t)===!0:e===!0,gi=e=>e.phase===`streaming`||e.text.trim().length>0||e.attachments.length>0;function Y(e,t){if(!e||e===`always`)return!0;let n=gi(t);return e===`when-text`?n:!n}const _i=e=>e.kind===`custom`,vi=e=>e instanceof HTMLButtonElement?e:e.querySelector(`button`)??e,yi=e=>{let t=vi(e);return t.getAttribute(`aria-label`)?.trim()||t.getAttribute(`title`)?.trim()||``};function bi(e){let t=``,n=e=>{if(e.nodeType===Node.TEXT_NODE){t+=e.nodeValue??``;return}if(e.nodeType!==Node.ELEMENT_NODE)return;let r=e;typeof r.matches==`function`&&r.matches(`.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]`)||e.childNodes.forEach(n)};return n(e),t.trim()}const xi=e=>bi(e).length===0;function Si(e){let t=/* @__PURE__ */ new Map,r=[],i=!1,a=()=>e.getButtonSize?.(),o=(e,t)=>{let n=e.button;if(!n)return;n.setAttribute(`role`,`menuitem`),n.setAttribute(`tabindex`,`-1`),n.className=`persona-composer-overflow-menu__item`;for(let e of[`width`,`height`,`minWidth`,`minHeight`,`fontSize`,`color`,`backgroundColor`])n.style[e]=``;n.style.lineHeight=`1`,t.tooltipText?n.setAttribute(`title`,t.tooltipText):n.removeAttribute(`title`),n.replaceChildren();let r=j(`span`,`persona-composer-overflow-menu__icon`);if(t.iconName){let e=M(t.iconName,16,`currentColor`,1.5);e&&r.appendChild(e)}let i=j(`span`,`persona-composer-overflow-menu__label`);i.textContent=t.shortLabel??t.label,n.append(r,i)},s=(e,t)=>{let r=e.button;if(!r)return;if(r.setAttribute(`aria-label`,t.label),t.pressed===void 0?r.removeAttribute(`aria-pressed`):r.setAttribute(`aria-pressed`,t.pressed?`true`:`false`),r.toggleAttribute(si,t.disableWhenStreaming===!0),e.mode===`menu`){e.tooltip?.destroy(),e.tooltip=void 0,o(e,t);return}r.removeAttribute(`role`),r.removeAttribute(`tabindex`),r.removeAttribute(`title`);let i=a(),s=!!t.shortLabel;if(r.className=pe(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button`,y,ne,s&&`persona-composer-action-button--text persona-gap-1 persona-text-sm`),r.style.width=i&&!s?i:``,r.style.height=i??``,r.style.minWidth=i&&!s?i:``,r.style.minHeight=i??``,r.style.fontSize=s?``:`18px`,r.style.lineHeight=`1`,r.style.color=t.iconColor??``,r.style.backgroundColor=t.backgroundColor??``,r.replaceChildren(),t.iconName){let e=M(t.iconName,24,`currentColor`,1.5);e&&r.appendChild(e)}if(s){let e=j(`span`,`persona-composer-action-button__label`);e.textContent=t.shortLabel,r.appendChild(e)}else r.firstChild||(r.textContent=t.label);e.tooltip?.destroy(),e.tooltip=n({anchor:r,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},c=(t,n)=>{let r=t.action,i=A(`button`,{attrs:{type:`button`}}),a=i;if(n===`bar`){let e=j(`div`,`persona-send-button-wrapper`);e.appendChild(i),a=e}a.setAttribute(oi,t.id);let o={resolved:t,element:a,button:i,owned:!0,managed:!0,busy:!1,visible:!0,mode:n},c=t=>{if(t.preventDefault(),t.stopPropagation(),o.busy||i.disabled)return;let n=o.resolved.action;o.mode===`menu`&&g?.close(!0);let r;try{r=n.onSelect(e.actionContext,t)}catch(t){e.reportError(t,{actionId:o.resolved.id});return}r&&typeof r.then==`function`&&(o.busy=!0,i.setAttribute(`aria-busy`,`true`),r.catch(t=>{e.reportError(t,{actionId:o.resolved.id})}).finally(()=>{o.busy=!1,i.removeAttribute(`aria-busy`)}))};return i.addEventListener(`click`,c),o.detach=()=>i.removeEventListener(`click`,c),s(o,r),o},l=t=>{let n=t.action,r;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(n){return e.reportError(n,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(oi,t.id),r.element.toggleAttribute(si,n.disableWhenStreaming===!0),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:`bar`}):null},u=(e,t)=>{if(e.builtIn){let t=e.builtIn.element;return t?{resolved:e,element:t,owned:!1,managed:e.builtIn.managed===!0,busy:!1,visible:!0,mode:`bar`}:null}let n=e.action;return n?_i(n)?l(e):c(e,t):null},d=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(n){e.reportError(n,{actionId:t.resolved.id})}t.element.remove()}},f=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(!r.managed)continue;let i=null;for(let r=n+1;r<t.length;r++){let n=t[r];if(!n.managed&&n.element.parentElement===e){i=n.element;break}}i?(r.element.parentElement!==e||r.element.nextSibling!==i)&&e.insertBefore(r.element,i):e.lastChild!==r.element&&e.appendChild(r.element)}},h=(e,t)=>{if(e.button){e.button.disabled=t;return}if(!e.owned)return;let n=e.element;n.toggleAttribute(`data-disabled`,t),n.setAttribute(`aria-disabled`,t?`true`:`false`);let r=n instanceof HTMLButtonElement||n instanceof HTMLSelectElement||n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n:n.querySelector(`button, select, input, textarea`);r&&(r.disabled=t)},g=null,_=null,v=null,b=0,x=()=>{let t=e.getOverflow?.();return t?.enabled===!0?t:void 0},S=()=>(g?g.setLabel(e.getOverflowLabel?.()??`More actions`):g=ii({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:a}),g),C=e=>{_!==e&&(v?.disconnect(),_=e,b=ui(e),typeof ResizeObserver<`u`&&(v=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??ui(e);n!==b&&(b=n,k())}),v.observe(e)))},w=(e,t)=>{let n=li(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=b||ui(t);return r>0&&r<n},T=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=ci(e.resolved.id);return n&&t.includeBuiltIns?.includes(n)?`menu`:`bar`}let r=e.resolved.presentation;return r===`overflow`||r===`auto`&&n?`menu`:`bar`},E=e=>{let t=e.menuSlot;if(!t)return;if(!xi(e.element)){e.menuLabel?.remove(),e.menuLabel=void 0;return}let n=yi(e.element);n?(e.menuLabel||=j(`span`,`persona-composer-overflow-menu__label`),e.menuLabel.textContent!==n&&(e.menuLabel.textContent=n),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},D=(e,n)=>{if(e.mode===n)return e;let r=e.resolved.action;if(r&&!_i(r)){d(e),t.delete(e.resolved.id);let r=c(e.resolved,n);return t.set(e.resolved.id,r),r}if(n===`menu`){let t=A(`div`,{className:`persona-composer-overflow-menu__slot`,attrs:{role:`none`,[p]:``}});t.appendChild(e.element),m(vi(e.element)),e.menuSlot=t;let n=t=>{let n=vi(e.element);if(n.disabled)return;let r=t.target===n||n.contains(t.target);g?.close(!0),r||n.click()};t.addEventListener(`click`,n,!0),e.detachMenuSlot=()=>t.removeEventListener(`click`,n,!0),e.managed=!0,E(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=n,e},O=(e,t)=>{let n=t.map(e=>e.menuSlot??e.element);for(n.forEach((t,n)=>{let r=e.children[n];r!==t&&(r?e.insertBefore(t,r):e.appendChild(t))});e.children.length>n.length;)e.lastElementChild?.remove()},k=()=>{if(i)return;let n=e.getBindings();if(!n)return;let a=e.getState(),o=a.phase===`streaming`,s=x();s&&C(n.footer);let c=s?w(s,n.footer):!1,l={start:[],end:[]},u=[];for(let e of r){let n=t.get(e.id);if(!n)continue;let r=e.action,i=!r||hi(r.visible,a,!0)&&Y(r.visibility,a);if(n.visible!==i&&(n.visible=i,!i&&n.managed&&(n.menuSlot??n.element).remove()),i){if(n=D(n,T(n,s,c)),r){let e=hi(r.disabled,a,!1)||r.disableWhenStreaming===!0&&o;h(n,e),!_i(r)&&r.pressed!==void 0&&n.button?.setAttribute(`aria-pressed`,r.pressed?`true`:`false`)}n.mode===`menu`?(E(n),u.push(n)):l[e.placement].push(n)}}if(u.length>0){let e=S();O(e.panel,u),e.setItems(u.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(s?.order)?s?.order:ai.overflow,n=l.start.findIndex(e=>e.resolved.order>t),r={resolved:{id:`core:overflow`,placement:`start`,presentation:`bar`,order:t,sequence:-1,source:`core`},element:e.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:`bar`};l.start.splice(n<0?l.start.length:n,0,r)}else g&&(g.close(),g.trigger.remove(),g.setItems([]));f(n.actionsStart,l.start),f(n.actionsEnd,l.end)};return{resolve:()=>{if(i)return;let n=pi(e.collect()),a=new Set(n.map(e=>e.id));for(let[e,n]of t)a.has(e)||(d(n),t.delete(e));for(let e of n){let n=t.get(e.id);if(!n){let n=u(e,`bar`);n&&t.set(e.id,n);continue}let r=n.resolved.action,i=e.action;if(!!r!=!!i||r&&i&&_i(r)!==_i(i)||r&&i&&_i(r)&&_i(i)&&r.render!==i.render){d(n),t.delete(e.id);let r=u(e,n.mode);r&&t.set(e.id,r)}else n.resolved=e,e.builtIn?(n.managed=e.builtIn.managed===!0||n.mode===`menu`,e.builtIn.element&&n.mode===`bar`&&(n.element=e.builtIn.element)):i&&!_i(i)?s(n,i):i&&n.element.toggleAttribute(si,i.disableWhenStreaming===!0)}r=n,k()},sync:k,getResolved:()=>r,getOverflowMenu:()=>g,destroy:()=>{if(!i){i=!0,v?.disconnect(),v=null,_=null;for(let e of t.values())d(e);t.clear(),g?.destroy(),g=null,r=[]}}}}const Ci=[`--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`],wi=()=>({wrapper:A(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:A(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function Ti(e){let t=e.label??`Model`,n=e.presentation??`native`,r=null,i=t=>{let n=e.getSelectedModelId();return t.find(e=>e.id===n)??t[0]},a=()=>{let n=A(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":t,"data-persona-composer-model-picker":``}}),a=``,o=()=>{let t=e.getModels(),r=t.map(e=>`${e.id}:${e.label}`).join(`|`);r!==a&&(a=r,n.replaceChildren(...t.map(e=>{let t=A(`option`,{attrs:{value:e.id}});return t.textContent=e.label,t}))),n.value=i(t)?.id??``};o(),r=o;let s=()=>{n.value&&e.onSelect(n.value)};n.addEventListener(`change`,s);let c=e=>e.stopPropagation();n.addEventListener(`click`,c);let{wrapper:l,chevron:u}=wi();return l.append(n,u),{element:l,destroy:()=>{r===o&&(r=null),n.removeEventListener(`change`,s),n.removeEventListener(`click`,c)}}},o=()=>{let n=A(`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`}}),a=j(`span`,`persona-composer-model-picker-label`),o=j(`span`,`persona-composer-model-picker-suffix`);n.append(a,o);let s=A(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":t,"data-persona-composer-model-menu":``}}),c=/* @__PURE__ */ new Map,l=``,u=null,d=()=>u?.isOpen===!0,f=(e=!1)=>{d()&&(u?.close(),n.setAttribute(`aria-expanded`,`false`),e&&n.focus())},p=e=>{let t=[...c.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(d())return;u||=Ct({anchor:n,content:s,placement:`top-start`,offset:6,onDismiss:()=>n.setAttribute(`aria-expanded`,`false`)}),ee(n,s,Ci),u.open(),n.setAttribute(`aria-expanded`,`true`);let r=[...c.keys()].indexOf(i(e.getModels())?.id??``);p(t??(r>=0?r:0))},h=t=>{f(!0),e.onSelect(t)},g=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&h(t)},_=e=>{let t=A(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":e.id}});if(e.icon){let n=M(e.icon,16,`currentColor`,1.5);if(n){let e=j(`span`,`persona-composer-model-option-icon`);e.appendChild(n),t.appendChild(e)}}let n=j(`span`,`persona-composer-model-option-body`),r=j(`span`,`persona-composer-model-option-label`);if(r.textContent=e.label,n.appendChild(r),e.description){let t=j(`span`,`persona-composer-model-option-description`);t.textContent=e.description,n.appendChild(t)}t.appendChild(n);let i=j(`span`,`persona-composer-model-option-check`);i.setAttribute(`aria-hidden`,`true`);let a=M(`check`,16,`currentColor`,2);return a&&i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,g),t},v=()=>{let r=e.getModels(),u=r.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(u!==l){l=u;for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),s.replaceChildren(...r.map(e=>{let t=_(e);return c.set(e.id,t),t}))}let d=i(r);for(let[e,t]of c)t.setAttribute(`aria-selected`,String(e===d?.id));a.textContent=d?.label??``;let f=e.getSuffix?.()??``;o.textContent=f,n.setAttribute(`aria-label`,[t,[d?.label,f].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};v(),r=v;let y=e=>{e.preventDefault(),e.stopPropagation(),d()?f(!0):m()},b=e=>{e.key===`ArrowDown`?(e.preventDefault(),d()?p(0):m(0)):e.key===`ArrowUp`&&(e.preventDefault(),d()?p(-1):m(-1))},x=e=>{let t=[...c.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),p(n+1);return;case`ArrowUp`:e.preventDefault(),p(n-1);return;case`Home`:e.preventDefault(),p(0);return;case`End`:e.preventDefault(),p(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),f(!0);return;case`Tab`:f(!0);return}};n.addEventListener(`click`,y),n.addEventListener(`keydown`,b),s.addEventListener(`keydown`,x);let{wrapper:S,chevron:C}=wi();return S.append(n,C),{element:S,destroy:()=>{r===v&&(r=null),n.removeEventListener(`click`,y),n.removeEventListener(`keydown`,b),s.removeEventListener(`keydown`,x);for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),u?.destroy(),u=null,s.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:n===`popover`?`bar`:`auto`,label:t,render:()=>n===`popover`?o():a()},repaint:()=>r?.()}}function Ei(e){let t=e.row,n=``,r=!1,i=new Set(e.initialIds??[]),a=t=>{let n=A(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=j(`span`,`persona-mention-chip-icon`),r=M(t.iconName,12,`currentColor`,1.5);r&&e.appendChild(r),n.appendChild(e)}let r=j(`span`,`persona-mention-chip-label`);r.textContent=t.shortLabel??t.label,n.appendChild(r);let i=A(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label}`}}),a=M(`x`,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=`×`,i.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),e.onRemove(t.id)}),n.appendChild(i),n},o=()=>Array.from(t.querySelectorAll(`:scope > [data-persona-composer-mode]`)),s=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let n=()=>{e.remove(),xt(t)},r=t.ownerDocument.defaultView,i=typeof r?.getComputedStyle==`function`?r.getComputedStyle(e).animationName:``;!i||i===`none`?n():(e.addEventListener(`animationend`,n,{once:!0}),e.addEventListener(`animationcancel`,n,{once:!0}))},c=()=>{for(let e of o())e.remove()};return{element:t,render:(e,c)=>{if(r)return;let l=c.filter(t=>e.includes(t.id)),u=l.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===n)return;n=u;let d=/* @__PURE__ */ new Map;for(let e of o()){let t=e.getAttribute(`data-persona-composer-mode`);t&&l.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?d.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||s(e)}let f=t.firstChild;for(let e of l){let n=d.get(e.id);n||(n=a(e),i.has(e.id)||(n.setAttribute(`data-persona-chip-enter`,``),n.addEventListener(`animationend`,()=>n?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),i.delete(e.id),n!==f&&t.insertBefore(n,f),f=n.nextSibling}xt(t)},destroy:()=>{r=!0,c(),xt(t)}}}const Di=e=>`core:mode:${e}`,Oi=e=>Math.min(300+e,499),ki=e=>`core:mode-group:${e}`;function Ai(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function ji(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function Mi(e,t){return e?.length?e.filter(e=>!Ai(e.groupId,t)&&!ji(e.groupId,t)):[]}const Ni=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function Pi(e,t,n,r){let i=n.find(e=>e.id===t);if(!i)return[...e];let a=e.includes(t),o=new Set(e);if(a)o.delete(t);else{if(Ni(i,r)===`single`){let e=n.filter(e=>e.groupId===i.groupId).map(e=>e.id);o=new Set([...o].filter(t=>!e.includes(t)))}o.add(t)}return n.filter(e=>o.has(e.id)).map(e=>e.id)}function Fi(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function Ii(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function Li(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}function Ri(e){let t=null;return{action:{id:ki(e.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:e.getGroup()?.label??e.groupId,render:()=>{let n=A(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":e.groupId}}),r=/* @__PURE__ */ new Map,i=``,a=t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getAttribute(`data-persona-composer-mode`);n&&(e.getActiveIds().includes(n)&&e.getGroup()?.selection===`single`||e.onSelect(n))},o=e=>{let t=A(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let n=M(e.iconName,16,`currentColor`,1.5);n&&t.appendChild(n)}let n=j(`span`,`persona-composer-segmented-label`);return n.textContent=e.shortLabel??e.label,t.appendChild(n),t.addEventListener(`click`,a),t},s=()=>{let t=e.getGroup();t?.label?(n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,t.label)):(n.removeAttribute(`role`),n.removeAttribute(`aria-label`));let s=e.getModes(),c=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(c!==i){i=c;for(let e of r.values())e.removeEventListener(`click`,a);r.clear();let e=s.map(e=>{let t=o(e);return r.set(e.id,t),t});n.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of r)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return s(),t=s,{element:n,destroy:()=>{t===s&&(t=null);for(let e of r.values())e.removeEventListener(`click`,a);r.clear()}}}},repaint:()=>t?.()}}function zi(e){let t=A(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=j(`span`,`persona-composer-quote-bar`),i=j(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=j(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=A(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=gr(n.text),i.appendChild(a);let o=A(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=M(`x`,12,`currentColor`,2);s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(r,i,o)};return{element:t,render:e=>{if(r)return;let a=e?`${e.sourceLabel??``}${e.text}`:``;a!==n&&(n=a,e?(i(e),t.style.display=`flex`):(t.replaceChildren(),t.style.display=`none`))},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}function Bi(e){let t=A(`div`,{className:`persona-composer-pending`,attrs:{"data-persona-composer-pending":``}});t.style.display=`none`;let n,r=!1,i=(e,t,n,r)=>{let i=A(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=M(e,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=t,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},a=e=>{let t=gr(e.text??``,90);if(t)return t;let n=e.contentParts?.length??0;return n>0?n===1?`1 attachment`:`${n} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(`, `):`Queued message`};return{element:t,render:o=>{if(r||o===n)return;if(n=o,!o){t.replaceChildren(),t.style.display=`none`;return}let s=j(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=A(`div`,{className:`persona-composer-pending-text`,attrs:{"data-persona-composer-pending-text":``}});c.textContent=a(o),t.replaceChildren(s,c,i(`pencil`,e.editLabel??`Edit queued message`,`data-persona-composer-pending-edit`,e.onEdit),i(`x`,e.removeLabel??`Remove queued message`,`data-persona-composer-pending-remove`,e.onRemove)),t.style.display=`flex`},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}function Vi(e){let t=A(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=A(`textarea`,{className:`persona-message-edit-input`,attrs:{rows:`1`,dir:`auto`,"aria-label":`Edit message`,"data-persona-message-edit-input":``}});n.value=e.initialText;let r=()=>{n.style.height=`auto`,n.style.height=`${n.scrollHeight}px`};n.addEventListener(`input`,r);let i=j(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=A(`button`,{className:`persona-message-edit-button ${t}`,attrs:{type:`button`,[n]:``},text:e});return i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},o=()=>{let t=n.value.trim();t&&e.onSave(t)};return i.append(a(e.cancelLabel??`Cancel`,`persona-message-edit-cancel`,`data-persona-message-edit-cancel`,e.onCancel),a(e.saveLabel??`Send`,`persona-message-edit-save`,`data-persona-message-edit-save`,o)),n.addEventListener(`keydown`,t=>{t.key===`Escape`?(t.preventDefault(),t.stopPropagation(),e.onCancel()):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),o())}),t.append(n,i),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let e=n.value.length;n.setSelectionRange(e,e),r()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Hi(e){let t=e.text??``;if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function Ui(e,t){if(!e||typeof e.text!=`string`)return;let n=new Set(t.mentionSourceIds),r=(e.mentionRefs??[]).filter(e=>n.has(e.sourceId)),i=r.length===(e.mentionRefs?.length??0)&&r.length>0,a=new Set(t.modes.map(e=>e.id)),o=(e.activeModeIds??[]).filter(e=>a.has(e)),s=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...i?{mentionRefs:r}:{},...i&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...s?{selectedModelId:s}:{},...o.length?{activeModeIds:o}:{},...e.quote?.text?{quote:e.quote}:{}}}function Wi(e){let t=e.delay??500,n=null,r=!1,i=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{r||(i(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{r||n===null||(i(),e.write())},cancel:i,destroy:()=>{r=!0,i()}}}function Gi(e){return e.wrapped||e.text.includes(`
|
|
12
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function Ki(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function qi(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-o>a*1.5}function Ji(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function Yi(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const Xi=e=>typeof e?.then==`function`;function Zi(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function Qi(e,t,n){let r;try{r=e(Ji(t),{signal:n})}catch(e){return{status:`error`,error:e}}return Xi(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:Zi(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):Zi(t,r)}const $i=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),ea={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`},ta=`16px`,na=`transparent`,ra={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:(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?`0px`:`${t/4}rem`;return e})(),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`}},ia={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`}},aa={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:O,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:ta,canvasBackground:na,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`}}},oa=ra.colors.gray,sa={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},ca={...ra,colors:{...ra.colors,gray:oa}},la={...ra,colors:{...ra.colors,gray:sa},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},ua=ia,da={...ia,colors:{...ia.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...ia.typography,fontSize:`14px`,lineHeight:`1.5`}},fa=aa,pa={...aa,launcher:ea,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:{...aa.input,borderRadius:`palette.radius.full`},introCard:{...aa.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...aa.suggestion.chip,fontWeight:`400`},card:{...aa.suggestion.card,fontWeight:`400`},list:{...aa.suggestion.list,fontWeight:`400`}},panel:{...aa.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...aa.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:{...aa.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...aa.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:{...aa.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},composer:{...aa.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)`}},ma=e=>a({future:e}),X=e=>ma(e)===`v5`?{palette:la,semantic:da,components:pa}:{palette:ca,semantic:ua,components:fa};function ha(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?ha(e,r):r}function ga(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=ha(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function _a(e){let t=[],n=[];return e.palette||t.push({path:`palette`,message:`Theme must include a palette`,severity:`error`}),e.semantic||n.push({path:`semantic`,message:`No semantic tokens defined - defaults will be used`,severity:`warning`}),e.components||n.push({path:`components`,message:`No component tokens defined - defaults will be used`,severity:`warning`}),{valid:t.length===0,errors:t,warnings:n}}function va(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?va(t,r):r}return n}function ya(e,t){return t?va(e,t):e}function ba(e,t={}){let n=X(t.future),r={palette:n.palette,semantic:n.semantic,components:n.components},i={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:ya(r.components,e?.components)},a=e?.components?.activity;for(let e of[`toolBubble`,`reasoningBubble`])for(let t of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[t]!==void 0&&(i.components[e][t]=a[t]);let o=e?.components?.collapsibleWidget?.surface;o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=e?.components?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=_a(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const xa=e=>e.trim()===`0`?`0px`:e,Sa=`--persona-`,Ca=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},wa=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[Sa+n],t!==void 0)break;t!==void 0&&(e[Sa+n]=t)}};function Ta(e){let t=ga(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}wa(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 r=n[`--persona-components-launcher-foreground`];n[`--persona-launcher-fg-muted`]=r&&r!==n[`--persona-primary`]?`color-mix(in srgb, ${r} 70%, transparent)`:n[`--persona-muted`],wa(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`]]),wa(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`]}`,wa(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`]??`16px`,n[`--persona-panel-canvas-bg`]=n[`--persona-components-panel-canvasBackground`]??`transparent`,wa(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`]]),wa(n,[[`header-bg`,`components-header-background`,`surface`]]);let i=n[`--persona-header-bg`],a=n[`--persona-components-header-foreground`],o=a?`color-mix(in srgb, ${a} 72%, ${i})`:void 0;n[`--persona-header-border`]=n[`--persona-components-header-border`]??(a?`color-mix(in srgb, ${a} 14%, ${i})`:void 0)??n[`--persona-divider`],wa(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`]??a??n[`--persona-primary`],n[`--persona-header-subtitle-fg`]=n[`--persona-components-header-subtitle-color`]??n[`--persona-components-header-subtitleForeground`]??o??n[`--persona-text-muted`],n[`--persona-header-action-icon-fg`]=n[`--persona-components-header-actionIconForeground`]??o??n[`--persona-muted`],wa(n,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=20px`]]);let s=e.components?.header;s?.shadow&&(n[`--persona-header-shadow`]=s.shadow),s?.borderBottom&&(n[`--persona-header-border-bottom`]=s.borderBottom),s?.minHeight&&(n[`--persona-header-min-height`]=s.minHeight);let c=n[`--persona-components-history-railHeader-background`];c&&(n[`--persona-history-rail-header-bg`]=c);let l=n[`--persona-components-history-railHeader-border`];l&&(n[`--persona-history-rail-header-border`]=l);let u=n[`--persona-components-history-railHeader-minHeight`];u&&(n[`--persona-history-rail-header-min-height`]=u);for(let[e,t]of[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]]){let r=n[`--persona-components-history-overlay-${e}`];r&&(n[`--persona-history-overlay-${t}`]=r)}for(let[e,t]of[[`background`,`bg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-history-menu-${e}`];r&&(n[`--persona-history-menu-${t}`]=r)}let d=e.components?.history?.motion;if(d){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(d.enterDurationMs);t!==void 0&&(n[`--persona-history-enter-ms`]=t);let r=e(d.exitDurationMs);r!==void 0&&(n[`--persona-history-exit-ms`]=r),d.enterEasing&&(n[`--persona-history-enter-easing`]=d.enterEasing),d.exitEasing&&(n[`--persona-history-exit-easing`]=d.exitEasing)}let f=n[`--persona-components-history-dangerForeground`];f&&(n[`--persona-history-danger-fg`]=f),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 e of[`scrim`,`shadow`]){let t=n[`--persona-components-history-confirm-${e}`];t&&(n[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]]){let r=n[`--persona-components-tooltip-${e}`];r&&(n[`--persona-tooltip-${t}`]=r)}e.components?.tooltip?.arrow===!1&&(n[`--persona-tooltip-arrow-display`]=`none`);for(let[e,t]of[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-messageActions-${e}`];r&&(n[`--persona-message-action-${t}`]=r)}wa(n,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let p=n[`--persona-components-introCard-background`],m=n[`--persona-components-introCard-shadow`],h=(!p||p===`transparent`||p===`none`)&&(!m||m===`none`),g=n[`--persona-components-introCard-padding`]??`1.5rem`;n[`--persona-intro-card-padding`]=h&&g===`1.5rem`?`1.5rem 0`:g,wa(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`]]),wa(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 _=n[`--persona-components-markdown-heading-h1-fontSize`];_&&(n[`--persona-md-h1-size`]=_);let v=n[`--persona-components-markdown-heading-h1-fontWeight`];v&&(n[`--persona-md-h1-weight`]=v);let y=n[`--persona-components-markdown-heading-h2-fontSize`];y&&(n[`--persona-md-h2-size`]=y);let b=n[`--persona-components-markdown-heading-h2-fontWeight`];b&&(n[`--persona-md-h2-weight`]=b);let x=n[`--persona-components-markdown-prose-fontFamily`];x&&x!==`inherit`&&(n[`--persona-md-prose-font-family`]=x),wa(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`]]),wa(n,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),wa(n,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),wa(n,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),wa(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`]]);for(let[e,t]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=n[`--persona-components-collapsibleWidget-${e}`]??n[`--persona-${t}`];r!==void 0&&(n[`--persona-cw-${e}`]=r,n[`--cw-${e}`]=r)}wa(n,[[`message-border`,`components-message-border`,`border`]]),wa(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 S=e.components,C=S?.iconButton;C&&(C.background&&(n[`--persona-icon-btn-bg`]=C.background),C.border&&(n[`--persona-icon-btn-border`]=C.border),C.color&&(n[`--persona-icon-btn-color`]=C.color),C.padding&&(n[`--persona-icon-btn-padding`]=C.padding),C.borderRadius&&(n[`--persona-icon-btn-radius`]=C.borderRadius),C.hoverBackground&&(n[`--persona-icon-btn-hover-bg`]=C.hoverBackground),C.hoverColor&&(n[`--persona-icon-btn-hover-color`]=C.hoverColor),C.activeBackground&&(n[`--persona-icon-btn-active-bg`]=C.activeBackground),C.activeBorder&&(n[`--persona-icon-btn-active-border`]=C.activeBorder));let w=S?.labelButton;w&&(w.background&&(n[`--persona-label-btn-bg`]=w.background),w.border&&(n[`--persona-label-btn-border`]=w.border),w.color&&(n[`--persona-label-btn-color`]=w.color),w.padding&&(n[`--persona-label-btn-padding`]=w.padding),w.borderRadius&&(n[`--persona-label-btn-radius`]=w.borderRadius),w.hoverBackground&&(n[`--persona-label-btn-hover-bg`]=w.hoverBackground),w.fontSize&&(n[`--persona-label-btn-font-size`]=w.fontSize),w.gap&&(n[`--persona-label-btn-gap`]=w.gap));let T=S?.toggleGroup;T&&(T.gap&&(n[`--persona-toggle-group-gap`]=T.gap),T.borderRadius&&(n[`--persona-toggle-group-radius`]=T.borderRadius));let E=S?.artifact;if(E?.toolbar){let t=E.toolbar;t.iconHoverColor&&(n[`--persona-artifact-toolbar-icon-hover-color`]=t.iconHoverColor),t.iconHoverBackground&&(n[`--persona-artifact-toolbar-icon-hover-bg`]=t.iconHoverBackground),t.iconPadding&&(n[`--persona-artifact-toolbar-icon-padding`]=t.iconPadding),t.iconBorderRadius&&(n[`--persona-artifact-toolbar-icon-radius`]=t.iconBorderRadius),t.iconBorder&&(n[`--persona-artifact-toolbar-icon-border`]=t.iconBorder),t.toggleGroupGap&&(n[`--persona-artifact-toolbar-toggle-group-gap`]=xa(t.toggleGroupGap)),t.toggleBorderRadius&&(n[`--persona-artifact-toolbar-toggle-radius`]=t.toggleBorderRadius),t.toggleGroupPadding&&(n[`--persona-artifact-toolbar-toggle-group-padding`]=xa(t.toggleGroupPadding)),t.toggleGroupBorder&&(n[`--persona-artifact-toolbar-toggle-group-border`]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(n[`--persona-artifact-toolbar-toggle-group-radius`]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(n[`--persona-artifact-toolbar-toggle-group-bg`]=ha(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(n[`--persona-artifact-toolbar-copy-bg`]=t.copyBackground),t.copyBorder&&(n[`--persona-artifact-toolbar-copy-border`]=t.copyBorder),t.copyColor&&(n[`--persona-artifact-toolbar-copy-color`]=t.copyColor),t.copyBorderRadius&&(n[`--persona-artifact-toolbar-copy-radius`]=xa(t.copyBorderRadius)),t.copyPadding&&(n[`--persona-artifact-toolbar-copy-padding`]=t.copyPadding),t.copyMenuBackground&&(n[`--persona-artifact-toolbar-copy-menu-bg`]=t.copyMenuBackground,n[`--persona-dropdown-bg`]=n[`--persona-dropdown-bg`]??t.copyMenuBackground),t.copyMenuBorder&&(n[`--persona-artifact-toolbar-copy-menu-border`]=t.copyMenuBorder,n[`--persona-dropdown-border`]=n[`--persona-dropdown-border`]??t.copyMenuBorder),t.copyMenuShadow&&(n[`--persona-artifact-toolbar-copy-menu-shadow`]=t.copyMenuShadow,n[`--persona-dropdown-shadow`]=n[`--persona-dropdown-shadow`]??t.copyMenuShadow),t.copyMenuBorderRadius&&(n[`--persona-artifact-toolbar-copy-menu-radius`]=t.copyMenuBorderRadius,n[`--persona-dropdown-radius`]=n[`--persona-dropdown-radius`]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(n[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=t.copyMenuItemHoverBackground,n[`--persona-dropdown-item-hover-bg`]=n[`--persona-dropdown-item-hover-bg`]??t.copyMenuItemHoverBackground),t.iconBackground&&(n[`--persona-artifact-toolbar-icon-bg`]=t.iconBackground),t.toolbarBorder&&(n[`--persona-artifact-toolbar-border`]=t.toolbarBorder)}if(E?.tab){let e=E.tab;e.background&&(n[`--persona-artifact-tab-bg`]=e.background),e.activeBackground&&(n[`--persona-artifact-tab-active-bg`]=e.activeBackground),e.activeBorder&&(n[`--persona-artifact-tab-active-border`]=e.activeBorder),e.borderRadius&&(n[`--persona-artifact-tab-radius`]=e.borderRadius),e.textColor&&(n[`--persona-artifact-tab-color`]=e.textColor),e.hoverBackground&&(n[`--persona-artifact-tab-hover-bg`]=e.hoverBackground),e.listBackground&&(n[`--persona-artifact-tab-list-bg`]=e.listBackground),e.listBorderColor&&(n[`--persona-artifact-tab-list-border-color`]=e.listBorderColor),e.listPadding&&(n[`--persona-artifact-tab-list-padding`]=e.listPadding)}if(E?.pane){let t=E.pane;t.toolbarBackground&&(n[`--persona-artifact-toolbar-bg`]=ha(e,t.toolbarBackground)??t.toolbarBackground)}if(E?.card){let e=E.card;e.background&&(n[`--persona-artifact-card-bg`]=e.background),e.border&&(n[`--persona-artifact-card-border`]=e.border),e.borderRadius&&(n[`--persona-artifact-card-radius`]=e.borderRadius),e.hoverBackground&&(n[`--persona-artifact-card-hover-bg`]=e.hoverBackground),e.hoverBorderColor&&(n[`--persona-artifact-card-hover-border`]=e.hoverBorderColor)}if(E?.inline){let t=E.inline;t.background&&(n[`--persona-artifact-inline-bg`]=ha(e,t.background)??t.background),t.border&&(n[`--persona-artifact-inline-border`]=t.border),t.borderRadius&&(n[`--persona-artifact-inline-radius`]=t.borderRadius),t.chromeBackground&&(n[`--persona-artifact-inline-chrome-bg`]=ha(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(n[`--persona-artifact-inline-chrome-border`]=ha(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(n[`--persona-artifact-inline-title-color`]=ha(e,t.titleColor)??t.titleColor),t.mutedColor&&(n[`--persona-artifact-inline-muted-color`]=ha(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(n[`--persona-artifact-inline-frame-height`]=t.frameHeight)}let D=S?.code;D&&(D.keywordColor&&(n[`--persona-code-keyword-color`]=D.keywordColor),D.stringColor&&(n[`--persona-code-string-color`]=D.stringColor),D.commentColor&&(n[`--persona-code-comment-color`]=D.commentColor),D.numberColor&&(n[`--persona-code-number-color`]=D.numberColor),D.tagColor&&(n[`--persona-code-tag-color`]=D.tagColor),D.attrColor&&(n[`--persona-code-attr-color`]=D.attrColor),D.propertyColor&&(n[`--persona-code-property-color`]=D.propertyColor),D.lineNumberColor&&(n[`--persona-code-line-number-color`]=D.lineNumberColor),D.gutterBorderColor&&(n[`--persona-code-gutter-border-color`]=D.gutterBorderColor),D.background&&(n[`--persona-code-bg`]=ha(e,D.background)??D.background));let O=n[`--persona-surface`],k=n[`--persona-container`],ee=n[`--persona-palette-colors-gray-100`]??`#f3f4f6`,te=n[`--persona-palette-colors-gray-200`]??`#e5e7eb`,ne=n[`--persona-palette-colors-gray-300`]??`#d1d5db`,re=!k||k===O,ie=Ca(O??n[`--persona-background`]),ae=re&&ie!==void 0&&ie<.179,oe=ae?`rgba(255, 255, 255, 0.08)`:ee,se=ae?`rgba(255, 255, 255, 0.12)`:te,ce=ae?`rgba(255, 255, 255, 0.16)`:ne,le=re?oe:k,ue=re?se:k;return n[`--persona-icon-btn-hover-bg`]=n[`--persona-icon-btn-hover-bg`]??le,n[`--persona-icon-btn-active-bg`]=n[`--persona-icon-btn-active-bg`]??ue,re&&(n[`--persona-icon-btn-active-border`]=n[`--persona-icon-btn-active-border`]??ce),n[`--persona-label-btn-hover-bg`]=n[`--persona-label-btn-hover-bg`]??le,n[`--persona-artifact-tab-hover-bg`]=n[`--persona-artifact-tab-hover-bg`]??le,n[`--persona-artifact-card-hover-bg`]=n[`--persona-artifact-card-hover-bg`]??le,n}const Ea=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),Da=(e,t)=>{if(!t||!Ea(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(Ra(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:a(t)===`v5`?`400px`:`420px`}}}:e},Oa={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`}}},ka={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)`}}}},Aa=Oa,ja={...Aa,colors:{...Aa.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`}}},Ma=ka,Na={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:{...ka.components,button:{...ka.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:{...ka.components?.eventStream,badge:{...ka.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`}}}}},Pa=e=>a({future:e})===`v5`?{palette:ja,components:Na}:{palette:Aa,components:Ma},Fa=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},Ia=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,La=e=>{let t=e?.colorScheme??`light`;return t===`light`?`light`:t===`dark`?`dark`:Ia()},Ra=e=>La(e),za=(e,t={})=>ba(e,t),Ba=(e,t={})=>{let n=Pa(t.future),r=_(n.components,e??{})??{};return ba({...r,palette:{...r.palette,colors:a(t)===`v5`?_(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},Va=e=>{let t=Ra(e),n=Fa(e?.theme),r=$i(e)===`circle`?ea:{...fa.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}},i=_({components:{launcher:r}},n),a=Fa(e?.darkTheme);return Da(t===`dark`?Ba(_(i??{},a??{}),{future:e?.future}):za(i,{future:e?.future}),e)},Ha=e=>Ta(e),Ua=(e,t)=>{let n=Va(t),r=Ha(n);for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute(`data-persona-color-scheme`,Ra(t)),e.setAttribute(`data-persona-defaults`,a(t))},Wa=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(Ia())});n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),t.push(()=>n.disconnect())}if(typeof window<`u`&&window.matchMedia){let n=window.matchMedia(`(prefers-color-scheme: dark)`),r=()=>e(Ia());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},Ga=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),Ka=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,qa=e=>{if(typeof e!=`string`)return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},Ja=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight),Ya=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;an.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&!t.hasAttribute(`data-preserve-animation`)||t instanceof HTMLElement&&t.hasAttribute(`data-preserve-animation`)&&(e.textContent??``)!==(t.textContent??``)?void 0:!1}}}})},Xa=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),Za={index:-1,draft:``};function Qa(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function $a(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??``,e.streaming?`1`:`0`,e.voiceProcessing?`1`:`0`,e.variant??``,e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??``,e.toolCall?.status??``,e.toolCall?.name??``,e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??``,typeof e.toolCall?.args==`string`?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??``,e.contentParts?.length??0,e.stopReason??``,t].join(`\0`)}function eo(){return/* @__PURE__ */ new Map}function to(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function no(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function ro(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}const{setLoader:io,load:ao}=me({fallbackImport:()=>import(`./chunk-Dg7uqL8l.js`)}),oo=ao;function so(e,t=_t){let n=e.style.position,r=e.style.zIndex,i=e.style.isolation,a=getComputedStyle(e),o=a.position===`static`||a.position===``;return o&&(e.style.position=`relative`),e.style.zIndex=String(t),e.style.isolation=`isolate`,()=>{o&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=i}}let co=0,lo=null;function uo(e=document){if(co++,co===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;lo={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:n},t.style.overflow=`hidden`,t.style.position=`fixed`,t.style.top=`-${n}px`,t.style.width=`100%`}let t=!1;return()=>{if(!t&&(t=!0,co=Math.max(0,co-1),co===0&&lo)){let t=e.body,n=e.defaultView??window;t.style.overflow=lo.originalOverflow,t.style.position=lo.originalPosition,t.style.top=lo.originalTop,t.style.width=lo.originalWidth,n.scrollTo(0,lo.scrollY),lo=null}}}const fo={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},po=e=>(e?.launcher?.mountMode??`floating`)===`docked`,mo=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,ho=e=>{let t=e?.launcher?.dock,n=s(e).dockWidth?t?.width:ha(Va(e),`components.panel.width`);return{side:t?.side??fo.side,width:n??fo.width,animate:t?.animate??fo.animate,reveal:t?.reveal??fo.reveal,maxHeight:t?.maxHeight??fo.maxHeight}},go=e=>e===`followUp`?`follow-up`:e,_o=(e,t=0)=>{if(typeof e==`string`){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:`default`}:null}let n=e.label.trim();if(!n)return null;let r=e.prompt?.trim()||n;return{id:e.id?.trim()||r||`suggestion-${t}`,label:n,prompt:r,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??`default`}},vo=/* @__PURE__ */ new WeakSet,yo=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,bo=e=>{yo()||e.forEach((e,t)=>{typeof e.animate==`function`&&e.animate([{opacity:`0`,transform:`translateY(4px)`},{opacity:`1`,transform:`none`}],{duration:250,delay:t*60,easing:`ease-out`,fill:`backwards`})})},xo=t=>{let{item:n,index:r,surface:i,source:a,variant:o,streaming:s,config:c,plugins:l,chipsConfig:u,session:d,getTextarea:f,eventTarget:p,submitPrompt:m}=t,h=i===`followUp`,g=n.behavior,_=()=>{if(d.isStreaming())return;let e={suggestion:{...n},surface:i,source:a,behavior:g},t=p.dispatchEvent(new CustomEvent(`persona:suggestion:selected`,{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(h&&p.dispatchEvent(new CustomEvent(`persona:suggestReplies:selected`,{detail:{suggestion:n.prompt},bubbles:!0,composed:!0})),!t)return;for(let e of l)if(e.onSuggestionSelect?.({suggestion:{...n},surface:i,source:a,variant:o,config:c})===!1)return;let r=f();g===`fill`?(r.value=n.prompt,r.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),r.focus()):m?m(n.prompt):(r.value=``,d.sendMessage(n.prompt))},v=()=>{let t=j(`button`,`persona-suggestion persona-suggestion--${o}`);if(t.type=`button`,t.disabled=s,t.dataset.suggestionId=n.id,t.dataset.emphasis=n.emphasis,t.dataset.behavior=g,o===`chip`&&(u?.fontWeight&&(t.style.fontWeight=u.fontWeight),u?.paddingX&&(t.style.paddingLeft=u.paddingX,t.style.paddingRight=u.paddingX),u?.paddingY&&(t.style.paddingTop=u.paddingY,t.style.paddingBottom=u.paddingY)),n.icon){let e=M(n.icon,`var(--persona-suggestion-icon-size)`,`currentColor`,1.8);e&&(e.classList.add(`persona-suggestion__icon`),n.iconColor&&(e.style.color=n.iconColor),t.appendChild(e))}let r=j(`span`,`persona-suggestion__copy`);if(r.appendChild(A(`span`,{className:`persona-suggestion__label`,text:n.label})),n.description&&o!==`chip`&&r.appendChild(A(`span`,{className:`persona-suggestion__description`,text:n.description})),t.appendChild(r),o!==`chip`){let n=e(Gt,16,`currentColor`,1.8);n&&(n.classList.add(`persona-suggestion__arrow`),t.appendChild(n))}return t.addEventListener(`click`,_),t},y=null;for(let e of l)if(e.renderSuggestion&&(y=e.renderSuggestion({suggestion:{...n},index:r,surface:i,source:a,variant:o,streaming:s,config:c,defaultRenderer:v,select:_}),y))break;return y??=v(),y.dataset.suggestionId||=n.id,y.dataset.behavior||=g,y.dataset.emphasis||=n.emphasis,y instanceof HTMLButtonElement||y.setAttribute(`aria-disabled`,s?`true`:`false`),y},So=e=>{let t=[],n=[],r=null,i=null,a=()=>{e.removeAttribute(`data-scroll-left`),e.removeAttribute(`data-scroll-right`)},o=()=>{if(i=null,e.hidden||e.dataset.variant!==`chip`||e.dataset.overflow!==`scroll`){a();return}let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1){a();return}let n=getComputedStyle(e).direction===`rtl`,r=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),o=r<=4,s=r>=t-4,c=n?!s:!o,l=n?!o:!s;e.toggleAttribute(`data-scroll-left`,c),e.toggleAttribute(`data-scroll-right`,l)},s=()=>{i!==null||typeof requestAnimationFrame!=`function`?typeof requestAnimationFrame!=`function`&&o():i=requestAnimationFrame(o)};e.addEventListener(`scroll`,s,{passive:!0});let c=typeof ResizeObserver==`function`?new ResizeObserver(s):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener(`scroll`,s),c?.disconnect(),i!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),i=null},render:(i,c,l,u,d,f)=>{e.replaceChildren(),t.length=0,n.length=0;let p=f?.source??`config`,m=f?.surface??(p===`config`?`starter`:`followUp`),h=m===`followUp`,g=f?.variant??`chip`,_=f?.behavior??`send`,v=f?.overflow??`wrap`,y=f?.config??{},b=f?.plugins??[],x=typeof f?.maxItems==`number`?Math.max(0,Math.floor(f.maxItems)):void 0,S=h?`followUps`:`starters`;!vo.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(vo.add(y),console.info(`[persona] suggestions.${S}.overflow applies to the "chip" variant only; the "${g}" variant manages its own stacking.`));let C=e=>e.map(_o).filter(e=>e!==null).map(e=>({...e,behavior:e.behavior??_})),w=C(i??[]);b.forEach(e=>{e.transformSuggestions&&(w=C(e.transformSuggestions({suggestions:w.map(e=>({...e})),surface:m,source:p,config:y})))});let T=x===void 0?w:w.slice(0,x);if(!T.length){e.hidden=!0,r=null,a();return}if(!h&&(u??c.getMessages()).some(e=>e.role===`user`)){e.hidden=!0,r=null;return}e.hidden=!1,e.classList.add(`persona-suggestions`),e.dataset.personaSuggestionSurface=go(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=xo({item:r,index:i,surface:m,source:p,variant:g,streaming:D,config:y,plugins:b,chipsConfig:d,session:c,getTextarea:()=>l,eventTarget:e,submitPrompt:f?.submitPrompt});E.appendChild(a),n.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll(`button`))].forEach(e=>{t.includes(e)||(e.disabled=D,t.push(e))})}),e.appendChild(E),o(),s();let O=JSON.stringify({normalized:T,surface:m,variant:g,source:p});O!==r&&(r=O,bo(n),e.dispatchEvent(new CustomEvent(`persona:suggestion:shown`,{detail:{suggestions:T.map(e=>({...e})),surface:m,source:p,variant:g},bubbles:!0,composed:!0})),h&&e.dispatchEvent(new CustomEvent(`persona:suggestReplies:shown`,{detail:{suggestions:T.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},Co={"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`},wo={x:[1.4,1.05]},To=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,Eo=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=wo[t]??[1,1.5],s=!r;e.classList.toggle(`persona-header-control--glyph`,s),e.classList.toggle(`persona-header-control--sparse`,s&&a!==1);let c=M(t,`${Math.round((parseFloat(r??``)||20)*a)}px`,`currentColor`,o);c?(c.style.display=`block`,s||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((o/1.5).toFixed(4))})`),e.replaceChildren(c)):i&&(e.textContent=i)},Do=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:i,iconName:a,iconText:o,wrapperClassName:s=To,size:c,iconSize:l,color:u,backgroundColor:d,borderWidth:f,borderColor:p,borderRadius:m,paddingX:h,paddingY:g,hidden:_,extraClassName:v,attrs:y}=e,b=j(`div`,s),x=!!(f||p),S=A(`button`,{className:pe(`persona-header-control`,`persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer`,!d&&`persona-bg-transparent hover:persona-bg-gray-100`,!x&&`persona-border-none`,!m&&`persona-rounded-full`,v),attrs:{type:`button`,"aria-label":t,...y},style:{width:c,height:c,minWidth:c,minHeight:c,display:_?`none`:void 0,color:u||Ao.actionIconColor,backgroundColor:d,border:x?`${f||`0px`} solid ${p||`transparent`}`:void 0,borderRadius:m,paddingLeft:h,paddingRight:h,paddingTop:g,paddingBottom:g}});return a?Eo(S,a,{iconSize:l,iconText:o}):o&&(S.textContent=o),b.appendChild(S),n({anchor:S,trigger:b,text:()=>S.getAttribute(`aria-label`)??t,hint:i,enabled:r}),{button:S,wrapper:b}},Oo=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=To,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=Do({ariaLabel:s,tooltip:c,iconName:o.closeButtonIconName??`x`,iconText:o.closeButtonIconText??`×`,wrapperClassName:r,size:i??o.closeButtonSize,iconSize:a,color:o.closeButtonColor,backgroundColor:o.closeButtonBackgroundColor,borderWidth:o.closeButtonBorderWidth,borderColor:o.closeButtonBorderColor,borderRadius:o.closeButtonBorderRadius,paddingX:o.closeButtonPaddingX,paddingY:o.closeButtonPaddingY,hidden:!n});return{button:l,wrapper:u}},ko=(e,t={})=>{let{wrapperClassName:n=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,buttonSize:r,iconSize:i}=t,a=(e?.launcher??{}).clearChat??{},o=a.tooltipText??`Clear chat`,s=a.showTooltip??!0,{button:c,wrapper:l}=Do({ariaLabel:o,tooltip:s,iconName:a.iconName??`refresh-cw`,wrapperClassName:n,size:r??a.size,iconSize:i,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:c,wrapper:l}},Ao={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)`},jo={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)`},Mo={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)`},No=e=>{let{config:t,showClose:n=!0}=e,r=A(`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:Ao.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)))`}}),i=t?.launcher??{},a=i.headerIconSize??`40px`,o=i.closeButtonPlacement??`inline`,s=i.headerIconHidden??!1,c=i.headerIconName,l=A(`div`,{className:`persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl`,style:{height:a,width:a,backgroundColor:`var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))`,color:`var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))`}});if(!s){if(c){let e=parseFloat(a)||24,n=M(c,e*.6,`currentColor`,1);n?(n.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,n.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,l.replaceChildren(n)):l.textContent=t?.launcher?.agentIconText??`💬`}else if(t?.launcher?.iconUrl){let e=j(`img`);e.src=t.launcher.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=a,e.style.width=a,l.replaceChildren(e)}else l.textContent=t?.launcher?.agentIconText??`💬`}let u=j(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=A(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:Ao.titleColor,...jo}}),f=A(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:Ao.subtitleColor,...Mo}});u.append(d,f),s?r.append(u):r.append(l,u);let p=i.clearChat??{},m=p.enabled??!0,h=p.placement??`inline`,g=null,_=null;if(m){let e=ko(t,{wrapperClassName:h===`top-right`?`persona-absolute persona-top-4 persona-z-50`:`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`});g=e.button,_=e.wrapper,h===`top-right`&&(_.style.right=`48px`),h===`inline`&&r.appendChild(_)}let{button:v,wrapper:y}=Oo(t,{showClose:n,wrapperClassName:o===`top-right`?`persona-absolute persona-top-4 persona-right-4 persona-z-50`:m&&h===`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`});return o!==`top-right`&&r.appendChild(y),{header:r,iconHolder:l,headerTitle:d,headerSubtitle:f,closeButton:v,closeButtonWrapper:y,clearChatButton:g,clearChatButtonWrapper:_}},Po=(e,t,n)=>{let r=n?.launcher??{},i=r.closeButtonPlacement??`inline`,a=r.clearChat?.placement??`inline`;e.appendChild(t.header),i===`top-right`&&(e.style.position=`relative`,e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a===`top-right`&&(e.style.position=`relative`,e.appendChild(t.clearChatButtonWrapper))},Fo=e=>{let t=No({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let e=t.headerTitle.parentElement;e&&(e.style.cursor=`pointer`,e.setAttribute(`role`,`button`),e.setAttribute(`tabindex`,`0`),e.addEventListener(`click`,()=>n()),e.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())}))}return t};function Io(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=Do({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?pt(r.shortcut):void 0,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`});if(t.setAttribute(`data-persona-header-action`,r.id),r.shortcut){let e=ht(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=_e({items:r.menuItems,onSelect:e=>n?.(e),anchor:i,position:`bottom-right`});i.appendChild(e.element),t.addEventListener(`click`,t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener(`click`,()=>n?.(r.id));e.appendChild(i)}}const Z={default:Fo,minimal:e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=j(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=Ao.minHeight,s.style.padding=`var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))`,s.style.backgroundColor=`var(--persona-header-bg, var(--persona-surface, #ffffff))`,s.style.borderBottomColor=`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,s.style.boxShadow=`var(--persona-header-shadow, none)`,s.style.borderBottom=`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`;let c=i?.titleMenu,l,u;if(c){let e=Te({label:o.title??`Chat Assistant`,menuItems:c.menuItems,onSelect:t=>{let n=n=>{n===!1&&e.element.dispatchEvent(new CustomEvent(`persona:title-menu-builtin`,{bubbles:!0,composed:!0,detail:{actionId:t}}))},r=c.onSelect(t);r instanceof Promise?r.then(n,()=>{}):n(r)},hover:c.hover,className:``});l=e.element,l.style.color=Ao.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=j(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=j(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=Ao.titleColor,Object.assign(u.style,jo),u.textContent=o.title??`Chat Assistant`,l.appendChild(u),i?.onTitleClick){l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`);let e=i.onTitleClick;l.addEventListener(`click`,t=>{t.target.closest(`button`)||e()}),l.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())})}let e=i?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??`10px`,l.style.padding=e.padding??`6px 4px 6px 12px`,l.style.margin=`-6px 0 -6px -12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.style.width=`fit-content`,l.style.flex=`none`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=e.background??``,l.style.borderColor=e.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}))}s.appendChild(l);let d=`persona-relative persona-inline-flex persona-items-center persona-justify-center`,{button:f,wrapper:p}=Oo(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=j(`div`,`persona-flex persona-items-center persona-gap-1`);c||Io(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=ko(t,{wrapperClassName:e===`top-right`?`persona-absolute persona-top-4 persona-z-50`:d});g=n.button,_=n.wrapper,e===`top-right`?_.style.right=`48px`:m.appendChild(_)}m.appendChild(p),s.appendChild(m);let v=j(`div`);v.style.display=`none`;let y=j(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}}},Lo=e=>Z[e]??Z.default,Ro=(e,t,n)=>{if(t?.render){let r=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=j(`div`);i.style.display=`none`;let a=j(`span`),o=j(`span`),s=j(`button`);s.style.display=`none`;let c=j(`div`);return c.style.display=`none`,{header:r,iconHolder:i,headerTitle:a,headerSubtitle:o,closeButton:s,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??`default`,i=Lo(r)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(i.iconHolder.style.display=`none`),t.showTitle===!1&&(i.headerTitle.style.display=`none`),t.showSubtitle===!1&&(i.headerSubtitle.style.display=`none`),t.showCloseButton===!1&&(i.closeButton.style.display=`none`),t.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display=`none`)),i},zo=e=>{let{config:t}=e,n=A(`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`}}),r=re(),i=A(`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:a,attachAutoResize:o}=k(t);o();let s=S(t),c=se(t),l=x(t),u=C(t),d=A(`div`,{className:`persona-widget-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});i.append(d),l&&(l.previewsContainer.style.gap=`8px`,d.append(l.previewsContainer),i.append(l.input)),i.append(a);let f=A(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=A(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=A(`div`,{className:`persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-end":``}});return l&&p.append(l.wrapper),c&&m.append(c.wrapper),m.append(s.wrapper),f.append(p,m),i.append(f),i.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),t?.statusIndicator?.mode===`transient`?n.append(r,u,i):n.append(r,i,u),{footer:n,suggestions:r,composerForm:i,header:d,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:s.setMode}},Bo=()=>{let t=A(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),n=j(`span`,`persona-pill-peek__icon`),r=e(nn,16,`currentColor`,1.5);r&&n.appendChild(r);let i=j(`span`,`persona-pill-peek__text`),a=j(`span`,`persona-pill-peek__caret`),o=e(Jt,16,`currentColor`,1.5);return o&&a.appendChild(o),t.append(n,i,a),{root:t,textNode:i}},Vo=e=>{let{config:t}=e,n=A(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=re(),i=C(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=k(t,{defaultMaxLines:5});o();let s=S(t),c=se(t),l=x(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=A(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=A(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=A(`div`,{className:`persona-widget-composer__right-actions persona-pill-composer__right`,attrs:{"data-persona-composer-actions-end":``}});c&&f.append(c.wrapper),f.append(s.wrapper),u.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),l&&u.append(l.input),u.append(d,a,f);let p=A(`div`,{className:`persona-pill-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});n.append(p),l&&p.append(l.previewsContainer),n.append(r,u,i);let m=u;return{footer:n,suggestions:r,composerForm:u,header:p,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:i,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:m,leftActions:d,rightActions:f,setSendButtonMode:s.setMode}},Ho=e=>{switch(e){case`max_tool_calls`:return`Stopped after calling a tool. Send a follow-up to continue.`;case`length`:return`Response cut off as max tokens reached. Ask for more to continue.`;case`content_filter`:return`The provider filtered this response.`;case`error`:return`Something went wrong generating this response.`;default:return null}},Uo=(e,t)=>{if(!e)return null;let n=Ho(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},Wo=(e,t)=>{let n=j(`div`,`persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic`);return n.setAttribute(`data-stop-reason`,e),n.setAttribute(`role`,`note`),n.style.opacity=`0.75`,n.textContent=t,n},Go=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},Ko=e=>{let t=e.toLowerCase();return t.startsWith(`javascript:`)||t.startsWith(`data:text/html`)||t.startsWith(`data:text/javascript`)||t.startsWith(`data:text/xml`)||t.startsWith(`data:application/xhtml`)||t.startsWith(`data:image/svg+xml`)?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:`)||!e.includes(`:`))},qo=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),Jo=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),Yo=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),Xo=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),Zo=e=>{if(!e||e.length===0)return null;let t=A(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=A(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=j(`span`,`persona-mention-chip-icon`),i=M(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(A(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},Q=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(oe(r.ref,{readonly:!0,render:t}));return n},Qo=(e,t,n,r)=>{let i=Math.random().toString(36).slice(2,8),a=e=>`${i}:${e}`,o=n(t.map((e,t)=>e.kind===`text`?e.text:a(t)).join(``));if(!t.every((e,t)=>e.kind===`text`||o.includes(a(t)))){e.replaceChildren(Q(t,r));return}e.innerHTML=o;let s=RegExp(`${i}:(\\d+)`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=[];for(let e=c.nextNode();e;e=c.nextNode())l.push(e);for(let e of l){let n=e;for(let e=s.exec(n.data);e;e=s.exec(n.data)){let i=t[Number(e[1])],a=n.splitText(e.index);a.data=a.data.slice(e[0].length),i?.kind===`mention`&&a.parentNode?.insertBefore(oe(i.ref,{readonly:!0,render:r}),a),n=a}}},$o=(e,t,n)=>{if(e.length===0)return null;try{let r=j(`div`,`persona-flex persona-flex-col persona-gap-2`);r.setAttribute(`data-message-attachments`,`images`),t&&(r.style.marginBottom=`8px`);let i=0,a=!1,o=()=>{a||(a=!0,r.remove(),n?.())};return e.forEach((e,t)=>{let n=j(`img`);n.alt=e.alt?.trim()||`Attached image ${t+1}`,n.loading=`lazy`,n.decoding=`async`,n.referrerPolicy=`no-referrer`,n.style.display=`block`,n.style.width=`100%`,n.style.maxWidth=`320px`,n.style.maxHeight=`320px`,n.style.height=`auto`,n.style.objectFit=`contain`,n.style.borderRadius=`10px`,n.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,n.style.border=`1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))`;let a=!1;i+=1,n.addEventListener(`error`,()=>{a||(a=!0,i=Math.max(0,i-1),n.remove(),i===0&&o())}),n.addEventListener(`load`,()=>{a=!0}),Go(e.image)?(n.src=e.image,r.appendChild(n)):(a=!0,i=Math.max(0,i-1),n.remove())}),i===0?(o(),null):r}catch{return n?.(),null}},es=e=>{if(e.length===0)return null;try{let t=j(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!Ko(e.audio))return;let r=j(`audio`);r.controls=!0,r.preload=`metadata`,r.src=e.audio,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ts=e=>{if(e.length===0)return null;try{let t=j(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!Ko(e.video))return;let r=j(`video`);r.controls=!0,r.preload=`metadata`,r.src=e.video,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,r.style.maxHeight=`320px`,r.style.borderRadius=`10px`,r.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ns=e=>{if(e.length===0)return null;try{let t=j(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!Ko(e.data))return;let r=j(`a`);r.href=e.data,r.download=e.filename,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=e.filename,r.className=`persona-message-file-attachment`,r.style.display=`inline-flex`,r.style.alignItems=`center`,r.style.gap=`6px`,r.style.padding=`6px 10px`,r.style.borderRadius=`8px`,r.style.fontSize=`0.875rem`,r.style.textDecoration=`underline`,r.style.backgroundColor=`var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))`,r.style.border=`1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))`,r.style.color=`inherit`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},rs=()=>{let e=document.createElement(`div`);e.className=`persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2`;let t=document.createElement(`div`);t.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,t.style.backgroundColor=`currentColor`,t.style.opacity=`0.4`,t.style.animationDelay=`0ms`;let 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 r=document.createElement(`div`);r.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,r.style.backgroundColor=`currentColor`,r.style.opacity=`0.4`,r.style.animationDelay=`500ms`;let i=document.createElement(`span`);return i.className=`persona-sr-only`,i.textContent=`Loading`,e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e},is=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:rs};if(t){let e=t(r);if(e!==null)return e}return rs()},as=(e,t)=>{let n=j(`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`),r=t===`user`?e.userAvatar:e.assistantAvatar;if(r){if(r.startsWith(`http`)||r.startsWith(`/`)||r.startsWith(`data:`)){let e=j(`img`);e.src=r,e.alt=t===`user`?`User`:`Assistant`,e.className=`persona-w-full persona-h-full persona-rounded-full persona-object-cover`,n.appendChild(e)}else n.textContent=r,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`)}else n.textContent=t===`user`?`U`:`A`,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`);return n},os=(e,t,n=`div`)=>{let r=j(n,`persona-text-xs persona-text-persona-muted`),i=new Date(e.createdAt);return r.textContent=t.format?t.format(i):i.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),r},ss=(e,t=`bubble`)=>{let n=[`persona-message-bubble`];switch(t){case`flat`:e===`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`),e===`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`),e===`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`)}return n},cs={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`}},ls=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=cs[n??`bubble`]??cs.bubble;r.padding&&(e.style.padding=`var(--persona-message-${i}-padding, ${a.padding})`),r.fontSize&&(e.style.fontSize=`var(--persona-message-${i}-font-size, ${a.fontSize})`),r.lineHeight&&(e.style.lineHeight=`var(--persona-message-${i}-line-height, ${a.lineHeight})`),r.fontFamily&&(e.style.fontFamily=`var(--persona-message-${i}-font-family, inherit)`)},us=e=>`custom:${e}`,ds=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),fs=(e,t,n,r)=>{let i=t.showCopy??!0,a=t.showUpvote??!1,o=t.showDownvote??!1,s=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&r?.canRegenerate===!0,l=(t.showEdit??!1)&&r?.canEdit===!0,u=(t.showQuote??!1)&&r?.canQuote!==!1,d=ds(t,e.role);if(!i&&!a&&!o&&!s&&!c&&!l&&!u&&d.length===0){let t=j(`div`);return t.style.display=`none`,t.id=`actions-${e.id}`,t.setAttribute(`data-actions-for`,e.id),t}let f=t.visibility??`hover`,p=t.align??`right`,m=t.layout??`pill-inside`,h={left:`persona-message-actions-left`,center:`persona-message-actions-center`,right:`persona-message-actions-right`}[p],g={"pill-inside":`persona-message-actions-pill`,"row-inside":`persona-message-actions-row`}[m],_=j(`div`,`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${h} ${g} ${f===`hover`?`persona-message-actions-hover`:``}`);_.id=`actions-${e.id}`,_.setAttribute(`data-actions-for`,e.id);let v=(e,t,n)=>{let r=be({icon:e,label:t,size:14,className:`persona-message-action-btn`,chromeless:!0});return r.setAttribute(`data-action`,n),r};i&&_.appendChild(v(`copy`,`Copy message`,`copy`)),s&&_.appendChild(v(`volume-2`,`Read aloud`,`read-aloud`)),a&&_.appendChild(v(`thumbs-up`,`Upvote`,`upvote`)),o&&_.appendChild(v(`thumbs-down`,`Downvote`,`downvote`)),c&&_.appendChild(v(`refresh-cw`,`Regenerate response`,`regenerate`)),l&&_.appendChild(v(`pencil`,`Edit message`,`edit`)),u&&_.appendChild(v(`quote`,`Quote message`,`quote`));for(let e of d)_.appendChild(v(e.iconName??`ellipsis`,e.label,us(e.id)));return _},ps=(e,t,n,r,i,a)=>{let o=n??{},s=o.layout??`bubble`,c=o.avatar,l=o.timestamp,u=c?.show??!1,d=l?.show??!1,f=c?.position??`left`,p=l?.position??`below`,m=ss(e.role,s),h=j(`div`,m.join(` `));h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.setAttribute(`data-persona-theme-zone`,e.role===`user`?`user-message`:`assistant-message`);let g=X(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;ls(h,e.role,s,e.role===`user`?{...g.user,..._?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...g.assistant,..._?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),s===`flat`?(h.style.backgroundColor=`transparent`,h.style.color=e.role===`user`?`var(--persona-primary, var(--persona-text))`:`var(--persona-message-assistant-text, var(--persona-text))`):e.role===`user`?(h.style.backgroundColor=`var(--persona-message-user-bg, var(--persona-accent))`,h.style.color=`var(--persona-message-user-text, white)`):e.role===`assistant`&&(h.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,h.style.color=`var(--persona-message-assistant-text, var(--persona-text))`);let v=qo(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=Ft(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?Lt(x.type,S):null,w=e.role===`assistant`&&C?.isAnimating?.(e)===!0,T=e.role===`assistant`&&C!==null&&(!!e.streaming||w);T&&C?.bubbleClass&&h.classList.add(C.bubbleClass);let E=document.createElement(`div`);E.classList.add(`persona-message-content`),e.streaming&&E.classList.add(`persona-content-streaming`),T&&C&&(C.containerClass&&E.classList.add(C.containerClass),E.style.setProperty(`--persona-stream-step`,`${x.speed}ms`),E.style.setProperty(`--persona-stream-duration`,`${x.duration}ms`));let D=T?Rt(e.content??``,x.buffer,C,e,!!e.streaming):e.content??``,O=()=>{let n=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent});return T&&C?.wrap===`char`?Ut(n,`char`,e.id,{skipTags:C.skipTags}):T&&C?.wrap===`word`?Ut(n,`word`,e.id,{skipTags:C.skipTags}):n},k=null;if(b?(k=document.createElement(`div`),k.innerHTML=O(),k.style.display=`none`,E.appendChild(k)):e.contentSegments?.length?Qo(E,e.contentSegments,n=>t({text:n,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=O(),T&&C?.useCaret&&!b&&y){let e=It(),t=E.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];if(n?.parentNode)n.parentNode.insertBefore(e,n.nextSibling);else{let t=E.lastElementChild;t?t.appendChild(e):E.appendChild(e)}}if(d&&p===`inline`&&e.createdAt){let t=os(e,l,`span`);t.classList.add(`persona-timestamp-inline`);let n=E.lastElementChild;n?n.appendChild(t):E.appendChild(t)}if(v.length>0){let e=$o(v,!b&&!!y,()=>{b&&k&&(k.style.display=``)});e?h.appendChild(e):b&&k&&(k.style.display=``)}let ee=Jo(e);if(ee.length>0){let e=es(ee);e&&h.appendChild(e)}let te=Yo(e);if(te.length>0){let e=ts(te);e&&h.appendChild(e)}let ne=Xo(e);if(ne.length>0){let e=ns(ne);e&&h.appendChild(e)}let re=e.contentSegments?.length?null:Zo(e.contextMentions);if(re&&h.appendChild(re),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=os(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let ie=e.role===`assistant`?Uo(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role===`assistant`){let e=!!(D&&D.trim()),t=x.placeholder===`skeleton`,n=t&&x.buffer===`line`&&e;if(e)n&&h.appendChild(Bt());else if(t)h.appendChild(Bt());else{let e=is(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}ie&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild(Wo(e.stopReason,ie)));let ae=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,oe=a?.actionEligibility,se=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&oe?.canEdit===!0||r?.showQuote===!0&&oe?.canQuote===!0||ds(r,`user`).length>0);if((ae||se)&&r){let t=fs(e,se?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,oe);h.appendChild(t)}if(!u||e.role===`system`)return h;let ce=j(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),le=as(c,e.role);return f===`right`||f===`left`&&e.role===`user`?ce.append(h,le):ce.append(le,h),ce},ms=(e,t)=>{if(e.replaceChildren(),!t)e.hidden=!0;else if(typeof t==`function`){let n=null;try{n=t()}catch(e){console.warn(`[persona] welcome.icon renderer threw`,e)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1}else{if(t.type===`lucide`){let n=M(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(A(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(A(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},hs=(e,t,n={})=>{let r=A(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=j(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=j(`h2`,`persona-welcome-title`),o=j(`p`,`persona-welcome-subtitle`),s=A(`div`,{className:`persona-welcome-head-text`},i,a),c=A(`div`,{className:`persona-welcome-title-row`},r,s);return{host:A(`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)`}},c,o,t),iconHolder:r,kicker:i,title:a,subtitle:o,starterSuggestions:t}},gs=(e,t,n)=>{t.hidden=!n,t.style.display=n?``:`none`,e.classList.toggle(`persona-gap-6`,n),e.classList.toggle(`persona-gap-3`,!n)},_s=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??``,e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle===``,ms(e.iconHolder,t.icon),e.host.setAttribute(`data-persona-welcome-variant`,t.variant),e.host.setAttribute(`data-persona-welcome-dismiss`,t.dismiss),e.host.setAttribute(`data-persona-welcome-layout`,t.layout??`top`),e.host.setAttribute(`data-persona-welcome-anchor`,t.anchor??`bottom`),t.iconPlacement===`inline`?e.host.setAttribute(`data-persona-welcome-icon-placement`,`inline`):e.host.removeAttribute(`data-persona-welcome-icon-placement`),t.align?e.host.setAttribute(`data-persona-welcome-align`,t.align):e.host.removeAttribute(`data-persona-welcome-align`)},vs=`data-persona-welcome-overlay`,ys=`persona-welcome-overlay-active`,bs=/* @__PURE__ */ new WeakMap,xs=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(vs,``),e.classList.contains(ys)||(bs.set(e,e.scrollTop),e.classList.add(ys),e.scrollTop=0)},Ss=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(vs),e.classList.contains(ys)&&(e.classList.remove(ys),e.scrollTop=bs.get(e)??e.scrollTop,bs.delete(e))},Cs=()=>{let e=A(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},ws=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=A(`div`,{className:ss(`assistant`,r).join(` `),attrs:{"data-persona-theme-zone":`assistant-message`},text:t,style:r===`flat`?{backgroundColor:`transparent`,color:`var(--persona-message-assistant-text, var(--persona-text))`}:{backgroundColor:`var(--persona-message-assistant-bg, var(--persona-container))`,color:`var(--persona-message-assistant-text, var(--persona-text))`}});e.appendChild(A(`div`,{className:`persona-flex`},i)),e.hidden=!1},Ts=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Es=(e,t)=>{if(Ts()||typeof e.animate!=`function`||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),r=e.parentElement,i=0,a=0,o=0;if(r){let t=getComputedStyle(r);i=parseFloat(t.rowGap)||0;let s=e.previousElementSibling,c=e.nextElementSibling,l=r.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-r.scrollTop;a=Math.max(0,s?n.top-s.getBoundingClientRect().bottom-i:n.top-l),o=Math.max(0,c?c.getBoundingClientRect().top-n.bottom-i:0)}let s=e.style.overflow;e.style.overflow=`hidden`;let c=getComputedStyle(e),l=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,d=e.animate([{opacity:`1`,transform:`none`,height:`${n.height}px`,minHeight:`0px`,paddingTop:`${l}px`,paddingBottom:`${u}px`,marginTop:`${a}px`,marginBottom:`${o}px`},{opacity:`0`,transform:`translateY(-4px)`,height:`0px`,minHeight:`0px`,paddingTop:`0px`,paddingBottom:`0px`,marginTop:`0px`,marginBottom:`${-i}px`}],{duration:180,easing:`ease-out`,fill:`forwards`}),f=!1,p=()=>{f||(f=!0,e.style.overflow=s,t(d))};return d.finished.then(p).catch(p),d},Ds=(e,t,n,r=260)=>{if(t<=1||Ts()||typeof e.animate!=`function`||!e.isConnected)return null;let i=n===`drop`?-t:t;return e.animate([{transform:`translateY(${i}px)`},{transform:`none`}],{duration:r,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`none`})},Os=/* @__PURE__ */ new WeakSet,ks=(e,t)=>!!e&&e[t]!==void 0,As=(e,t)=>{e&&e.debug===!0&&t.length&&(Os.has(e)||(Os.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},js=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!==`docked`)=>{let n=e?.welcome,r=e?.copy,i=e?.future?.v5Defaults===!0,a=n?.layout??(i?`centered`:`top`),o=ks(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:ks(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];ks(n,`title`)&&ks(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),ks(n,`subtitle`)&&ks(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),ks(n,`variant`)&&ks(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&ks(n,`message`)&&c.push(`welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.`),!i&&n?.layout===void 0&&o===`hero`&&ks(n,`dismiss`)&&n.dismiss!==`on-first-message`&&c.push(`welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".`);let l=n?.anchor??(a===`centered`&&t?`center`:`bottom`),u=qa(n?.anchorComposerTop)!==null;return ks(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(ks(n,`anchorComposerTop`)||ks(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),As(e,c),{title:ks(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:ks(n,`subtitle`)?n.subtitle:r?.welcomeSubtitle??(i?``:`I can answer questions and help you get things done here.`),icon:n?.icon,align:n?.align===`start`||n?.align===`center`?n.align:a===`centered`?`center`:void 0,iconPlacement:n?.icon&&typeof n.icon!=`function`&&n.icon.placement===`inline`?`inline`:`above`,variant:o,dismiss:s,message:o===`hero`?void 0:n?.message,layout:a,anchor:l,anchorComposerTop:u?n.anchorComposerTop:`44%`,composerGap:n?.composerGap?.trim()||`24px`}},Ms=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,Ns=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`),Ps=`var(--persona-components-panel-height)`,Fs=e=>{let t=s(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,r=e?.launcher?.heightOffset??0,i=r===0?`max(200px, ${Ps})`:`max(200px, calc(${Ps} - ${r}px))`;return{width:n??`var(--persona-components-panel-width)`,maxWidth:n??`var(--persona-components-panel-maxWidth)`,height:i,maxHeight:`var(--persona-components-panel-maxHeight)`}},Is=`16px`,Ls=`10px`,Rs=`14px`,zs=e=>{let t=e?.launcher?.enabled??!0,n=po(e);if(mo(e)){let t=e?.launcher?.composerBar??{},n=j(`div`,`persona-widget-wrapper persona-fixed persona-transition`);n.setAttribute(`data-persona-composer-bar`,``),n.dataset.state=`collapsed`,n.dataset.expandedSize=t.expandedSize??`anchored`,n.style.zIndex=String(e?.launcher?.zIndex??1e5);let r=j(`div`,`persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);r.style.width=`100%`,n.appendChild(r);let i=j(`div`,`persona-widget-pill-root`);return i.setAttribute(`data-persona-composer-bar`,``),i.dataset.state=`collapsed`,i.dataset.expandedSize=t.expandedSize??`anchored`,i.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:n,panel:r,pillRoot:i}}if(n){let e=j(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=j(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=j(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=j(`div`,`persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0`),r=s(e),i=r.launcherWidth||r.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Fs(e).width:`100%`;return t.style.width=i,n.style.width=`100%`,t.appendChild(n),{wrapper:t,panel:n}}let r=e?.launcher??{},i=r.position&&Co[r.position]?Co[r.position]:Co[`bottom-right`],a=j(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=j(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),c=Fs(e);return o.style.width=c.width,o.style.maxWidth=c.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},Bs=e=>{let t=A(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":go(e)}});return t.hidden=!0,t},Vs=(e,t)=>{let n=Bs(`starter`),r=hs(e,n,{flatShadow:po(e)}),i=js(e);_s(r,i),gs(t,r.host,Ns(i,e?.initialMessages));let a=Cs();return ws(a,i.message,e),{welcome:r,greetingHost:a}},Hs=(e,t)=>{let n=j(`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:r,wrapper:i}=Oo(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:Is,iconSize:Ls});i.style.position=`absolute`,i.style.top=`8px`,i.style.right=`8px`,i.style.zIndex=`10`;let a=e?.launcher?.clearChat?.enabled??!0,o=null,s=null;if(a){let t=ko(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:Is,iconSize:Rs});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=A(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=A(`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`}});l.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:u,greetingHost:d}=Vs(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=j(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=Bs(`followUp`),v=Ga(e,!0);v&&(g.style.maxWidth=v,g.style.marginLeft=`auto`,g.style.marginRight=`auto`,g.style.width=`100%`),l.append(f,d,g,_);let y=A(`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=Vo({config:e}),{root:x,textNode:S}=Bo();return n.append(c,i,l,y),s&&n.appendChild(s),{container:n,body:l,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:_,composerOverlay:y,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:f,welcomeIconHolder:u.iconHolder,greetingHost:d,introKicker:u.kicker,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:i,clearChatButton:o,clearChatButtonWrapper:s,iconHolder:j(`span`),headerTitle:j(`span`),headerSubtitle:j(`span`),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:x,peekTextNode:S}},Us=(e,t=!0)=>{if(mo(e))return Hs(e,t);let n=A(`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`}}),r=e?.layout?.header,i=e?.layout?.showHeader!==!1,a=r?Ro(e,r,{showClose:t}):No({config:e,showClose:t}),o=A(`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`}});o.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:s,greetingHost:c}=Vs(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=j(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=Bs(`followUp`),h=Ga(e,!1);h&&(p.style.maxWidth=h,p.style.marginLeft=`auto`,p.style.marginRight=`auto`,p.style.width=`100%`),o.append(l,c,p,m);let g=zo({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),Po(n,a,e),n.append(o);let v=A(`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 _||(g.footer.style.display=`none`),n.append(g.footer),n.append(v),{container:n,body:o,messagesWrapper:p,starterSuggestions:f,transcriptSuggestions:m,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,welcomeHost:l,welcomeIconHolder:s.iconHolder,greetingHost:c,introKicker:s.kicker,introTitle:u,introSubtitle:d,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}},Ws=(e,t)=>{let n=j(`button`);n.type=`button`,n.innerHTML=`
|
|
11
|
+
`),o=Array.isArray(e.contentParts)&&e.contentParts.length>0,s=r.contentParts.length>0;if(o){let t=[];i&&t.push(st(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(st(a)),t.push(...r.contentParts),e.contentParts=t}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,t){let n=e.trim(),r=!!t?.replayFields&&(t.replayFields.llmContent!==void 0||t.replayFields.rawContent!==void 0||(t.replayFields.contextMentions?.length??0)>0);if(!n&&(!t?.contentParts||t.contentParts.length===0)&&(!t?.mentions||t.mentions.refs.length===0)&&!r)return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#T||this.#D||this.#w||this.#P)&&await this.#ke(),this.stopSpeaking(),this.abortController?.abort(),this.#He(),this.#Le++,this.#it();let i=t?.voiceTurn?.userMessageId,a=i?this.messages.find(e=>e.id===i&&e.role===`user`):void 0,o=a?.id??Je(),s=Ye();this.#i=null;let c=t?.contentParts&&ut(t.contentParts)?dt:``,l={id:o,role:`user`,content:n||c,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#mt(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==n&&(a.llmContent=n),this.callbacks.onMessagesChanged([...this.messages])):this.#ft(l),this.#ct(!0);let u=new AbortController;if(this.abortController=u,t?.mentions){let e=this.messages.find(e=>e.id===o)??l;if(await this.#Ne(e,n,t.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===o)??l,n=Sr({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});n.contentParts&&(e.contentParts=n.contentParts),n.llmContent!==void 0&&(e.llmContent=n.llmContent),(n.contentParts||n.llmContent!==void 0)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let d=(/* @__PURE__ */ new Date()).toISOString(),f=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:d}]:[...this.messages],p=(a??this.messages.find(e=>e.id===o))?.createdAt??d,m=yr(t?.voiceTurn?.priorToolResults,p);for(let e of m)this.messages.some(t=>t.id===e.id)||(this.#ft(e),f.push({...e,createdAt:d}));let h=m.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:n,args:r,result:i}=e.clientToolAnswer;return{toolCallId:t,name:n,arguments:r,result:i}});try{await this.#je(f,u,s,o,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn,...h.length>0&&{voicePriorToolResults:h}})}catch(e){if(this.status===`resuming`||this.#a)return;this.#U&&(this.#U.failed=!0);let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));if(!t){let t=Kr(e,this.config.errorMessage);if(t){let e={id:s,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:t,localOnly:!0,sequence:this.#mt()};this.#ft(e)}}this.#st(`idle`),this.#ct(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let n=wr(this.messages,e);if(!n)return!1;let r=this.messages[n.start],i=t.replacement,a=i?i.text:r.content,o=i?i.contentParts:r.contentParts;if(!(a?.trim()||(o?.length??0)>0||!i&&(r.llmContent?.trim()?.length??0)>0))return!1;let s=i?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},c=i?this.#Pe(i.options):r.composerOptions,l=i?i.contentSegments:r.contentSegments,u=i?i.options?.quote:void 0,d=i?i.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(a??``,{...o?.length?{contentParts:[...o]}:{},...l?.length?{contentSegments:[...l]}:{},...c?{composerOptions:c}:{},...u?{quote:u}:{},...s&&Object.keys(s).length>0?{replayFields:s}:{},viaVoice:d===!0}),!0}#Pe(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#T||this.#D||this.#w||this.#P)&&await this.#ke(),this.abortController?.abort(),this.#it();let e=Ye();this.#i=null,this.#ct(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if(this.status===`resuming`||this.#a)return;let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));if(!n){let n=Kr(t,this.config.errorMessage);if(n){let t={id:e,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:n,localOnly:!0,sequence:this.#mt()};this.#ft(t)}}this.#st(`idle`),this.#ct(!1),this.abortController=null,n||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#i=t.assistantMessageId);let n=t?.preserveAssistantId?t.assistantMessageId:void 0,r=!1;for(let e of this.messages)e.streaming&&e.id!==n&&(e.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#ct(!0);let i={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=i;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#lt(i)}catch(e){if(this.status===`resuming`||this.#a){this.#ut(i);return}this.#lt(i),this.#st(`error`),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Fe(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t;do t=`webmcp-${++this.#d}`;while(this.messages.some(e=>e.id===`approval-${t}`||e.approval?.id===t));let n={id:t,status:`pending`,agentId:``,executionId:``,toolName:e.toolName,toolType:`webmcp`,description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,approval:n}),new Promise(t=>{this.webMcpApprovalResolvers.set(r,t),e.signal?.addEventListener(`abort`,()=>this.resolveWebMcpApproval(r,`timeout`),{once:!0})})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(t=>t.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:t,resolvedAt:Date.now()}}),n(t===`approved`)}#Ie;#Le;#Re(e){let t=this.#Ie??={s:this,setStreaming:e=>this.#ct(e),appendMessage:e=>this.#ft(e),nextSequence:()=>this.#mt(),settleApprovalPausedToolCall:e=>this.#dt(e),resumeAfter:e=>this.#r?.executionId===e?this.#r.lastEventId:void 0},n=_r();if(n)return e(n,t);let r=this.#Le;return gr().then(n=>r===this.#Le?e(n,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,n){return this.#Re((r,i)=>r.resolveApproval(i,e,t,n))}resolveAskUserQuestion(e,t){return this.#Re((n,r)=>n.resolveAskUserQuestion(r,e,t))}resolveWebMcpToolCall(e){return this.#Re((t,n)=>t.resolveWebMcpToolCall(n,e))}persistAskUserQuestionProgress(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#ze(e){let t=e.agentMetadata?.executionId,n=e.toolCall?.id;if(!t||!n){let t=this.#u;queueMicrotask(()=>{t===this.#u&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(t);r||(r={snapshots:[],seen:/* @__PURE__ */ new Set},this.webMcpAwaitBatches.set(t,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(e))}#Be(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#u;queueMicrotask(()=>{if(e===this.#u)for(let e of[...this.webMcpAwaitBatches.keys()])this.#Ve(e)})}#Ve(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.#Re((t,r)=>t.resolveWebMcpToolCallBatch(r,e,n))}#He(){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.#u++}cancel(){this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ct(!1),this.#st(`idle`)}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.messages=[],this.agentExecution=null,this.#Ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#l}selectArtifact(e){this.#l=e,this.#Ke()}clearArtifacts(){this.#Ge()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=e.artifactType===`markdown`?{id:t,artifactType:`markdown`,title:e.title,status:`complete`,markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:`component`,title:e.title,status:`complete`,component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,n),this.#l=t,this.#Ke(),e.transcript!==!1&&this.#Ue(n),n}#Ue(e){let t=`artifact-ref-${e.id}`,n=rt(this.config.features?.artifacts,e),r=at(n,{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(e=>e.id===t);i?(i.rawContent=r,i.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:``,rawContent:r})}#We(){let e=!1;for(let t of this.artifacts.values()){let n=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!n)continue;let r=rt(this.config.features?.artifacts,t),i=at(r,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown===void 0?{}:{markdown:t.markdown}});n.rawContent!==i&&(n.rawContent=i,n.streaming=t.status===`streaming`,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Ge(){(this.artifacts.size!==0||this.#l!==null)&&(this.artifacts.clear(),this.#l=null,this.#Ke())}#Ke(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#l})}#qe(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.#l=e.id;break;case`artifact_delta`:{let t=this.artifacts.get(e.id);t?.artifactType===`markdown`&&(t.markdown=(t.markdown??``)+e.artDelta);break}case`artifact_update`:{let t=this.artifacts.get(e.id);t?.artifactType===`component`&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case`artifact_complete`:{let t=this.artifacts.get(e.id);t&&(t.status=`complete`);break}default:return}this.#Ke()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ht(e.map(e=>({...y(e),streaming:!1,sequence:e.sequence??this.#mt()}))),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:`complete`});this.#l=t,this.#Ke()}#Je(e){let t=this.agentExecution?.executionId;if(!t||!this.#i||this.agentExecution?.status!==`running`)return;let n=this.#r===null;this.#r={executionId:t,lastEventId:e,assistantMessageId:this.#i,status:`running`},this.#ot(n)}#Ye(){return this.#r!==null&&typeof this.config.reconnectStream==`function`&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Xe()}#Xe(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant===`approval`&&e.approval?.status===`pending`)}#Ze(){this.#a||this.#r&&typeof this.config.reconnectStream==`function`&&(this.#a=!0,this.callbacks.onReconnect?.({phase:`paused`,handle:this.#r}),this.#ct(!0),this.#st(`resuming`),this.#Qe().then(e=>{this.#a&&this.#r&&e.begin()}))}#Qe(){return this.#o?Promise.resolve(this.#o):(this.#s||(this.#s=Hr().then(({createReconnectController:e})=>{let t=e(this.#$e());return this.#o=t,t}),this.#s.catch(()=>{this.#s=null})),this.#s)}#$e(){let e=this;return{get config(){return e.config},getResumable:()=>e.#r,clearResumable:()=>e.#at(),getStatus:()=>e.status,setStatus:t=>e.#st(t),setStreaming:t=>e.#ct(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,n,r)=>e.connectStream(t,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:t=>e.#ft(t),settleParked:t=>e.#et(t),nextSequence:()=>e.#mt(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>Kr(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#o?.wake():this.#Ze()}resumeFromHandle(e){if(typeof this.config.reconnectStream!=`function`||this.#a)return;if(this.#Xe()){this.#tt(e.executionId),this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:this.#i??``,status:`running`};return}let t=this.#nt(e.executionId)?Ye():this.#rt();t||(t=Ye(),this.#ft({id:t,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:this.#mt()})),this.#i=t,this.#tt(e.executionId),this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:`running`},this.#Ze()}#et(e){let t=this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0;if(!t&&!this.#Xe()){if(!this.#nt(e))return!1;this.#at()}if(this.#a=!1,!t){let e=!1;for(let t of this.messages)t.streaming&&(t.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.#ct(!1),this.abortController=null}return this.#st(`idle`),!0}#tt(e){this.agentExecution||={executionId:e,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0}}#nt(e){return this.messages.some(t=>t.agentMetadata?.executionId===e&&[t.toolCall,...t.tools??[]].some(e=>e?.interrupted===!0))}#rt(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role===`assistant`&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role===`user`)break}return null}#it(){this.#a=!1,this.#o?.teardown(),this.#at()}#at(){this.#c&&=(clearTimeout(this.#c),null);let e=this.#r!==null;this.#r=null,e&&this.config.onExecutionState?.(null)}#ot(e){let t=this.config.onExecutionState;t&&(e?(this.#c&&=(clearTimeout(this.#c),null),t(this.#r)):this.#c||=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#r)},500))}getResumableHandle(){return this.#r}#st(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#ct(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#lt(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider===`browser`||t.provider===`runtype`&&t.browserFallback))return;let n=[...this.messages].reverse().find(e=>e.role===`assistant`&&e.content&&!e.voiceProcessing);if(!n||e&&!e.includes(n.id))return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Ir(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Or(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=Ir(t.content||``);if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.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()}#lt(e){for(let[t,n]of[...this.#e])n===e&&(this.#e.delete(t),this.#dt(t))}#ut(e){for(let[t,n]of this.#e)n===e&&this.#e.set(t,void 0)}#dt(e){let t=this.messages.find(t=>t.id===e)?.approval,n=t?.toolCallId,r=n&&this.messages.find(e=>e.toolCall?.id===n),i=r&&r.toolCall;if(!i||i.status===`complete`||t.status===`pending`)return;let a={...i,status:`complete`,approvalStatus:t.status,completedAt:Date.now(),...t.status===`approved`?{superseded:!0}:{success:!1,error:t.status===`denied`?`Denied`:`Approval timed out`}};this.upsertMessage({...r,streaming:!1,toolCall:a})}#ft(e){let t=this.#pt(e);this.messages=this.#ht([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#pt(e),n=this.messages.findIndex(e=>e.id===t.id);n===-1?this.#ft(t):(this.messages=this.messages.map((e,r)=>{if(r!==n||e.toolCall?.name&&g(e.toolCall.name)&&e.toolCall.status===`complete`&&t.toolCall?.id===e.toolCall.id&&t.toolCall.status!==`complete`&&(t.toolCall.status===`pending`&&!t.toolCall.name||!e.toolCall.interrupted&&(e.toolCall.result!==void 0||e.toolCall.success!==void 0)&&(!t.agentMetadata?.executionId||t.agentMetadata.executionId===e.agentMetadata?.executionId)))return e;let i={...e,...t};e.agentMetadata?.askUserQuestionAnswered===!0&&t.agentMetadata&&(i.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),e.agentMetadata?.suggestRepliesResolved===!0&&t.agentMetadata&&(i.agentMetadata={...i.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let n=e.approval,r=t.approval;i.approval={...n,...r,executionId:r.executionId||n.executionId,toolName:r.toolName||n.toolName,description:r.description||n.description,toolType:r.toolType??n.toolType,reason:r.reason??n.reason,parameters:r.parameters??n.parameters,toolCallId:r.toolCallId??n.toolCallId}}let o=t.toolCall?.name,s=t.agentMetadata?.executionId,c=t.toolCall?.id;if(o&&qr(o)&&s&&c&&t.agentMetadata?.awaitingLocalTool===!0){let t=`${s}:${c}`,n=this.webMcpInflightKeys.has(t),r=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,o=e.agentMetadata?.executionId===s&&e.toolCall?.id===c&&a!==void 0&&qr(a)&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;(n||r||o)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=e.toolCall,i.streaming=e.streaming)}return i}),this.messages=this.#ht(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#pt(e){return e.sequence===void 0?{...e,sequence:this.#mt()}:{...e}}#mt(){return this.#n++}#ht(e){return[...e].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}};const Yr={add:e=>ft(e)},Xr=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Zr={allowedTypes:pt,maxFileSize:10485760,maxFiles:4};function Qr(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $r(e){return e===`application/pdf`||e.startsWith(`text/`)||e.includes(`word`)?sn:e.includes(`excel`)||e.includes(`spreadsheet`)?on:e===`application/json`?an:rn}var ei=class e{#e;#t;#n;constructor(e={}){this.attachments=[],this.#e=null,this.#t=/* @__PURE__ */ new Map,this.#n=!1,this.config={allowedTypes:e.allowedTypes??Zr.allowedTypes,maxFileSize:e.maxFileSize??Zr.maxFileSize,maxFiles:e.maxFiles??Zr.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#r(){return typeof this.config.adapter?.add==`function`}#i(){return this.#r()?this.config.adapter:Yr}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML=``;for(let e of this.attachments)this.#l(e)}this.#f()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Zr.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.#n)return;let t=[];for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,`count`);continue}let e=lt(n,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes(`type`)?`type`:`size`;this.config.onFileRejected?.(n,t);continue}let r={id:Qr(),file:n,previewUrl:mt(n)?URL.createObjectURL(n):null,contentPart:null,status:this.#r()?`uploading`:`processing`,progress:this.#r()?0:void 0};this.attachments.push(r),this.#l(r),t.push(r)}this.#f(),this.#c(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let n=()=>this.#n||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let r=await this.#i().add(e.file,{signal:t.signal,onProgress:t=>{n()||e.status!==`uploading`||(e.progress=Xr(t),this.#u(e),this.#c())}});if(n())return;e.contentPart=r,e.status=`ready`,e.progress=void 0,e.error=void 0}catch(t){if(n())return;e.status=`error`,e.progress=void 0,e.error=t instanceof Error?t.message:String(t??`Upload failed`)}finally{this.#t.get(e.id)===t&&this.#t.delete(e.id)}this.#u(e),this.#c()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||t.status!==`error`||this.#n||(t.status=this.#r()?`uploading`:`processing`,t.progress=this.#r()?0:void 0,t.error=void 0,this.#u(t),this.#c(),this.#a(t))}#o(e){let t=this.#t.get(e);t&&(this.#t.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(t===-1)return;let n=this.attachments[t];this.#o(e),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let r=this.#e?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),n.status===`ready`&&n.contentPart&&this.#s(n.contentPart),this.#f(),this.#c()}#s(e){let t=this.config.adapter?.remove;if(t)try{let n=t(e,{signal:new AbortController().signal});n&&typeof n.catch==`function`&&n.catch(e=>{console.error(`[AttachmentManager] adapter.remove failed:`,e)})}catch(e){console.error(`[AttachmentManager] adapter.remove failed:`,e)}}clearAttachments(){for(let e of this.attachments)this.#o(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=``),this.#f(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let e of this.#t.values())e.abort();this.#t.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#l(e){if(!this.#e)return;let t=mt(e.file),n=M(`div`,`persona-attachment-preview persona-relative persona-inline-block`);if(n.setAttribute(`data-attachment-id`,e.id),n.style.width=`48px`,n.style.height=`48px`,t&&e.previewUrl){let t=M(`img`);t.src=e.previewUrl,t.alt=e.file.name,t.className=`persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200`,t.style.width=`48px`,t.style.height=`48px`,t.style.objectFit=`cover`,t.style.borderRadius=`8px`,n.appendChild(t)}else{let t=M(`div`);t.style.width=`48px`,t.style.height=`48px`,t.style.borderRadius=`8px`,t.style.backgroundColor=`var(--persona-container, #f3f4f6)`,t.style.border=`1px solid var(--persona-border, #e5e7eb)`,t.style.display=`flex`,t.style.flexDirection=`column`,t.style.alignItems=`center`,t.style.justifyContent=`center`,t.style.gap=`2px`,t.style.overflow=`hidden`;let r=$r(e.file.type),i=b(r,20,`var(--persona-muted, #6b7280)`,1.5);i&&t.appendChild(i);let a=M(`span`);a.textContent=ct(e.file.type,e.file.name),a.style.fontSize=`8px`,a.style.fontWeight=`600`,a.style.color=`var(--persona-muted, #6b7280)`,a.style.textTransform=`uppercase`,a.style.lineHeight=`1`,t.appendChild(a),n.appendChild(t)}let r=j(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),i=M(`div`,`persona-attachment-progress`);i.appendChild(M(`div`,`persona-attachment-progress__bar`));let a=j(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),o=N(`rotate-cw`,12,`var(--persona-text-inverse, #ffffff)`,2);o?a.appendChild(o):a.textContent=`↻`,a.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),r.append(i,a),n.appendChild(r);let s=M(`button`,`persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center`);s.type=`button`,s.setAttribute(`aria-label`,`Remove attachment`),s.style.position=`absolute`,s.style.top=`-4px`,s.style.insetInlineEnd=`-4px`,s.style.width=`18px`,s.style.height=`18px`,s.style.borderRadius=`50%`,s.style.backgroundColor=`var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))`,s.style.border=`none`,s.style.cursor=`pointer`,s.style.display=`flex`,s.style.alignItems=`center`,s.style.justifyContent=`center`,s.style.padding=`0`;let c=b(ln,10,`var(--persona-text-inverse, #ffffff)`,2);c?s.appendChild(c):(s.textContent=`×`,s.style.color=`var(--persona-text-inverse, #ffffff)`,s.style.fontSize=`14px`,s.style.lineHeight=`1`),s.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(s),this.#e.appendChild(n),this.#d(n,e)}#u(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#d(t,e)}#d(e,t){e.dataset.status=t.status;let n=t.status!==`ready`&&t.status!==`error`;e.setAttribute(`aria-busy`,n?`true`:`false`),e.title=t.status===`error`?`${t.file.name}: ${t.error??`Upload failed`}`:t.file.name;let r=e.querySelector(`.persona-attachment-progress__bar`);if(r){let e=t.progress;r.style.width=typeof e==`number`?`${Math.round(e*100)}%`:``}}#f(){this.#e&&(this.#e.style.display=this.attachments.length>0?`flex`:`none`)}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};const ti=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),ni=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.name===r.name&&e.mimeType===r.mimeType&&e.size===r.size&&e.status===r.status&&e.progress===r.progress&&e.error===r.error});function ri(){let e={text:``,attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=/* @__PURE__ */ new Set,n=null,r=!1,i=!1,a=()=>e.preparing?`preparing`:e.streaming?`streaming`:`idle`,o=()=>{let t=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:t,inputDisabled:e.inputDisabled,sendDisabled:t!==`idle`||e.sendDisabled||e.inputDisabled})},s=()=>(n||=o(),n),c=()=>{if(r=!1,i||t.size===0)return;let e=s();for(let n of[...t])try{n(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] composer state listener failed:`,e)}},l=()=>{n=null,!(i||r)&&(r=!0,queueMicrotask(c))};return{getState:s,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,l())},setAttachments:t=>{ni(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{ti(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{ti(e.activeModeIds,t)||(e.activeModeIds=[...t],l())},setQuote:t=>{let n=e.quote;(n?.text!==t?.text||n?.messageId!==t?.messageId||n?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,l())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,l())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,l())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,l())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,l())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,l())},flush:()=>{r&&c()},destroy:()=>{i=!0,r=!1,t.clear()}}}const ii=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},ai=(e,t)=>{let n=M(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function oi(e,t={}){let n=ii(e,`[data-persona-composer-form]`),r=ii(e,`[data-persona-composer-input]`);if(!n||!r){let e=`[Persona] composer surface is missing required element(s): ${[!n&&`form`,!r&&`input`].filter(Boolean).join(`, `)}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||r))throw Error(e);return typeof console<`u`&&console.warn(e),null}let i={header:ii(e,`[data-persona-composer-header]`),body:ii(e,`[data-persona-composer-body]`),actionsStart:ii(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:ii(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:ii(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:ii(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:ii(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=ai(`persona-widget-composer__header`,`data-persona-composer-header`),n.parentNode?n.parentNode.insertBefore(o,n):e.appendChild(o));let s=i.body??r.parentElement??n,c=(e,t,n,r,i)=>{if(t)return t;a.add(e);let o=ai(n,r);return i.appendChild(o),o},l=c(`actionsStart`,i.actionsStart,`persona-widget-composer__left-actions`,`data-persona-composer-actions-start`,n),u=c(`actionsEnd`,i.actionsEnd,`persona-widget-composer__right-actions`,`data-persona-composer-actions-end`,n),d=c(`suggestions`,i.suggestions,`persona-widget-composer__suggestions`,`data-persona-composer-suggestions`,e),f=c(`status`,i.status,`persona-widget-composer__status`,`data-persona-composer-status`,e),p=[],m=(e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler,h=ii(e,`[data-persona-composer-attachment-input]`,`input[type="file"]`)??void 0;return{footer:e,form:n,input:r,header:o,body:s,actionsStart:l,actionsEnd:u,suggestions:d,status:f,attachmentInput:h,attachmentPreviews:ii(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:ii(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:ii(e,`[data-persona-composer-submit]`)??void 0,micButton:ii(e,`[data-persona-composer-mic]`)??void 0,synthesized:a,found:i,addListener:(e,t,n,r)=>{e.addEventListener(t,n,r),p.push({target:e,type:t,handler:n,options:r})},removeListener:(e,t,n,r)=>{e.removeEventListener(t,n,r),p=p.filter(r=>!m(r,{target:e,type:t,handler:n}))},destroy:()=>{for(let e of p)e.target.removeEventListener(e.type,e.handler,e.options);p=[]}}}const si=[`--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`],ci=`data-persona-menu-focus`,li=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function ui(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const di=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function fi(e){let t=e.label,n=!1,r=M(`div`,`persona-send-button-wrapper`),i=j(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${ue} ${xe}`,attrs:{type:`button`,"aria-haspopup":`menu`,"aria-expanded":`false`,"data-persona-composer-overflow-trigger":``}});r.appendChild(i);let a=j(`div`,{className:`persona-composer-overflow-menu`,attrs:{role:`menu`,tabindex:`-1`,"data-persona-composer-overflow-menu":``}}),o=()=>{let t=e.getButtonSize?.()??``;i.style.width=t,i.style.height=t,i.style.minWidth=t,i.style.minHeight=t,i.style.lineHeight=`1`,i.replaceChildren();let n=N(`plus`,24,`currentColor`,1.5);n?i.appendChild(n):i.textContent=`+`},s=()=>{i.setAttribute(`aria-label`,t),i.setAttribute(`title`,t),a.setAttribute(`aria-label`,t)};s(),o();let c=[],l=-1,u=!1,d=()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null},f=()=>{let e=d();for(let t of c){let n=!!e&&ui(t)===e;t.toggleAttribute(ci,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(ui).filter(e=>!di(e)),m=(e,t)=>{e.forEach((e,n)=>{e.setAttribute(`tabindex`,n===t?`0`:`-1`)})},h=e=>{let t=p();if(t.length===0)return;let n=(e%t.length+t.length)%t.length;l=n,m(t,n),t[n].focus(),f()},g=()=>r.ownerDocument??document,_=null,v=null,y=null,b=()=>{_&&=(g().removeEventListener(`focusin`,_,!0),null)},x=()=>{v&&=(a.removeEventListener(`focusin`,v),null),y&&=(a.removeEventListener(`pointerdown`,y,!0),null)},S=null,C=()=>(S||=Ot({anchor:i,content:a,placement:`top-start`,offset:6,onDismiss:()=>{i.setAttribute(`aria-expanded`,`false`),b()}}),S),w=()=>S?.isOpen===!0,T=(e=!1)=>{if(w()){S?.close(),i.setAttribute(`aria-expanded`,`false`),b(),x(),l=-1,u=!1;for(let e of c)e.removeAttribute(ci);e&&i.focus()}},E=(e=0,t=!1)=>{if(n||w())return;u=t,A(i,a,si),C().open(),i.setAttribute(`aria-expanded`,`true`);let o=p();m(o,-1),h(e<0?o.length-1:e),_=e=>{let t=typeof e.composedPath==`function`?e.composedPath():[];t.includes(a)||t.includes(r)||T()},g().addEventListener(`focusin`,_,!0),v=()=>f(),a.addEventListener(`focusin`,v),y=()=>{u=!1},a.addEventListener(`pointerdown`,y,!0)},D=e=>{e.preventDefault(),e.stopPropagation(),w()?T(!0):E(0)},ee=e=>{e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),u=!0,w()?h(0):E(0,!0)):e.key===`ArrowUp`&&(e.preventDefault(),u=!0,w()?h(-1):E(-1,!0))},te=e=>{switch(li.has(e.key)&&(u=!0),e.key){case`ArrowDown`:e.preventDefault(),h(l+1);return;case`ArrowUp`:e.preventDefault(),h(l-1);return;case`Home`:e.preventDefault(),h(0);return;case`End`:e.preventDefault(),h(p().length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),T(!0);return;case`Tab`:T(!0);return}};return i.addEventListener(`click`,D),i.addEventListener(`keydown`,ee),a.addEventListener(`keydown`,te),{trigger:r,triggerButton:i,panel:a,setItems:e=>{for(let t of c)e.includes(t)||t.removeAttribute(ci);if(c=[...e],!w())return;let t=p();m(t,Math.min(l,t.length-1)),f()},isOpen:w,open:()=>E(0),close:T,setLabel:e=>{e!==t&&(t=e,s())},applyButtonSize:o,destroy:()=>{n=!0,b(),x(),i.removeEventListener(`click`,D),i.removeEventListener(`keydown`,ee),a.removeEventListener(`keydown`,te),S?.destroy(),S=null,r.remove(),a.remove(),c=[]}}}const pi={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},mi=`data-persona-composer-action`,hi=`data-persona-composer-disable-when-streaming`,gi=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function _i(e,t){if(e===void 0)return null;if(typeof e==`number`)return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let r=M(`div`);r.style.position=`absolute`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`,r.style.height=`0`,r.style.width=e,t.appendChild(r);let i=r.getBoundingClientRect().width;return r.remove(),Number.isFinite(i)&&i>0?i:Number.isFinite(n)?n:null}function Y(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let r=n.getComputedStyle(e),i=(Number.parseFloat(r.paddingLeft)||0)+(Number.parseFloat(r.paddingRight)||0);return Math.max(0,t-i)}const vi=(e,t)=>{e&&typeof console<`u`&&console.warn(t)},yi=(e,t)=>t.includes(`:`)?t:`${e}:${t}`;function bi(e){let{debug:t}=e,n=[],r=/* @__PURE__ */ new Map,i=0,a=e=>{let i=r.get(e.id);i?vi(t,`[Persona] composer action "${e.id}" is already contributed by ${xi(i)}; the ${xi(e)} copy is ignored.`):(r.set(e.id,e),n.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:`bar`,order:t.order,sequence:i++,source:`core`,builtIn:t});let o=(e,n,r)=>{let o=r?yi(r,e.id):e.id,s=e.order??pi.custom;e.placement===`end`&&s>=pi.send&&(vi(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${pi.send-1}.`),s=pi.send-1),a({id:o,placement:e.placement,presentation:e.presentation??`bar`,order:s,sequence:i++,source:n,pluginId:r,action:e})};for(let t of e.configActions??[])o(t,`config`);for(let t of e.plugins){if(!t.contributeComposerActions)continue;let n;try{n=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<`u`&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of n??[])o(e,`plugin`,t.id)}return n.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}const xi=e=>e.source===`plugin`?`plugin "${e.pluginId}"`:e.source===`config`?`composer.actions`:`a core built-in`,Si=(e,t,n)=>e===void 0?n:typeof e==`function`?e(t)===!0:e===!0,Ci=e=>e.phase===`streaming`||e.text.trim().length>0||e.attachments.length>0;function wi(e,t){if(!e||e===`always`)return!0;let n=Ci(t);return e===`when-text`?n:!n}const Ti=e=>e.kind===`custom`,Ei=e=>e instanceof HTMLButtonElement?e:e.querySelector(`button`)??e,Di=e=>{let t=Ei(e);return t.getAttribute(`aria-label`)?.trim()||t.getAttribute(`title`)?.trim()||``};function Oi(e){let t=``,n=e=>{if(e.nodeType===Node.TEXT_NODE){t+=e.nodeValue??``;return}if(e.nodeType!==Node.ELEMENT_NODE)return;let r=e;typeof r.matches==`function`&&r.matches(`.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]`)||e.childNodes.forEach(n)};return n(e),t.trim()}const ki=e=>Oi(e).length===0;function Ai(e){let t=/* @__PURE__ */ new Map,n=[],r=!1,i=()=>e.getButtonSize?.(),a=(e,t)=>{let n=e.button;if(!n)return;n.setAttribute(`role`,`menuitem`),n.setAttribute(`tabindex`,`-1`),n.className=`persona-composer-overflow-menu__item`;for(let e of[`width`,`height`,`minWidth`,`minHeight`,`fontSize`,`color`,`backgroundColor`])n.style[e]=``;n.style.lineHeight=`1`,t.tooltipText?n.setAttribute(`title`,t.tooltipText):n.removeAttribute(`title`),n.replaceChildren();let r=M(`span`,`persona-composer-overflow-menu__icon`);if(t.iconName){let e=N(t.iconName,16,`currentColor`,1.5);e&&r.appendChild(e)}let i=M(`span`,`persona-composer-overflow-menu__label`);i.textContent=t.shortLabel??t.label,n.append(r,i)},o=(e,t)=>{let n=e.button;if(!n)return;if(n.setAttribute(`aria-label`,t.label),t.pressed===void 0?n.removeAttribute(`aria-pressed`):n.setAttribute(`aria-pressed`,t.pressed?`true`:`false`),n.toggleAttribute(hi,t.disableWhenStreaming===!0),e.mode===`menu`){e.tooltip?.destroy(),e.tooltip=void 0,a(e,t);return}n.removeAttribute(`role`),n.removeAttribute(`tabindex`),n.removeAttribute(`title`);let r=i(),o=!!t.shortLabel;if(n.className=Me(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button`,ue,xe,o&&`persona-composer-action-button--text persona-gap-1 persona-text-sm`),n.style.width=r&&!o?r:``,n.style.height=r??``,n.style.minWidth=r&&!o?r:``,n.style.minHeight=r??``,n.style.fontSize=o?``:`18px`,n.style.lineHeight=`1`,n.style.color=t.iconColor??``,n.style.backgroundColor=t.backgroundColor??``,n.replaceChildren(),t.iconName){let e=N(t.iconName,24,`currentColor`,1.5);e&&n.appendChild(e)}if(o){let e=M(`span`,`persona-composer-action-button__label`);e.textContent=t.shortLabel,n.appendChild(e)}else n.firstChild||(n.textContent=t.label);e.tooltip?.destroy(),e.tooltip=S({anchor:n,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,n)=>{let r=t.action,i=j(`button`,{attrs:{type:`button`}}),a=i;if(n===`bar`){let e=M(`div`,`persona-send-button-wrapper`);e.appendChild(i),a=e}a.setAttribute(mi,t.id);let s={resolved:t,element:a,button:i,owned:!0,managed:!0,busy:!1,visible:!0,mode:n},c=t=>{if(t.preventDefault(),t.stopPropagation(),s.busy||i.disabled)return;let n=s.resolved.action;s.mode===`menu`&&p?.close(!0);let r;try{r=n.onSelect(e.actionContext,t)}catch(t){e.reportError(t,{actionId:s.resolved.id});return}r&&typeof r.then==`function`&&(s.busy=!0,i.setAttribute(`aria-busy`,`true`),r.catch(t=>{e.reportError(t,{actionId:s.resolved.id})}).finally(()=>{s.busy=!1,i.removeAttribute(`aria-busy`)}))};return i.addEventListener(`click`,c),s.detach=()=>i.removeEventListener(`click`,c),o(s,r),s},c=t=>{let n=t.action,r;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(n){return e.reportError(n,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(mi,t.id),r.element.toggleAttribute(hi,n.disableWhenStreaming===!0),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:`bar`}):null},l=(e,t)=>{if(e.builtIn){let t=e.builtIn.element;return t?{resolved:e,element:t,owned:!1,managed:e.builtIn.managed===!0,busy:!1,visible:!0,mode:`bar`}:null}let n=e.action;return n?Ti(n)?c(e):s(e,t):null},u=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(n){e.reportError(n,{actionId:t.resolved.id})}t.element.remove()}},d=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(!r.managed)continue;let i=null;for(let r=n+1;r<t.length;r++){let n=t[r];if(!n.managed&&n.element.parentElement===e){i=n.element;break}}i?(r.element.parentElement!==e||r.element.nextSibling!==i)&&e.insertBefore(r.element,i):e.lastChild!==r.element&&e.appendChild(r.element)}},f=(e,t)=>{if(e.button){e.button.disabled=t;return}if(!e.owned)return;let n=e.element;n.toggleAttribute(`data-disabled`,t),n.setAttribute(`aria-disabled`,t?`true`:`false`);let r=n instanceof HTMLButtonElement||n instanceof HTMLSelectElement||n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n:n.querySelector(`button, select, input, textarea`);r&&(r.disabled=t)},p=null,m=null,h=null,g=0,_=()=>{let t=e.getOverflow?.();return t?.enabled===!0?t:void 0},v=()=>(p?p.setLabel(e.getOverflowLabel?.()??`More actions`):p=fi({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:i}),p),y=e=>{m!==e&&(h?.disconnect(),m=e,g=Y(e),typeof ResizeObserver<`u`&&(h=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??Y(e);n!==g&&(g=n,E())}),h.observe(e)))},b=(e,t)=>{let n=_i(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=g||Y(t);return r>0&&r<n},x=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=gi(e.resolved.id);return n&&t.includeBuiltIns?.includes(n)?`menu`:`bar`}let r=e.resolved.presentation;return r===`overflow`||r===`auto`&&n?`menu`:`bar`},C=e=>{let t=e.menuSlot;if(!t)return;if(!ki(e.element)){e.menuLabel?.remove(),e.menuLabel=void 0;return}let n=Di(e.element);n?(e.menuLabel||=M(`span`,`persona-composer-overflow-menu__label`),e.menuLabel.textContent!==n&&(e.menuLabel.textContent=n),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},w=(e,n)=>{if(e.mode===n)return e;let r=e.resolved.action;if(r&&!Ti(r)){u(e),t.delete(e.resolved.id);let r=s(e.resolved,n);return t.set(e.resolved.id,r),r}if(n===`menu`){let t=j(`div`,{className:`persona-composer-overflow-menu__slot`,attrs:{role:`none`,[ae]:``}});t.appendChild(e.element),oe(Ei(e.element)),e.menuSlot=t;let n=t=>{let n=Ei(e.element);if(n.disabled)return;let r=t.target===n||n.contains(t.target);p?.close(!0),r||n.click()};t.addEventListener(`click`,n,!0),e.detachMenuSlot=()=>t.removeEventListener(`click`,n,!0),e.managed=!0,C(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=n,e},T=(e,t)=>{let n=t.map(e=>e.menuSlot??e.element);for(n.forEach((t,n)=>{let r=e.children[n];r!==t&&(r?e.insertBefore(t,r):e.appendChild(t))});e.children.length>n.length;)e.lastElementChild?.remove()},E=()=>{if(r)return;let i=e.getBindings();if(!i)return;let a=e.getState(),o=a.phase===`streaming`,s=_();s&&y(i.footer);let c=s?b(s,i.footer):!1,l={start:[],end:[]},u=[];for(let e of n){let n=t.get(e.id);if(!n)continue;let r=e.action,i=!r||Si(r.visible,a,!0)&&wi(r.visibility,a);if(n.visible!==i&&(n.visible=i,!i&&n.managed&&(n.menuSlot??n.element).remove()),i){if(n=w(n,x(n,s,c)),r){let e=Si(r.disabled,a,!1)||r.disableWhenStreaming===!0&&o;f(n,e),!Ti(r)&&r.pressed!==void 0&&n.button?.setAttribute(`aria-pressed`,r.pressed?`true`:`false`)}n.mode===`menu`?(C(n),u.push(n)):l[e.placement].push(n)}}if(u.length>0){let e=v();T(e.panel,u),e.setItems(u.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(s?.order)?s?.order:pi.overflow,n=l.start.findIndex(e=>e.resolved.order>t),r={resolved:{id:`core:overflow`,placement:`start`,presentation:`bar`,order:t,sequence:-1,source:`core`},element:e.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:`bar`};l.start.splice(n<0?l.start.length:n,0,r)}else p&&(p.close(),p.trigger.remove(),p.setItems([]));d(i.actionsStart,l.start),d(i.actionsEnd,l.end)};return{resolve:()=>{if(r)return;let i=bi(e.collect()),a=new Set(i.map(e=>e.id));for(let[e,n]of t)a.has(e)||(u(n),t.delete(e));for(let e of i){let n=t.get(e.id);if(!n){let n=l(e,`bar`);n&&t.set(e.id,n);continue}let r=n.resolved.action,i=e.action;if(!!r!=!!i||r&&i&&Ti(r)!==Ti(i)||r&&i&&Ti(r)&&Ti(i)&&r.render!==i.render){u(n),t.delete(e.id);let r=l(e,n.mode);r&&t.set(e.id,r)}else n.resolved=e,e.builtIn?(n.managed=e.builtIn.managed===!0||n.mode===`menu`,e.builtIn.element&&n.mode===`bar`&&(n.element=e.builtIn.element)):i&&!Ti(i)?o(n,i):i&&n.element.toggleAttribute(hi,i.disableWhenStreaming===!0)}n=i,E()},sync:E,getResolved:()=>n,getOverflowMenu:()=>p,destroy:()=>{if(!r){r=!0,h?.disconnect(),h=null,m=null;for(let e of t.values())u(e);t.clear(),p?.destroy(),p=null,n=[]}}}}const ji=[`--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`],Mi=()=>({wrapper:j(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:j(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function Ni(e){let t=e.label??`Model`,n=e.presentation??`native`,r=null,i=t=>{let n=e.getSelectedModelId();return t.find(e=>e.id===n)??t[0]},a=()=>{let n=j(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":t,"data-persona-composer-model-picker":``}}),a=``,o=()=>{let t=e.getModels(),r=t.map(e=>`${e.id}:${e.label}`).join(`|`);r!==a&&(a=r,n.replaceChildren(...t.map(e=>{let t=j(`option`,{attrs:{value:e.id}});return t.textContent=e.label,t}))),n.value=i(t)?.id??``};o(),r=o;let s=()=>{n.value&&e.onSelect(n.value)};n.addEventListener(`change`,s);let c=e=>e.stopPropagation();n.addEventListener(`click`,c);let{wrapper:l,chevron:u}=Mi();return l.append(n,u),{element:l,destroy:()=>{r===o&&(r=null),n.removeEventListener(`change`,s),n.removeEventListener(`click`,c)}}},o=()=>{let n=j(`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`}}),a=M(`span`,`persona-composer-model-picker-label`),o=M(`span`,`persona-composer-model-picker-suffix`);n.append(a,o);let s=j(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":t,"data-persona-composer-model-menu":``}}),c=/* @__PURE__ */ new Map,l=``,u=null,d=()=>u?.isOpen===!0,f=(e=!1)=>{d()&&(u?.close(),n.setAttribute(`aria-expanded`,`false`),e&&n.focus())},p=e=>{let t=[...c.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(d())return;u||=Ot({anchor:n,content:s,placement:`top-start`,offset:6,onDismiss:()=>n.setAttribute(`aria-expanded`,`false`)}),A(n,s,ji),u.open(),n.setAttribute(`aria-expanded`,`true`);let r=[...c.keys()].indexOf(i(e.getModels())?.id??``);p(t??(r>=0?r:0))},h=t=>{f(!0),e.onSelect(t)},g=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&h(t)},_=e=>{let t=j(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":e.id}});if(e.icon){let n=N(e.icon,16,`currentColor`,1.5);if(n){let e=M(`span`,`persona-composer-model-option-icon`);e.appendChild(n),t.appendChild(e)}}let n=M(`span`,`persona-composer-model-option-body`),r=M(`span`,`persona-composer-model-option-label`);if(r.textContent=e.label,n.appendChild(r),e.description){let t=M(`span`,`persona-composer-model-option-description`);t.textContent=e.description,n.appendChild(t)}t.appendChild(n);let i=M(`span`,`persona-composer-model-option-check`);i.setAttribute(`aria-hidden`,`true`);let a=N(`check`,16,`currentColor`,2);return a&&i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,g),t},v=()=>{let r=e.getModels(),u=r.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(u!==l){l=u;for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),s.replaceChildren(...r.map(e=>{let t=_(e);return c.set(e.id,t),t}))}let d=i(r);for(let[e,t]of c)t.setAttribute(`aria-selected`,String(e===d?.id));a.textContent=d?.label??``;let f=e.getSuffix?.()??``;o.textContent=f,n.setAttribute(`aria-label`,[t,[d?.label,f].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};v(),r=v;let y=e=>{e.preventDefault(),e.stopPropagation(),d()?f(!0):m()},b=e=>{e.key===`ArrowDown`?(e.preventDefault(),d()?p(0):m(0)):e.key===`ArrowUp`&&(e.preventDefault(),d()?p(-1):m(-1))},x=e=>{let t=[...c.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),p(n+1);return;case`ArrowUp`:e.preventDefault(),p(n-1);return;case`Home`:e.preventDefault(),p(0);return;case`End`:e.preventDefault(),p(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),f(!0);return;case`Tab`:f(!0);return}};n.addEventListener(`click`,y),n.addEventListener(`keydown`,b),s.addEventListener(`keydown`,x);let{wrapper:S,chevron:C}=Mi();return S.append(n,C),{element:S,destroy:()=>{r===v&&(r=null),n.removeEventListener(`click`,y),n.removeEventListener(`keydown`,b),s.removeEventListener(`keydown`,x);for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),u?.destroy(),u=null,s.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:n===`popover`?`bar`:`auto`,label:t,render:()=>n===`popover`?o():a()},repaint:()=>r?.()}}function Pi(e){let t=e.row,n=``,r=!1,i=new Set(e.initialIds??[]),a=t=>{let n=j(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=M(`span`,`persona-mention-chip-icon`),r=N(t.iconName,12,`currentColor`,1.5);r&&e.appendChild(r),n.appendChild(e)}let r=M(`span`,`persona-mention-chip-label`);r.textContent=t.shortLabel??t.label,n.appendChild(r);let i=j(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label}`}}),a=N(`x`,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=`×`,i.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),e.onRemove(t.id)}),n.appendChild(i),n},o=()=>Array.from(t.querySelectorAll(`:scope > [data-persona-composer-mode]`)),s=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let n=()=>{e.remove(),Et(t)},r=t.ownerDocument.defaultView,i=typeof r?.getComputedStyle==`function`?r.getComputedStyle(e).animationName:``;!i||i===`none`?n():(e.addEventListener(`animationend`,n,{once:!0}),e.addEventListener(`animationcancel`,n,{once:!0}))},c=()=>{for(let e of o())e.remove()};return{element:t,render:(e,c)=>{if(r)return;let l=c.filter(t=>e.includes(t.id)),u=l.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===n)return;n=u;let d=/* @__PURE__ */ new Map;for(let e of o()){let t=e.getAttribute(`data-persona-composer-mode`);t&&l.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?d.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||s(e)}let f=t.firstChild;for(let e of l){let n=d.get(e.id);n||(n=a(e),i.has(e.id)||(n.setAttribute(`data-persona-chip-enter`,``),n.addEventListener(`animationend`,()=>n?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),i.delete(e.id),n!==f&&t.insertBefore(n,f),f=n.nextSibling}Et(t)},destroy:()=>{r=!0,c(),Et(t)}}}const Fi=e=>`core:mode:${e}`,Ii=e=>Math.min(300+e,499),Li=e=>`core:mode-group:${e}`;function Ri(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function zi(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function Bi(e,t){return e?.length?e.filter(e=>!Ri(e.groupId,t)&&!zi(e.groupId,t)):[]}const Vi=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function Hi(e,t,n,r){let i=n.find(e=>e.id===t);if(!i)return[...e];let a=e.includes(t),o=new Set(e);if(a)o.delete(t);else{if(Vi(i,r)===`single`){let e=n.filter(e=>e.groupId===i.groupId).map(e=>e.id);o=new Set([...o].filter(t=>!e.includes(t)))}o.add(t)}return n.filter(e=>o.has(e.id)).map(e=>e.id)}function Ui(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function Wi(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function Gi(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}function Ki(e){let t=null;return{action:{id:Li(e.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:e.getGroup()?.label??e.groupId,render:()=>{let n=j(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":e.groupId}}),r=/* @__PURE__ */ new Map,i=``,a=t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getAttribute(`data-persona-composer-mode`);n&&(e.getActiveIds().includes(n)&&e.getGroup()?.selection===`single`||e.onSelect(n))},o=e=>{let t=j(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let n=N(e.iconName,16,`currentColor`,1.5);n&&t.appendChild(n)}let n=M(`span`,`persona-composer-segmented-label`);return n.textContent=e.shortLabel??e.label,t.appendChild(n),t.addEventListener(`click`,a),t},s=()=>{let t=e.getGroup();t?.label?(n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,t.label)):(n.removeAttribute(`role`),n.removeAttribute(`aria-label`));let s=e.getModes(),c=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(c!==i){i=c;for(let e of r.values())e.removeEventListener(`click`,a);r.clear();let e=s.map(e=>{let t=o(e);return r.set(e.id,t),t});n.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of r)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return s(),t=s,{element:n,destroy:()=>{t===s&&(t=null);for(let e of r.values())e.removeEventListener(`click`,a);r.clear()}}}},repaint:()=>t?.()}}function qi(e){let t=j(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=M(`span`,`persona-composer-quote-bar`),i=M(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=M(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=j(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=Cr(n.text),i.appendChild(a);let o=j(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=N(`x`,12,`currentColor`,2);s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(r,i,o)};return{element:t,render:e=>{if(r)return;let a=e?`${e.sourceLabel??``}${e.text}`:``;a!==n&&(n=a,e?(i(e),t.style.display=`flex`):(t.replaceChildren(),t.style.display=`none`))},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}function Ji(e){let t=j(`div`,{className:`persona-composer-pending`,attrs:{"data-persona-composer-pending":``}});t.style.display=`none`;let n,r=!1,i=(e,t,n,r)=>{let i=j(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=N(e,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=t,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},a=e=>{let t=Cr(e.text??``,90);if(t)return t;let n=e.contentParts?.length??0;return n>0?n===1?`1 attachment`:`${n} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(`, `):`Queued message`};return{element:t,render:o=>{if(r||o===n)return;if(n=o,!o){t.replaceChildren(),t.style.display=`none`;return}let s=M(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=j(`div`,{className:`persona-composer-pending-text`,attrs:{"data-persona-composer-pending-text":``}});c.textContent=a(o),t.replaceChildren(s,c,i(`pencil`,e.editLabel??`Edit queued message`,`data-persona-composer-pending-edit`,e.onEdit),i(`x`,e.removeLabel??`Remove queued message`,`data-persona-composer-pending-remove`,e.onRemove)),t.style.display=`flex`},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}function Yi(e){let t=j(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=j(`textarea`,{className:`persona-message-edit-input`,attrs:{rows:`1`,dir:`auto`,"aria-label":`Edit message`,"data-persona-message-edit-input":``}});n.value=e.initialText;let r=()=>{n.style.height=`auto`,n.style.height=`${n.scrollHeight}px`};n.addEventListener(`input`,r);let i=M(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=j(`button`,{className:`persona-message-edit-button ${t}`,attrs:{type:`button`,[n]:``},text:e});return i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},o=()=>{let t=n.value.trim();t&&e.onSave(t)};return i.append(a(e.cancelLabel??`Cancel`,`persona-message-edit-cancel`,`data-persona-message-edit-cancel`,e.onCancel),a(e.saveLabel??`Send`,`persona-message-edit-save`,`data-persona-message-edit-save`,o)),n.addEventListener(`keydown`,t=>{t.key===`Escape`?(t.preventDefault(),t.stopPropagation(),e.onCancel()):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),o())}),t.append(n,i),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let e=n.value.length;n.setSelectionRange(e,e),r()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Xi(e){let t=e.text??``;if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function Zi(e,t){if(!e||typeof e.text!=`string`)return;let n=new Set(t.mentionSourceIds),r=(e.mentionRefs??[]).filter(e=>n.has(e.sourceId)),i=r.length===(e.mentionRefs?.length??0)&&r.length>0,a=new Set(t.modes.map(e=>e.id)),o=(e.activeModeIds??[]).filter(e=>a.has(e)),s=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...i?{mentionRefs:r}:{},...i&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...s?{selectedModelId:s}:{},...o.length?{activeModeIds:o}:{},...e.quote?.text?{quote:e.quote}:{}}}function Qi(e){let t=e.delay??500,n=null,r=!1,i=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{r||(i(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{r||n===null||(i(),e.write())},cancel:i,destroy:()=>{r=!0,i()}}}function $i(e){return e.wrapped||e.text.includes(`
|
|
12
|
+
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function ea(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function ta(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-o>a*1.5}function na(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function ra(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const ia=e=>typeof e?.then==`function`;function aa(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function oa(e,t,n){let r;try{r=e(na(t),{signal:n})}catch(e){return{status:`error`,error:e}}return ia(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:aa(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):aa(t,r)}const sa=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),ca={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`},la=`16px`,ua=`transparent`,da={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:(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?`0px`:`${t/4}rem`;return e})(),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`}},fa={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`}},pa={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:ve,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:la,canvasBackground:ua,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`}}},ma=da.colors.gray,ha={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},X={...da,colors:{...da.colors,gray:ma}},ga={...da,colors:{...da.colors,gray:ha},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},_a=fa,va={...fa,colors:{...fa.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...fa.typography,fontSize:`14px`,lineHeight:`1.5`}},ya=pa,ba={...pa,launcher:ca,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:{...pa.input,borderRadius:`palette.radius.full`},introCard:{...pa.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...pa.suggestion.chip,fontWeight:`400`},card:{...pa.suggestion.card,fontWeight:`400`},list:{...pa.suggestion.list,fontWeight:`400`}},panel:{...pa.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...pa.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:{...pa.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...pa.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:{...pa.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},composer:{...pa.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)`}},xa=e=>T({future:e}),Sa=e=>xa(e)===`v5`?{palette:ga,semantic:va,components:ba}:{palette:X,semantic:_a,components:ya};function Ca(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?Ca(e,r):r}function wa(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=Ca(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function Ta(e){let t=[],n=[];return e.palette||t.push({path:`palette`,message:`Theme must include a palette`,severity:`error`}),e.semantic||n.push({path:`semantic`,message:`No semantic tokens defined - defaults will be used`,severity:`warning`}),e.components||n.push({path:`components`,message:`No component tokens defined - defaults will be used`,severity:`warning`}),{valid:t.length===0,errors:t,warnings:n}}function Ea(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?Ea(t,r):r}return n}function Da(e,t){return t?Ea(e,t):e}function Oa(e,t={}){let n=Sa(t.future),r={palette:n.palette,semantic:n.semantic,components:n.components},i={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:Da(r.components,e?.components)},a=e?.components?.activity;for(let e of[`toolBubble`,`reasoningBubble`])for(let t of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[t]!==void 0&&(i.components[e][t]=a[t]);let o=e?.components?.collapsibleWidget?.surface;o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=e?.components?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=Ta(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const ka=e=>e.trim()===`0`?`0px`:e,Aa=`--persona-`,ja=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},Ma=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[Aa+n],t!==void 0)break;t!==void 0&&(e[Aa+n]=t)}};function Na(e){let t=wa(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}Ma(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 r=n[`--persona-components-launcher-foreground`];n[`--persona-launcher-fg-muted`]=r&&r!==n[`--persona-primary`]?`color-mix(in srgb, ${r} 70%, transparent)`:n[`--persona-muted`],Ma(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`]]),Ma(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`]}`,Ma(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`]??`16px`,n[`--persona-panel-canvas-bg`]=n[`--persona-components-panel-canvasBackground`]??`transparent`,Ma(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`]]),Ma(n,[[`header-bg`,`components-header-background`,`surface`]]);let i=n[`--persona-header-bg`],a=n[`--persona-components-header-foreground`],o=a?`color-mix(in srgb, ${a} 72%, ${i})`:void 0;n[`--persona-header-border`]=n[`--persona-components-header-border`]??(a?`color-mix(in srgb, ${a} 14%, ${i})`:void 0)??n[`--persona-divider`],Ma(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`]??a??n[`--persona-primary`],n[`--persona-header-subtitle-fg`]=n[`--persona-components-header-subtitle-color`]??n[`--persona-components-header-subtitleForeground`]??o??n[`--persona-text-muted`],n[`--persona-header-action-icon-fg`]=n[`--persona-components-header-actionIconForeground`]??o??n[`--persona-muted`],Ma(n,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=20px`]]);let s=e.components?.header;s?.shadow&&(n[`--persona-header-shadow`]=s.shadow),s?.borderBottom&&(n[`--persona-header-border-bottom`]=s.borderBottom),s?.minHeight&&(n[`--persona-header-min-height`]=s.minHeight);let c=n[`--persona-components-history-railHeader-background`];c&&(n[`--persona-history-rail-header-bg`]=c);let l=n[`--persona-components-history-railHeader-border`];l&&(n[`--persona-history-rail-header-border`]=l);let u=n[`--persona-components-history-railHeader-minHeight`];u&&(n[`--persona-history-rail-header-min-height`]=u);for(let[e,t]of[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]]){let r=n[`--persona-components-history-overlay-${e}`];r&&(n[`--persona-history-overlay-${t}`]=r)}for(let[e,t]of[[`background`,`bg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-history-menu-${e}`];r&&(n[`--persona-history-menu-${t}`]=r)}let d=e.components?.history?.motion;if(d){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(d.enterDurationMs);t!==void 0&&(n[`--persona-history-enter-ms`]=t);let r=e(d.exitDurationMs);r!==void 0&&(n[`--persona-history-exit-ms`]=r),d.enterEasing&&(n[`--persona-history-enter-easing`]=d.enterEasing),d.exitEasing&&(n[`--persona-history-exit-easing`]=d.exitEasing)}let f=n[`--persona-components-history-dangerForeground`];f&&(n[`--persona-history-danger-fg`]=f),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 e of[`scrim`,`shadow`]){let t=n[`--persona-components-history-confirm-${e}`];t&&(n[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]]){let r=n[`--persona-components-tooltip-${e}`];r&&(n[`--persona-tooltip-${t}`]=r)}e.components?.tooltip?.arrow===!1&&(n[`--persona-tooltip-arrow-display`]=`none`);for(let[e,t]of[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-messageActions-${e}`];r&&(n[`--persona-message-action-${t}`]=r)}Ma(n,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let p=n[`--persona-components-introCard-background`],m=n[`--persona-components-introCard-shadow`],h=(!p||p===`transparent`||p===`none`)&&(!m||m===`none`),g=n[`--persona-components-introCard-padding`]??`1.5rem`;n[`--persona-intro-card-padding`]=h&&g===`1.5rem`?`1.5rem 0`:g,Ma(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`]]),Ma(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 _=n[`--persona-components-markdown-heading-h1-fontSize`];_&&(n[`--persona-md-h1-size`]=_);let v=n[`--persona-components-markdown-heading-h1-fontWeight`];v&&(n[`--persona-md-h1-weight`]=v);let y=n[`--persona-components-markdown-heading-h2-fontSize`];y&&(n[`--persona-md-h2-size`]=y);let b=n[`--persona-components-markdown-heading-h2-fontWeight`];b&&(n[`--persona-md-h2-weight`]=b);let x=n[`--persona-components-markdown-prose-fontFamily`];x&&x!==`inherit`&&(n[`--persona-md-prose-font-family`]=x),Ma(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`]]),Ma(n,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),Ma(n,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),Ma(n,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),Ma(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`]]);for(let[e,t]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=n[`--persona-components-collapsibleWidget-${e}`]??n[`--persona-${t}`];r!==void 0&&(n[`--persona-cw-${e}`]=r,n[`--cw-${e}`]=r)}Ma(n,[[`message-border`,`components-message-border`,`border`]]),Ma(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 S=e.components,C=S?.iconButton;C&&(C.background&&(n[`--persona-icon-btn-bg`]=C.background),C.border&&(n[`--persona-icon-btn-border`]=C.border),C.color&&(n[`--persona-icon-btn-color`]=C.color),C.padding&&(n[`--persona-icon-btn-padding`]=C.padding),C.borderRadius&&(n[`--persona-icon-btn-radius`]=C.borderRadius),C.hoverBackground&&(n[`--persona-icon-btn-hover-bg`]=C.hoverBackground),C.hoverColor&&(n[`--persona-icon-btn-hover-color`]=C.hoverColor),C.activeBackground&&(n[`--persona-icon-btn-active-bg`]=C.activeBackground),C.activeBorder&&(n[`--persona-icon-btn-active-border`]=C.activeBorder));let w=S?.labelButton;w&&(w.background&&(n[`--persona-label-btn-bg`]=w.background),w.border&&(n[`--persona-label-btn-border`]=w.border),w.color&&(n[`--persona-label-btn-color`]=w.color),w.padding&&(n[`--persona-label-btn-padding`]=w.padding),w.borderRadius&&(n[`--persona-label-btn-radius`]=w.borderRadius),w.hoverBackground&&(n[`--persona-label-btn-hover-bg`]=w.hoverBackground),w.fontSize&&(n[`--persona-label-btn-font-size`]=w.fontSize),w.gap&&(n[`--persona-label-btn-gap`]=w.gap));let T=S?.toggleGroup;T&&(T.gap&&(n[`--persona-toggle-group-gap`]=T.gap),T.borderRadius&&(n[`--persona-toggle-group-radius`]=T.borderRadius));let E=S?.artifact;if(E?.toolbar){let t=E.toolbar;t.iconHoverColor&&(n[`--persona-artifact-toolbar-icon-hover-color`]=t.iconHoverColor),t.iconHoverBackground&&(n[`--persona-artifact-toolbar-icon-hover-bg`]=t.iconHoverBackground),t.iconPadding&&(n[`--persona-artifact-toolbar-icon-padding`]=t.iconPadding),t.iconBorderRadius&&(n[`--persona-artifact-toolbar-icon-radius`]=t.iconBorderRadius),t.iconBorder&&(n[`--persona-artifact-toolbar-icon-border`]=t.iconBorder),t.toggleGroupGap&&(n[`--persona-artifact-toolbar-toggle-group-gap`]=ka(t.toggleGroupGap)),t.toggleBorderRadius&&(n[`--persona-artifact-toolbar-toggle-radius`]=t.toggleBorderRadius),t.toggleGroupPadding&&(n[`--persona-artifact-toolbar-toggle-group-padding`]=ka(t.toggleGroupPadding)),t.toggleGroupBorder&&(n[`--persona-artifact-toolbar-toggle-group-border`]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(n[`--persona-artifact-toolbar-toggle-group-radius`]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(n[`--persona-artifact-toolbar-toggle-group-bg`]=Ca(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(n[`--persona-artifact-toolbar-copy-bg`]=t.copyBackground),t.copyBorder&&(n[`--persona-artifact-toolbar-copy-border`]=t.copyBorder),t.copyColor&&(n[`--persona-artifact-toolbar-copy-color`]=t.copyColor),t.copyBorderRadius&&(n[`--persona-artifact-toolbar-copy-radius`]=ka(t.copyBorderRadius)),t.copyPadding&&(n[`--persona-artifact-toolbar-copy-padding`]=t.copyPadding),t.copyMenuBackground&&(n[`--persona-artifact-toolbar-copy-menu-bg`]=t.copyMenuBackground,n[`--persona-dropdown-bg`]=n[`--persona-dropdown-bg`]??t.copyMenuBackground),t.copyMenuBorder&&(n[`--persona-artifact-toolbar-copy-menu-border`]=t.copyMenuBorder,n[`--persona-dropdown-border`]=n[`--persona-dropdown-border`]??t.copyMenuBorder),t.copyMenuShadow&&(n[`--persona-artifact-toolbar-copy-menu-shadow`]=t.copyMenuShadow,n[`--persona-dropdown-shadow`]=n[`--persona-dropdown-shadow`]??t.copyMenuShadow),t.copyMenuBorderRadius&&(n[`--persona-artifact-toolbar-copy-menu-radius`]=t.copyMenuBorderRadius,n[`--persona-dropdown-radius`]=n[`--persona-dropdown-radius`]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(n[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=t.copyMenuItemHoverBackground,n[`--persona-dropdown-item-hover-bg`]=n[`--persona-dropdown-item-hover-bg`]??t.copyMenuItemHoverBackground),t.iconBackground&&(n[`--persona-artifact-toolbar-icon-bg`]=t.iconBackground),t.toolbarBorder&&(n[`--persona-artifact-toolbar-border`]=t.toolbarBorder)}if(E?.tab){let e=E.tab;e.background&&(n[`--persona-artifact-tab-bg`]=e.background),e.activeBackground&&(n[`--persona-artifact-tab-active-bg`]=e.activeBackground),e.activeBorder&&(n[`--persona-artifact-tab-active-border`]=e.activeBorder),e.borderRadius&&(n[`--persona-artifact-tab-radius`]=e.borderRadius),e.textColor&&(n[`--persona-artifact-tab-color`]=e.textColor),e.hoverBackground&&(n[`--persona-artifact-tab-hover-bg`]=e.hoverBackground),e.listBackground&&(n[`--persona-artifact-tab-list-bg`]=e.listBackground),e.listBorderColor&&(n[`--persona-artifact-tab-list-border-color`]=e.listBorderColor),e.listPadding&&(n[`--persona-artifact-tab-list-padding`]=e.listPadding)}if(E?.pane){let t=E.pane;t.toolbarBackground&&(n[`--persona-artifact-toolbar-bg`]=Ca(e,t.toolbarBackground)??t.toolbarBackground)}if(E?.card){let e=E.card;e.background&&(n[`--persona-artifact-card-bg`]=e.background),e.border&&(n[`--persona-artifact-card-border`]=e.border),e.borderRadius&&(n[`--persona-artifact-card-radius`]=e.borderRadius),e.hoverBackground&&(n[`--persona-artifact-card-hover-bg`]=e.hoverBackground),e.hoverBorderColor&&(n[`--persona-artifact-card-hover-border`]=e.hoverBorderColor)}if(E?.inline){let t=E.inline;t.background&&(n[`--persona-artifact-inline-bg`]=Ca(e,t.background)??t.background),t.border&&(n[`--persona-artifact-inline-border`]=t.border),t.borderRadius&&(n[`--persona-artifact-inline-radius`]=t.borderRadius),t.chromeBackground&&(n[`--persona-artifact-inline-chrome-bg`]=Ca(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(n[`--persona-artifact-inline-chrome-border`]=Ca(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(n[`--persona-artifact-inline-title-color`]=Ca(e,t.titleColor)??t.titleColor),t.mutedColor&&(n[`--persona-artifact-inline-muted-color`]=Ca(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(n[`--persona-artifact-inline-frame-height`]=t.frameHeight)}let D=S?.code;D&&(D.keywordColor&&(n[`--persona-code-keyword-color`]=D.keywordColor),D.stringColor&&(n[`--persona-code-string-color`]=D.stringColor),D.commentColor&&(n[`--persona-code-comment-color`]=D.commentColor),D.numberColor&&(n[`--persona-code-number-color`]=D.numberColor),D.tagColor&&(n[`--persona-code-tag-color`]=D.tagColor),D.attrColor&&(n[`--persona-code-attr-color`]=D.attrColor),D.propertyColor&&(n[`--persona-code-property-color`]=D.propertyColor),D.lineNumberColor&&(n[`--persona-code-line-number-color`]=D.lineNumberColor),D.gutterBorderColor&&(n[`--persona-code-gutter-border-color`]=D.gutterBorderColor),D.background&&(n[`--persona-code-bg`]=Ca(e,D.background)??D.background));let ee=n[`--persona-surface`],te=n[`--persona-container`],ne=n[`--persona-palette-colors-gray-100`]??`#f3f4f6`,re=n[`--persona-palette-colors-gray-200`]??`#e5e7eb`,ie=n[`--persona-palette-colors-gray-300`]??`#d1d5db`,ae=!te||te===ee,oe=ja(ee??n[`--persona-background`]),se=ae&&oe!==void 0&&oe<.179,O=se?`rgba(255, 255, 255, 0.08)`:ne,ce=se?`rgba(255, 255, 255, 0.12)`:re,le=se?`rgba(255, 255, 255, 0.16)`:ie,ue=ae?O:te,de=ae?ce:te;return n[`--persona-icon-btn-hover-bg`]=n[`--persona-icon-btn-hover-bg`]??ue,n[`--persona-icon-btn-active-bg`]=n[`--persona-icon-btn-active-bg`]??de,ae&&(n[`--persona-icon-btn-active-border`]=n[`--persona-icon-btn-active-border`]??le),n[`--persona-label-btn-hover-bg`]=n[`--persona-label-btn-hover-bg`]??ue,n[`--persona-artifact-tab-hover-bg`]=n[`--persona-artifact-tab-hover-bg`]??ue,n[`--persona-artifact-card-hover-bg`]=n[`--persona-artifact-card-hover-bg`]??ue,n}const Pa=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),Fa=(e,t)=>{if(!t||!Pa(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(Ka(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:T(t)===`v5`?`400px`:`420px`}}}:e},Ia={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`}}},La={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)`}}}},Ra=Ia,za={...Ra,colors:{...Ra.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`}}},Ba=La,Va={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:{...La.components,button:{...La.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:{...La.components?.eventStream,badge:{...La.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`}}}}},Ha=e=>T({future:e})===`v5`?{palette:za,components:Va}:{palette:Ra,components:Ba},Ua=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},Wa=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,Ga=e=>{let t=e?.colorScheme??`light`;return t===`light`?`light`:t===`dark`?`dark`:Wa()},Ka=e=>Ga(e),qa=(e,t={})=>Oa(e,t),Ja=(e,t={})=>{let n=Ha(t.future),r=ce(n.components,e??{})??{};return Oa({...r,palette:{...r.palette,colors:T(t)===`v5`?ce(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},Ya=e=>{let t=Ka(e),n=Ua(e?.theme),r=sa(e)===`circle`?ca:{...ya.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}},i=ce({components:{launcher:r}},n),a=Ua(e?.darkTheme);return Fa(t===`dark`?Ja(ce(i??{},a??{}),{future:e?.future}):qa(i,{future:e?.future}),e)},Xa=e=>Na(e),Za=(e,t)=>{let n=Ya(t),r=Xa(n);for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute(`data-persona-color-scheme`,Ka(t)),e.setAttribute(`data-persona-defaults`,T(t))},Qa=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(Wa())});n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),t.push(()=>n.disconnect())}if(typeof window<`u`&&window.matchMedia){let n=window.matchMedia(`(prefers-color-scheme: dark)`),r=()=>e(Wa());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},$a=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),eo=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,to=e=>{if(typeof e!=`string`)return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},no=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight),ro=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;un.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&!t.hasAttribute(`data-preserve-animation`)||t instanceof HTMLElement&&t.hasAttribute(`data-preserve-animation`)&&(e.textContent??``)!==(t.textContent??``)?void 0:!1}}}})},io=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),ao={index:-1,draft:``};function oo(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function so(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??``,e.streaming?`1`:`0`,e.voiceProcessing?`1`:`0`,e.variant??``,e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??``,e.toolCall?.status??``,e.toolCall?.name??``,e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??``,typeof e.toolCall?.args==`string`?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??``,e.contentParts?.length??0,e.stopReason??``,t].join(`\0`)}function co(){return/* @__PURE__ */ new Map}function lo(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function uo(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function fo(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}const{setLoader:po,load:mo}=Ne({fallbackImport:()=>import(`./chunk-Dg7uqL8l.js`)}),ho=mo;function go(e,t=St){let n=e.style.position,r=e.style.zIndex,i=e.style.isolation,a=getComputedStyle(e),o=a.position===`static`||a.position===``;return o&&(e.style.position=`relative`),e.style.zIndex=String(t),e.style.isolation=`isolate`,()=>{o&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=i}}let _o=0,vo=null;function yo(e=document){if(_o++,_o===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;vo={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:n},t.style.overflow=`hidden`,t.style.position=`fixed`,t.style.top=`-${n}px`,t.style.width=`100%`}let t=!1;return()=>{if(!t&&(t=!0,_o=Math.max(0,_o-1),_o===0&&vo)){let t=e.body,n=e.defaultView??window;t.style.overflow=vo.originalOverflow,t.style.position=vo.originalPosition,t.style.top=vo.originalTop,t.style.width=vo.originalWidth,n.scrollTo(0,vo.scrollY),vo=null}}}const bo={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},xo=e=>(e?.launcher?.mountMode??`floating`)===`docked`,So=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,Co=e=>{let t=e?.launcher?.dock,n=D(e).dockWidth?t?.width:Ca(Ya(e),`components.panel.width`);return{side:t?.side??bo.side,width:n??bo.width,animate:t?.animate??bo.animate,reveal:t?.reveal??bo.reveal,maxHeight:t?.maxHeight??bo.maxHeight}},wo=e=>e===`followUp`?`follow-up`:e,To=(e,t=0)=>{if(typeof e==`string`){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:`default`}:null}let n=e.label.trim();if(!n)return null;let r=e.prompt?.trim()||n;return{id:e.id?.trim()||r||`suggestion-${t}`,label:n,prompt:r,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??`default`}},Eo=/* @__PURE__ */ new WeakSet,Do=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Oo=e=>{Do()||e.forEach((e,t)=>{typeof e.animate==`function`&&e.animate([{opacity:`0`,transform:`translateY(4px)`},{opacity:`1`,transform:`none`}],{duration:250,delay:t*60,easing:`ease-out`,fill:`backwards`})})},ko=e=>{let{item:t,index:n,surface:r,source:i,variant:a,streaming:o,config:s,plugins:c,chipsConfig:l,session:u,getTextarea:d,eventTarget:f,submitPrompt:p}=e,m=r===`followUp`,h=t.behavior,g=()=>{if(u.isStreaming())return;let e={suggestion:{...t},surface:r,source:i,behavior:h},n=f.dispatchEvent(new CustomEvent(`persona:suggestion:selected`,{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(m&&f.dispatchEvent(new CustomEvent(`persona:suggestReplies:selected`,{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!n)return;for(let e of c)if(e.onSuggestionSelect?.({suggestion:{...t},surface:r,source:i,variant:a,config:s})===!1)return;let o=d();h===`fill`?(o.value=t.prompt,o.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),o.focus()):p?p(t.prompt):(o.value=``,u.sendMessage(t.prompt))},_=()=>{let e=M(`button`,`persona-suggestion persona-suggestion--${a}`);if(e.type=`button`,e.disabled=o,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=h,a===`chip`&&(l?.fontWeight&&(e.style.fontWeight=l.fontWeight),l?.paddingX&&(e.style.paddingLeft=l.paddingX,e.style.paddingRight=l.paddingX),l?.paddingY&&(e.style.paddingTop=l.paddingY,e.style.paddingBottom=l.paddingY)),t.icon){let n=N(t.icon,`var(--persona-suggestion-icon-size)`,`currentColor`,1.8);n&&(n.classList.add(`persona-suggestion__icon`),t.iconColor&&(n.style.color=t.iconColor),e.appendChild(n))}let n=M(`span`,`persona-suggestion__copy`);if(n.appendChild(j(`span`,{className:`persona-suggestion__label`,text:t.label})),t.description&&a!==`chip`&&n.appendChild(j(`span`,{className:`persona-suggestion__description`,text:t.description})),e.appendChild(n),a!==`chip`){let t=b(Xt,16,`currentColor`,1.8);t&&(t.classList.add(`persona-suggestion__arrow`),e.appendChild(t))}return e.addEventListener(`click`,g),e},v=null;for(let e of c)if(e.renderSuggestion&&(v=e.renderSuggestion({suggestion:{...t},index:n,surface:r,source:i,variant:a,streaming:o,config:s,defaultRenderer:_,select:g}),v))break;return v??=_(),v.dataset.suggestionId||=t.id,v.dataset.behavior||=h,v.dataset.emphasis||=t.emphasis,v instanceof HTMLButtonElement||v.setAttribute(`aria-disabled`,o?`true`:`false`),v},Ao=e=>{let t=[],n=[],r=null,i=null,a=()=>{e.removeAttribute(`data-scroll-left`),e.removeAttribute(`data-scroll-right`)},o=()=>{if(i=null,e.hidden||e.dataset.variant!==`chip`||e.dataset.overflow!==`scroll`){a();return}let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1){a();return}let n=getComputedStyle(e).direction===`rtl`,r=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),o=r<=4,s=r>=t-4,c=n?!s:!o,l=n?!o:!s;e.toggleAttribute(`data-scroll-left`,c),e.toggleAttribute(`data-scroll-right`,l)},s=()=>{i!==null||typeof requestAnimationFrame!=`function`?typeof requestAnimationFrame!=`function`&&o():i=requestAnimationFrame(o)};e.addEventListener(`scroll`,s,{passive:!0});let c=typeof ResizeObserver==`function`?new ResizeObserver(s):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener(`scroll`,s),c?.disconnect(),i!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),i=null},render:(i,c,l,u,d,f)=>{e.replaceChildren(),t.length=0,n.length=0;let p=f?.source??`config`,m=f?.surface??(p===`config`?`starter`:`followUp`),h=m===`followUp`,g=f?.variant??`chip`,_=f?.behavior??`send`,v=f?.overflow??`wrap`,y=f?.config??{},b=f?.plugins??[],x=typeof f?.maxItems==`number`?Math.max(0,Math.floor(f.maxItems)):void 0,S=h?`followUps`:`starters`;!Eo.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(Eo.add(y),console.info(`[persona] suggestions.${S}.overflow applies to the "chip" variant only; the "${g}" variant manages its own stacking.`));let C=e=>e.map(To).filter(e=>e!==null).map(e=>({...e,behavior:e.behavior??_})),w=C(i??[]);b.forEach(e=>{e.transformSuggestions&&(w=C(e.transformSuggestions({suggestions:w.map(e=>({...e})),surface:m,source:p,config:y})))});let T=x===void 0?w:w.slice(0,x);if(!T.length){e.hidden=!0,r=null,a();return}if(!h&&(u??c.getMessages()).some(e=>e.role===`user`)){e.hidden=!0,r=null;return}e.hidden=!1,e.classList.add(`persona-suggestions`),e.dataset.personaSuggestionSurface=wo(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=ko({item:r,index:i,surface:m,source:p,variant:g,streaming:D,config:y,plugins:b,chipsConfig:d,session:c,getTextarea:()=>l,eventTarget:e,submitPrompt:f?.submitPrompt});E.appendChild(a),n.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll(`button`))].forEach(e=>{t.includes(e)||(e.disabled=D,t.push(e))})}),e.appendChild(E),o(),s();let ee=JSON.stringify({normalized:T,surface:m,variant:g,source:p});ee!==r&&(r=ee,Oo(n),e.dispatchEvent(new CustomEvent(`persona:suggestion:shown`,{detail:{suggestions:T.map(e=>({...e})),surface:m,source:p,variant:g},bubbles:!0,composed:!0})),h&&e.dispatchEvent(new CustomEvent(`persona:suggestReplies:shown`,{detail:{suggestions:T.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},jo={"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`},Mo={x:[1.4,1.05]},Z=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,No=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=Mo[t]??[1,1.5],s=!r;e.classList.toggle(`persona-header-control--glyph`,s),e.classList.toggle(`persona-header-control--sparse`,s&&a!==1);let c=N(t,`${Math.round((parseFloat(r??``)||20)*a)}px`,`currentColor`,o);c?(c.style.display=`block`,s||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((o/1.5).toFixed(4))})`),e.replaceChildren(c)):i&&(e.textContent=i)},Po=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:r,iconName:i,iconText:a,wrapperClassName:o=Z,size:s,iconSize:c,color:l,backgroundColor:u,borderWidth:d,borderColor:f,borderRadius:p,paddingX:m,paddingY:h,hidden:g,extraClassName:_,attrs:v}=e,y=M(`div`,o),b=!!(d||f),x=j(`button`,{className:Me(`persona-header-control`,`persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer`,!u&&`persona-bg-transparent hover:persona-bg-gray-100`,!b&&`persona-border-none`,!p&&`persona-rounded-full`,_),attrs:{type:`button`,"aria-label":t,...v},style:{width:s,height:s,minWidth:s,minHeight:s,display:g?`none`:void 0,color:l||Lo.actionIconColor,backgroundColor:u,border:b?`${d||`0px`} solid ${f||`transparent`}`:void 0,borderRadius:p,paddingLeft:m,paddingRight:m,paddingTop:h,paddingBottom:h}});return i?No(x,i,{iconSize:c,iconText:a}):a&&(x.textContent=a),y.appendChild(x),S({anchor:x,trigger:y,text:()=>x.getAttribute(`aria-label`)??t,hint:r,enabled:n}),{button:x,wrapper:y}},Fo=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=Z,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=Po({ariaLabel:s,tooltip:c,iconName:o.closeButtonIconName??`x`,iconText:o.closeButtonIconText??`×`,wrapperClassName:r,size:i??o.closeButtonSize,iconSize:a,color:o.closeButtonColor,backgroundColor:o.closeButtonBackgroundColor,borderWidth:o.closeButtonBorderWidth,borderColor:o.closeButtonBorderColor,borderRadius:o.closeButtonBorderRadius,paddingX:o.closeButtonPaddingX,paddingY:o.closeButtonPaddingY,hidden:!n});return{button:l,wrapper:u}},Io=(e,t={})=>{let{wrapperClassName:n=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,buttonSize:r,iconSize:i}=t,a=(e?.launcher??{}).clearChat??{},o=a.tooltipText??`Clear chat`,s=a.showTooltip??!0,{button:c,wrapper:l}=Po({ariaLabel:o,tooltip:s,iconName:a.iconName??`refresh-cw`,wrapperClassName:n,size:r??a.size,iconSize:i,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:c,wrapper:l}},Lo={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)`},Ro={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)`},zo={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)`},Bo=e=>{let{config:t,showClose:n=!0}=e,r=j(`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:Lo.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)))`}}),i=t?.launcher??{},a=i.headerIconSize??`40px`,o=i.closeButtonPlacement??`inline`,s=i.headerIconHidden??!1,c=i.headerIconName,l=j(`div`,{className:`persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl`,style:{height:a,width:a,backgroundColor:`var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))`,color:`var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))`}});if(!s){if(c){let e=parseFloat(a)||24,n=N(c,e*.6,`currentColor`,1);n?(n.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,n.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,l.replaceChildren(n)):l.textContent=t?.launcher?.agentIconText??`💬`}else if(t?.launcher?.iconUrl){let e=M(`img`);e.src=t.launcher.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=a,e.style.width=a,l.replaceChildren(e)}else l.textContent=t?.launcher?.agentIconText??`💬`}let u=M(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=j(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:Lo.titleColor,...Ro}}),f=j(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:Lo.subtitleColor,...zo}});u.append(d,f),s?r.append(u):r.append(l,u);let p=i.clearChat??{},m=p.enabled??!0,h=p.placement??`inline`,g=null,_=null;if(m){let e=Io(t,{wrapperClassName:h===`top-right`?`persona-absolute persona-top-4 persona-z-50`:`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`});g=e.button,_=e.wrapper,h===`top-right`&&(_.style.right=`48px`),h===`inline`&&r.appendChild(_)}let{button:v,wrapper:y}=Fo(t,{showClose:n,wrapperClassName:o===`top-right`?`persona-absolute persona-top-4 persona-right-4 persona-z-50`:m&&h===`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`});return o!==`top-right`&&r.appendChild(y),{header:r,iconHolder:l,headerTitle:d,headerSubtitle:f,closeButton:v,closeButtonWrapper:y,clearChatButton:g,clearChatButtonWrapper:_}},Vo=(e,t,n)=>{let r=n?.launcher??{},i=r.closeButtonPlacement??`inline`,a=r.clearChat?.placement??`inline`;e.appendChild(t.header),i===`top-right`&&(e.style.position=`relative`,e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a===`top-right`&&(e.style.position=`relative`,e.appendChild(t.clearChatButtonWrapper))},Ho=e=>{let t=Bo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let e=t.headerTitle.parentElement;e&&(e.style.cursor=`pointer`,e.setAttribute(`role`,`button`),e.setAttribute(`tabindex`,`0`),e.addEventListener(`click`,()=>n()),e.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())}))}return t};function Uo(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=Po({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?_t(r.shortcut):void 0,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`});if(t.setAttribute(`data-persona-header-action`,r.id),r.shortcut){let e=yt(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=Ie({items:r.menuItems,onSelect:e=>n?.(e),anchor:i,position:`bottom-right`});i.appendChild(e.element),t.addEventListener(`click`,t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener(`click`,()=>n?.(r.id));e.appendChild(i)}}const Wo={default:Ho,minimal:e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=M(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=Lo.minHeight,s.style.padding=`var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))`,s.style.backgroundColor=`var(--persona-header-bg, var(--persona-surface, #ffffff))`,s.style.borderBottomColor=`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,s.style.boxShadow=`var(--persona-header-shadow, none)`,s.style.borderBottom=`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`;let c=i?.titleMenu,l,u;if(c){let e=We({label:o.title??`Chat Assistant`,menuItems:c.menuItems,onSelect:t=>{let n=n=>{n===!1&&e.element.dispatchEvent(new CustomEvent(`persona:title-menu-builtin`,{bubbles:!0,composed:!0,detail:{actionId:t}}))},r=c.onSelect(t);r instanceof Promise?r.then(n,()=>{}):n(r)},hover:c.hover,className:``});l=e.element,l.style.color=Lo.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=M(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=M(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=Lo.titleColor,Object.assign(u.style,Ro),u.textContent=o.title??`Chat Assistant`,l.appendChild(u),i?.onTitleClick){l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`);let e=i.onTitleClick;l.addEventListener(`click`,t=>{t.target.closest(`button`)||e()}),l.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())})}let e=i?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??`10px`,l.style.padding=e.padding??`6px 4px 6px 12px`,l.style.margin=`-6px 0 -6px -12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.style.width=`fit-content`,l.style.flex=`none`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=e.background??``,l.style.borderColor=e.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}))}s.appendChild(l);let d=`persona-relative persona-inline-flex persona-items-center persona-justify-center`,{button:f,wrapper:p}=Fo(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=M(`div`,`persona-flex persona-items-center persona-gap-1`);c||Uo(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=Io(t,{wrapperClassName:e===`top-right`?`persona-absolute persona-top-4 persona-z-50`:d});g=n.button,_=n.wrapper,e===`top-right`?_.style.right=`48px`:m.appendChild(_)}m.appendChild(p),s.appendChild(m);let v=M(`div`);v.style.display=`none`;let y=M(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}}},Go=e=>Wo[e]??Wo.default,Ko=(e,t,n)=>{if(t?.render){let r=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=M(`div`);i.style.display=`none`;let a=M(`span`),o=M(`span`),s=M(`button`);s.style.display=`none`;let c=M(`div`);return c.style.display=`none`,{header:r,iconHolder:i,headerTitle:a,headerSubtitle:o,closeButton:s,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??`default`,i=Go(r)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(i.iconHolder.style.display=`none`),t.showTitle===!1&&(i.headerTitle.style.display=`none`),t.showSubtitle===!1&&(i.headerSubtitle.style.display=`none`),t.showCloseButton===!1&&(i.closeButton.style.display=`none`),t.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display=`none`)),i},qo=e=>{let{config:t}=e,n=j(`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`}}),r=Se(),i=j(`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:a,attachAutoResize:o}=ye(t);o();let s=k(t),c=Ee(t),l=fe(t),u=pe(t),d=j(`div`,{className:`persona-widget-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});i.append(d),l&&(l.previewsContainer.style.gap=`8px`,d.append(l.previewsContainer),i.append(l.input)),i.append(a);let f=j(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=j(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=j(`div`,{className:`persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-end":``}});return l&&p.append(l.wrapper),c&&m.append(c.wrapper),m.append(s.wrapper),f.append(p,m),i.append(f),i.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),t?.statusIndicator?.mode===`transient`?n.append(r,u,i):n.append(r,i,u),{footer:n,suggestions:r,composerForm:i,header:d,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:s.setMode}},Jo=()=>{let e=j(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),t=M(`span`,`persona-pill-peek__icon`),n=b(cn,16,`currentColor`,1.5);n&&t.appendChild(n);let r=M(`span`,`persona-pill-peek__text`),i=M(`span`,`persona-pill-peek__caret`),a=b($t,16,`currentColor`,1.5);return a&&i.appendChild(a),e.append(t,r,i),{root:e,textNode:r}},Yo=e=>{let{config:t}=e,n=j(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=Se(),i=pe(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=ye(t,{defaultMaxLines:5});o();let s=k(t),c=Ee(t),l=fe(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=j(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=j(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=j(`div`,{className:`persona-widget-composer__right-actions persona-pill-composer__right`,attrs:{"data-persona-composer-actions-end":``}});c&&f.append(c.wrapper),f.append(s.wrapper),u.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),l&&u.append(l.input),u.append(d,a,f);let p=j(`div`,{className:`persona-pill-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});n.append(p),l&&p.append(l.previewsContainer),n.append(r,u,i);let m=u;return{footer:n,suggestions:r,composerForm:u,header:p,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:i,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:m,leftActions:d,rightActions:f,setSendButtonMode:s.setMode}},Xo=e=>{switch(e){case`max_tool_calls`:return`Stopped after calling a tool. Send a follow-up to continue.`;case`length`:return`Response cut off as max tokens reached. Ask for more to continue.`;case`content_filter`:return`The provider filtered this response.`;case`error`:return`Something went wrong generating this response.`;default:return null}},Zo=(e,t)=>{if(!e)return null;let n=Xo(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},Qo=(e,t)=>{let n=M(`div`,`persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic`);return n.setAttribute(`data-stop-reason`,e),n.setAttribute(`role`,`note`),n.style.opacity=`0.75`,n.textContent=t,n},Q=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},$o=e=>{let t=e.toLowerCase();return t.startsWith(`javascript:`)||t.startsWith(`data:text/html`)||t.startsWith(`data:text/javascript`)||t.startsWith(`data:text/xml`)||t.startsWith(`data:application/xhtml`)||t.startsWith(`data:image/svg+xml`)?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:`)||!e.includes(`:`))},es=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),ts=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),ns=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),rs=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),is=e=>{if(!e||e.length===0)return null;let t=j(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=j(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=M(`span`,`persona-mention-chip-icon`),i=N(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(j(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},as=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(Te(r.ref,{readonly:!0,render:t}));return n},os=(e,t,n,r)=>{let i=Math.random().toString(36).slice(2,8),a=e=>`${i}:${e}`,o=n(t.map((e,t)=>e.kind===`text`?e.text:a(t)).join(``));if(!t.every((e,t)=>e.kind===`text`||o.includes(a(t)))){e.replaceChildren(as(t,r));return}e.innerHTML=o;let s=RegExp(`${i}:(\\d+)`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=[];for(let e=c.nextNode();e;e=c.nextNode())l.push(e);for(let e of l){let n=e;for(let e=s.exec(n.data);e;e=s.exec(n.data)){let i=t[Number(e[1])],a=n.splitText(e.index);a.data=a.data.slice(e[0].length),i?.kind===`mention`&&a.parentNode?.insertBefore(Te(i.ref,{readonly:!0,render:r}),a),n=a}}},ss=(e,t,n)=>{if(e.length===0)return null;try{let r=M(`div`,`persona-flex persona-flex-col persona-gap-2`);r.setAttribute(`data-message-attachments`,`images`),t&&(r.style.marginBottom=`8px`);let i=0,a=!1,o=()=>{a||(a=!0,r.remove(),n?.())};return e.forEach((e,t)=>{let n=M(`img`);n.alt=e.alt?.trim()||`Attached image ${t+1}`,n.loading=`lazy`,n.decoding=`async`,n.referrerPolicy=`no-referrer`,n.style.display=`block`,n.style.width=`100%`,n.style.maxWidth=`320px`,n.style.maxHeight=`320px`,n.style.height=`auto`,n.style.objectFit=`contain`,n.style.borderRadius=`10px`,n.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,n.style.border=`1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))`;let a=!1;i+=1,n.addEventListener(`error`,()=>{a||(a=!0,i=Math.max(0,i-1),n.remove(),i===0&&o())}),n.addEventListener(`load`,()=>{a=!0}),Q(e.image)?(n.src=e.image,r.appendChild(n)):(a=!0,i=Math.max(0,i-1),n.remove())}),i===0?(o(),null):r}catch{return n?.(),null}},cs=e=>{if(e.length===0)return null;try{let t=M(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!$o(e.audio))return;let r=M(`audio`);r.controls=!0,r.preload=`metadata`,r.src=e.audio,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ls=e=>{if(e.length===0)return null;try{let t=M(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!$o(e.video))return;let r=M(`video`);r.controls=!0,r.preload=`metadata`,r.src=e.video,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,r.style.maxHeight=`320px`,r.style.borderRadius=`10px`,r.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},us=e=>{if(e.length===0)return null;try{let t=M(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!$o(e.data))return;let r=M(`a`);r.href=e.data,r.download=e.filename,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=e.filename,r.className=`persona-message-file-attachment`,r.style.display=`inline-flex`,r.style.alignItems=`center`,r.style.gap=`6px`,r.style.padding=`6px 10px`,r.style.borderRadius=`8px`,r.style.fontSize=`0.875rem`,r.style.textDecoration=`underline`,r.style.backgroundColor=`var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))`,r.style.border=`1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))`,r.style.color=`inherit`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ds=()=>{let e=document.createElement(`div`);e.className=`persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2`;let t=document.createElement(`div`);t.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,t.style.backgroundColor=`currentColor`,t.style.opacity=`0.4`,t.style.animationDelay=`0ms`;let 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 r=document.createElement(`div`);r.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,r.style.backgroundColor=`currentColor`,r.style.opacity=`0.4`,r.style.animationDelay=`500ms`;let i=document.createElement(`span`);return i.className=`persona-sr-only`,i.textContent=`Loading`,e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e},fs=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:ds};if(t){let e=t(r);if(e!==null)return e}return ds()},ps=(e,t)=>{let n=M(`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`),r=t===`user`?e.userAvatar:e.assistantAvatar;if(r){if(r.startsWith(`http`)||r.startsWith(`/`)||r.startsWith(`data:`)){let e=M(`img`);e.src=r,e.alt=t===`user`?`User`:`Assistant`,e.className=`persona-w-full persona-h-full persona-rounded-full persona-object-cover`,n.appendChild(e)}else n.textContent=r,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`)}else n.textContent=t===`user`?`U`:`A`,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`);return n},ms=(e,t,n=`div`)=>{let r=M(n,`persona-text-xs persona-text-persona-muted`),i=new Date(e.createdAt);return r.textContent=t.format?t.format(i):i.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),r},hs=(e,t=`bubble`)=>{let n=[`persona-message-bubble`];switch(t){case`flat`:e===`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`),e===`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`),e===`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`)}return n},gs={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=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=gs[n??`bubble`]??gs.bubble;r.padding&&(e.style.padding=`var(--persona-message-${i}-padding, ${a.padding})`),r.fontSize&&(e.style.fontSize=`var(--persona-message-${i}-font-size, ${a.fontSize})`),r.lineHeight&&(e.style.lineHeight=`var(--persona-message-${i}-line-height, ${a.lineHeight})`),r.fontFamily&&(e.style.fontFamily=`var(--persona-message-${i}-font-family, inherit)`)},vs=e=>`custom:${e}`,ys=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),bs=(e,t,n,r)=>{let i=t.showCopy??!0,a=t.showUpvote??!1,o=t.showDownvote??!1,s=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&r?.canRegenerate===!0,l=(t.showEdit??!1)&&r?.canEdit===!0,u=(t.showQuote??!1)&&r?.canQuote!==!1,d=ys(t,e.role);if(!i&&!a&&!o&&!s&&!c&&!l&&!u&&d.length===0){let t=M(`div`);return t.style.display=`none`,t.id=`actions-${e.id}`,t.setAttribute(`data-actions-for`,e.id),t}let f=t.visibility??`hover`,p=t.align??`right`,m=t.layout??`pill-inside`,h={left:`persona-message-actions-left`,center:`persona-message-actions-center`,right:`persona-message-actions-right`}[p],g={"pill-inside":`persona-message-actions-pill`,"row-inside":`persona-message-actions-row`}[m],_=M(`div`,`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${h} ${g} ${f===`hover`?`persona-message-actions-hover`:``}`);_.id=`actions-${e.id}`,_.setAttribute(`data-actions-for`,e.id);let v=(e,t,n)=>{let r=ze({icon:e,label:t,size:14,className:`persona-message-action-btn`,chromeless:!0});return r.setAttribute(`data-action`,n),r};i&&_.appendChild(v(`copy`,`Copy message`,`copy`)),s&&_.appendChild(v(`volume-2`,`Read aloud`,`read-aloud`)),a&&_.appendChild(v(`thumbs-up`,`Upvote`,`upvote`)),o&&_.appendChild(v(`thumbs-down`,`Downvote`,`downvote`)),c&&_.appendChild(v(`refresh-cw`,`Regenerate response`,`regenerate`)),l&&_.appendChild(v(`pencil`,`Edit message`,`edit`)),u&&_.appendChild(v(`quote`,`Quote message`,`quote`));for(let e of d)_.appendChild(v(e.iconName??`ellipsis`,e.label,vs(e.id)));return _},xs=(e,t,n,r,i,a)=>{let o=n??{},s=o.layout??`bubble`,c=o.avatar,l=o.timestamp,u=c?.show??!1,d=l?.show??!1,f=c?.position??`left`,p=l?.position??`below`,m=hs(e.role,s),h=M(`div`,m.join(` `));h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.setAttribute(`data-persona-theme-zone`,e.role===`user`?`user-message`:`assistant-message`);let g=Sa(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;_s(h,e.role,s,e.role===`user`?{...g.user,..._?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...g.assistant,..._?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),s===`flat`?(h.style.backgroundColor=`transparent`,h.style.color=e.role===`user`?`var(--persona-primary, var(--persona-text))`:`var(--persona-message-assistant-text, var(--persona-text))`):e.role===`user`?(h.style.backgroundColor=`var(--persona-message-user-bg, var(--persona-accent))`,h.style.color=`var(--persona-message-user-text, white)`):e.role===`assistant`&&(h.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,h.style.color=`var(--persona-message-assistant-text, var(--persona-text))`);let v=es(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=Bt(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?Ht(x.type,S):null,w=e.role===`assistant`&&C?.isAnimating?.(e)===!0,T=e.role===`assistant`&&C!==null&&(!!e.streaming||w);T&&C?.bubbleClass&&h.classList.add(C.bubbleClass);let E=document.createElement(`div`);E.classList.add(`persona-message-content`),e.streaming&&E.classList.add(`persona-content-streaming`),T&&C&&(C.containerClass&&E.classList.add(C.containerClass),E.style.setProperty(`--persona-stream-step`,`${x.speed}ms`),E.style.setProperty(`--persona-stream-duration`,`${x.duration}ms`));let D=T?Ut(e.content??``,x.buffer,C,e,!!e.streaming):e.content??``,ee=()=>{let n=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent});return T&&C?.wrap===`char`?Jt(n,`char`,e.id,{skipTags:C.skipTags}):T&&C?.wrap===`word`?Jt(n,`word`,e.id,{skipTags:C.skipTags}):n},te=null;if(b?(te=document.createElement(`div`),te.innerHTML=ee(),te.style.display=`none`,E.appendChild(te)):e.contentSegments?.length?os(E,e.contentSegments,n=>t({text:n,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=ee(),T&&C?.useCaret&&!b&&y){let e=Vt(),t=E.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];if(n?.parentNode)n.parentNode.insertBefore(e,n.nextSibling);else{let t=E.lastElementChild;t?t.appendChild(e):E.appendChild(e)}}if(d&&p===`inline`&&e.createdAt){let t=ms(e,l,`span`);t.classList.add(`persona-timestamp-inline`);let n=E.lastElementChild;n?n.appendChild(t):E.appendChild(t)}if(v.length>0){let e=ss(v,!b&&!!y,()=>{b&&te&&(te.style.display=``)});e?h.appendChild(e):b&&te&&(te.style.display=``)}let ne=ts(e);if(ne.length>0){let e=cs(ne);e&&h.appendChild(e)}let re=ns(e);if(re.length>0){let e=ls(re);e&&h.appendChild(e)}let ie=rs(e);if(ie.length>0){let e=us(ie);e&&h.appendChild(e)}let ae=e.contentSegments?.length?null:is(e.contextMentions);if(ae&&h.appendChild(ae),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=ms(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let oe=e.role===`assistant`?Zo(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role===`assistant`){let e=!!(D&&D.trim()),t=x.placeholder===`skeleton`,n=t&&x.buffer===`line`&&e;if(e)n&&h.appendChild(Gt());else if(t)h.appendChild(Gt());else{let e=fs(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}oe&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild(Qo(e.stopReason,oe)));let se=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,O=a?.actionEligibility,ce=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&O?.canEdit===!0||r?.showQuote===!0&&O?.canQuote===!0||ys(r,`user`).length>0);if((se||ce)&&r){let t=bs(e,ce?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,O);h.appendChild(t)}if(!u||e.role===`system`)return h;let le=M(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),ue=ps(c,e.role);return f===`right`||f===`left`&&e.role===`user`?le.append(h,ue):le.append(ue,h),le},Ss=(e,t)=>{if(e.replaceChildren(),!t)e.hidden=!0;else if(typeof t==`function`){let n=null;try{n=t()}catch(e){console.warn(`[persona] welcome.icon renderer threw`,e)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1}else{if(t.type===`lucide`){let n=N(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(j(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(j(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},Cs=(e,t,n={})=>{let r=j(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=M(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=M(`h2`,`persona-welcome-title`),o=M(`p`,`persona-welcome-subtitle`),s=j(`div`,{className:`persona-welcome-head-text`},i,a),c=j(`div`,{className:`persona-welcome-title-row`},r,s);return{host:j(`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)`}},c,o,t),iconHolder:r,kicker:i,title:a,subtitle:o,starterSuggestions:t}},ws=(e,t,n)=>{t.hidden=!n,t.style.display=n?``:`none`,e.classList.toggle(`persona-gap-6`,n),e.classList.toggle(`persona-gap-3`,!n)},Ts=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??``,e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle===``,Ss(e.iconHolder,t.icon),e.host.setAttribute(`data-persona-welcome-variant`,t.variant),e.host.setAttribute(`data-persona-welcome-dismiss`,t.dismiss),e.host.setAttribute(`data-persona-welcome-layout`,t.layout??`top`),e.host.setAttribute(`data-persona-welcome-anchor`,t.anchor??`bottom`),t.iconPlacement===`inline`?e.host.setAttribute(`data-persona-welcome-icon-placement`,`inline`):e.host.removeAttribute(`data-persona-welcome-icon-placement`),t.align?e.host.setAttribute(`data-persona-welcome-align`,t.align):e.host.removeAttribute(`data-persona-welcome-align`)},Es=`data-persona-welcome-overlay`,Ds=`persona-welcome-overlay-active`,Os=/* @__PURE__ */ new WeakMap,ks=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(Es,``),e.classList.contains(Ds)||(Os.set(e,e.scrollTop),e.classList.add(Ds),e.scrollTop=0)},As=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(Es),e.classList.contains(Ds)&&(e.classList.remove(Ds),e.scrollTop=Os.get(e)??e.scrollTop,Os.delete(e))},js=()=>{let e=j(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},Ms=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=j(`div`,{className:hs(`assistant`,r).join(` `),attrs:{"data-persona-theme-zone":`assistant-message`},text:t,style:r===`flat`?{backgroundColor:`transparent`,color:`var(--persona-message-assistant-text, var(--persona-text))`}:{backgroundColor:`var(--persona-message-assistant-bg, var(--persona-container))`,color:`var(--persona-message-assistant-text, var(--persona-text))`}});e.appendChild(j(`div`,{className:`persona-flex`},i)),e.hidden=!1},Ns=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Ps=(e,t)=>{if(Ns()||typeof e.animate!=`function`||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),r=e.parentElement,i=0,a=0,o=0;if(r){let t=getComputedStyle(r);i=parseFloat(t.rowGap)||0;let s=e.previousElementSibling,c=e.nextElementSibling,l=r.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-r.scrollTop;a=Math.max(0,s?n.top-s.getBoundingClientRect().bottom-i:n.top-l),o=Math.max(0,c?c.getBoundingClientRect().top-n.bottom-i:0)}let s=e.style.overflow;e.style.overflow=`hidden`;let c=getComputedStyle(e),l=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,d=e.animate([{opacity:`1`,transform:`none`,height:`${n.height}px`,minHeight:`0px`,paddingTop:`${l}px`,paddingBottom:`${u}px`,marginTop:`${a}px`,marginBottom:`${o}px`},{opacity:`0`,transform:`translateY(-4px)`,height:`0px`,minHeight:`0px`,paddingTop:`0px`,paddingBottom:`0px`,marginTop:`0px`,marginBottom:`${-i}px`}],{duration:180,easing:`ease-out`,fill:`forwards`}),f=!1,p=()=>{f||(f=!0,e.style.overflow=s,t(d))};return d.finished.then(p).catch(p),d},Fs=(e,t,n,r=260)=>{if(t<=1||Ns()||typeof e.animate!=`function`||!e.isConnected)return null;let i=n===`drop`?-t:t;return e.animate([{transform:`translateY(${i}px)`},{transform:`none`}],{duration:r,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`none`})},Is=/* @__PURE__ */ new WeakSet,Ls=(e,t)=>!!e&&e[t]!==void 0,Rs=(e,t)=>{e&&e.debug===!0&&t.length&&(Is.has(e)||(Is.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},zs=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!==`docked`)=>{let n=e?.welcome,r=e?.copy,i=e?.future?.v5Defaults===!0,a=n?.layout??(i?`centered`:`top`),o=Ls(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:Ls(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];Ls(n,`title`)&&Ls(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),Ls(n,`subtitle`)&&Ls(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),Ls(n,`variant`)&&Ls(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&Ls(n,`message`)&&c.push(`welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.`),!i&&n?.layout===void 0&&o===`hero`&&Ls(n,`dismiss`)&&n.dismiss!==`on-first-message`&&c.push(`welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".`);let l=n?.anchor??(a===`centered`&&t?`center`:`bottom`),u=to(n?.anchorComposerTop)!==null;return Ls(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(Ls(n,`anchorComposerTop`)||Ls(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),Rs(e,c),{title:Ls(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:Ls(n,`subtitle`)?n.subtitle:r?.welcomeSubtitle??(i?``:`I can answer questions and help you get things done here.`),icon:n?.icon,align:n?.align===`start`||n?.align===`center`?n.align:a===`centered`?`center`:void 0,iconPlacement:n?.icon&&typeof n.icon!=`function`&&n.icon.placement===`inline`?`inline`:`above`,variant:o,dismiss:s,message:o===`hero`?void 0:n?.message,layout:a,anchor:l,anchorComposerTop:u?n.anchorComposerTop:`44%`,composerGap:n?.composerGap?.trim()||`24px`}},Bs=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,Vs=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`),Hs=`var(--persona-components-panel-height)`,Us=e=>{let t=D(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,r=e?.launcher?.heightOffset??0,i=r===0?`max(200px, ${Hs})`:`max(200px, calc(${Hs} - ${r}px))`;return{width:n??`var(--persona-components-panel-width)`,maxWidth:n??`var(--persona-components-panel-maxWidth)`,height:i,maxHeight:`var(--persona-components-panel-maxHeight)`}},Ws=`16px`,Gs=`10px`,Ks=`14px`,qs=e=>{let t=e?.launcher?.enabled??!0,n=xo(e);if(So(e)){let t=e?.launcher?.composerBar??{},n=M(`div`,`persona-widget-wrapper persona-fixed persona-transition`);n.setAttribute(`data-persona-composer-bar`,``),n.dataset.state=`collapsed`,n.dataset.expandedSize=t.expandedSize??`anchored`,n.style.zIndex=String(e?.launcher?.zIndex??1e5);let r=M(`div`,`persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);r.style.width=`100%`,n.appendChild(r);let i=M(`div`,`persona-widget-pill-root`);return i.setAttribute(`data-persona-composer-bar`,``),i.dataset.state=`collapsed`,i.dataset.expandedSize=t.expandedSize??`anchored`,i.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:n,panel:r,pillRoot:i}}if(n){let e=M(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=M(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=M(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=M(`div`,`persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0`),r=D(e),i=r.launcherWidth||r.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Us(e).width:`100%`;return t.style.width=i,n.style.width=`100%`,t.appendChild(n),{wrapper:t,panel:n}}let r=e?.launcher??{},i=r.position&&jo[r.position]?jo[r.position]:jo[`bottom-right`],a=M(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=M(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),s=Us(e);return o.style.width=s.width,o.style.maxWidth=s.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},Js=e=>{let t=j(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":wo(e)}});return t.hidden=!0,t},Ys=(e,t)=>{let n=Js(`starter`),r=Cs(e,n,{flatShadow:xo(e)}),i=zs(e);Ts(r,i),ws(t,r.host,Vs(i,e?.initialMessages));let a=js();return Ms(a,i.message,e),{welcome:r,greetingHost:a}},Xs=(e,t)=>{let n=M(`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:r,wrapper:i}=Fo(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:Ws,iconSize:Gs});i.style.position=`absolute`,i.style.top=`8px`,i.style.right=`8px`,i.style.zIndex=`10`;let a=e?.launcher?.clearChat?.enabled??!0,o=null,s=null;if(a){let t=Io(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:Ws,iconSize:Ks});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=j(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=j(`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`}});l.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:u,greetingHost:d}=Ys(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=M(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=Js(`followUp`),v=$a(e,!0);v&&(g.style.maxWidth=v,g.style.marginLeft=`auto`,g.style.marginRight=`auto`,g.style.width=`100%`),l.append(f,d,g,_);let y=j(`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=Yo({config:e}),{root:x,textNode:S}=Jo();return n.append(c,i,l,y),s&&n.appendChild(s),{container:n,body:l,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:_,composerOverlay:y,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:f,welcomeIconHolder:u.iconHolder,greetingHost:d,introKicker:u.kicker,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:i,clearChatButton:o,clearChatButtonWrapper:s,iconHolder:M(`span`),headerTitle:M(`span`),headerSubtitle:M(`span`),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:x,peekTextNode:S}},Zs=(e,t=!0)=>{if(So(e))return Xs(e,t);let n=j(`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`}}),r=e?.layout?.header,i=e?.layout?.showHeader!==!1,a=r?Ko(e,r,{showClose:t}):Bo({config:e,showClose:t}),o=j(`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`}});o.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:s,greetingHost:c}=Ys(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=M(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=Js(`followUp`),h=$a(e,!1);h&&(p.style.maxWidth=h,p.style.marginLeft=`auto`,p.style.marginRight=`auto`,p.style.width=`100%`),o.append(l,c,p,m);let g=qo({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),Vo(n,a,e),n.append(o);let v=j(`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 _||(g.footer.style.display=`none`),n.append(g.footer),n.append(v),{container:n,body:o,messagesWrapper:p,starterSuggestions:f,transcriptSuggestions:m,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,welcomeHost:l,welcomeIconHolder:s.iconHolder,greetingHost:c,introKicker:s.kicker,introTitle:u,introSubtitle:d,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}},Qs=(e,t)=>{let n=M(`button`);n.type=`button`,n.innerHTML=`
|
|
13
13
|
<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">💬</span>
|
|
14
14
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
15
15
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -17,15 +17,15 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
17
17
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
18
18
|
</span>
|
|
19
19
|
<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">↗</span>
|
|
20
|
-
`,n.addEventListener(`click`,t);let r=e=>{let t=e.launcher??{},r=
|
|
21
|
-
`):``},
|
|
22
|
-
`).length>7?{tabindex:`0`,"aria-label":`${t} content`}:{},style:{color:
|
|
23
|
-
`);let i
|
|
24
|
-
`):``},$=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??`var(--persona-container, #f3f4f6)`,e.style.borderColor=t.codeBlockBorderColor??`var(--persona-border, #e5e7eb)`,e.style.color=t.codeBlockTextColor??`var(--persona-text, #171717)`},pc=(e,t)=>{let n=e.toolCall,r=t?.features?.toolCallDisplay,i=r?.collapsedMode??c.collapsedMode,a=n?.success===!1?n.error||`Tool failed`:fc(e,r?.previewMaxLines??c.previewMaxLines),o=n?gn(t,`tool`)===`row`?`${n.status===`complete`?`Used`:`Using`} ${n.name?.trim()||`tool`}`:je(n):``;if(!n)return{summary:o,previewText:a,isActive:!1};let s=n.status!==`complete`,l=t?.toolCall??{},u=o;return i===`tool-name`?u=n.name?.trim()||o:i===`tool-preview`&&a&&(u=a),s&&l.activeTextTemplate?u=Ie(n,l.activeTextTemplate,u):!s&&l.completeTextTemplate&&(u=Ie(n,l.completeTextTemplate,u)),n.success===!1?u+=` · Failed`:n.superseded&&(u+=` · Approved, ran again below`),{summary:u,previewText:a,isActive:s}},mc=(e,t,n,r)=>{mn(e,t,{stateSet:n,previewKind:`tool`,iconColor:dc(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},hc=(e,t,n=/* @__PURE__ */ new Set)=>{t=hn(t,`tool`);let r=e.toolCall,i=t?.toolCall??{},a=cn(`persona-tool-bubble`,e.id);if(i.backgroundColor&&(a.style.backgroundColor=i.backgroundColor),i.borderColor&&(a.style.borderColor=i.borderColor),i.borderWidth&&(a.style.borderWidth=i.borderWidth),i.borderRadius&&(a.style.borderRadius=i.borderRadius),a.style.boxShadow=i.shadow===void 0?`var(--persona-tool-bubble-shadow)`:i.shadow.trim()===``?`none`:i.shadow,!r)return vn(a,e,t,`tool`);let o=t?.features?.toolCallDisplay??{},s=o.expandable??c.expandable,l=s&&n.has(e.id),{summary:u,previewText:d,isActive:f}=pc(e,t),p=ln({expandable:s,expanded:l,bubbleType:`tool`});i.headerBackgroundColor&&(p.style.backgroundColor=i.headerBackgroundColor),i.headerPaddingX&&(p.style.paddingLeft=i.headerPaddingX,p.style.paddingRight=i.headerPaddingX),i.headerPaddingY&&(p.style.paddingTop=i.headerPaddingY,p.style.paddingBottom=i.headerPaddingY);let m=j(`div`,`persona-flex persona-flex-col persona-text-left`),h=j(`span`,`persona-text-xs persona-text-persona-primary`);i.headerTextColor&&(h.style.color=i.headerTextColor);let g=String(r.startedAt??Date.now()),_=()=>{let e=j(`span`,``);return e.setAttribute(`data-tool-elapsed`,g),e.textContent=Le(r),e},v=i.renderCollapsedSummary?.({message:e,toolCall:r,defaultSummary:u,previewText:d,collapsedMode:o.collapsedMode??c.collapsedMode,isActive:f,config:t??{},elapsed:Le(r),createElapsedElement:_});typeof v==`string`&&v.trim()?(h.textContent=v,m.appendChild(h)):v instanceof HTMLElement?m.appendChild(v):(h.textContent=u,m.appendChild(h));let y=o.loadingAnimation??c.loadingAnimation,b=i.activeTextTemplate,x=i.completeTextTemplate,S=f?b:x,C=v instanceof HTMLElement,w=(e,t)=>{h.textContent=``;let n=r.name?.trim()||`tool`,i=ze(e,n),a=0;for(let e of i){let n=e.styles.length>0?(()=>{let t=j(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return h.appendChild(t),t})():h;if(e.isDuration&&f)n.appendChild(_());else{let i=e.isDuration?Le(r):e.text;t?a=Ce(n,i,a):n.appendChild(document.createTextNode(i))}}};if(!C){if(f&&y!==`none`){let e=i.loadingAnimationDuration??2e3;if(h.setAttribute(`data-preserve-animation`,`true`),y===`pulse`)h.classList.add(`persona-tool-loading-pulse`),h.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),S&&w(S,!1);else if(h.classList.add(`persona-tool-loading-${y}`),h.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),y===`shimmer-color`&&(i.loadingAnimationColor&&h.style.setProperty(`--persona-tool-anim-color`,i.loadingAnimationColor),i.loadingAnimationSecondaryColor&&h.style.setProperty(`--persona-tool-anim-secondary-color`,i.loadingAnimationSecondaryColor)),S)w(S,!0);else{let e=h.textContent||u;h.textContent=``,Ce(h,e,0)}}else S&&w(S,!1)}let T=dc(i,gn(t,`tool`)===`row`),E=dn(p,m,{expandable:s,expanded:l,iconColor:T,metaGap:!0}),D=fn({bubble:a,previewKind:`tool`,expanded:l,isActive:f,previewText:d,activePreview:o.activePreview,activeMinHeight:o.activeMinHeight,renderPreview:()=>i.renderCollapsedPreview?.({message:e,toolCall:r,defaultPreview:d,isActive:f,config:t??{}})});if(!s)return a.append(p,D),vn(a,e,t,`tool`);let O=j(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);if(O.style.display=l?``:`none`,i.contentBackgroundColor&&(O.style.backgroundColor=i.contentBackgroundColor),i.contentTextColor&&(O.style.color=i.contentTextColor),i.contentPaddingX&&(O.style.paddingLeft=i.contentPaddingX,O.style.paddingRight=i.contentPaddingX),i.contentPaddingY&&(O.style.paddingTop=i.contentPaddingY,O.style.paddingBottom=i.contentPaddingY),t.future?.v5Defaults===!0)cc(O,e,t);else{if(r.name){let e=j(`div`,`persona-text-xs persona-text-persona-muted persona-italic`);i.contentTextColor?e.style.color=i.contentTextColor:i.headerTextColor&&(e.style.color=i.headerTextColor),e.textContent=r.name,O.appendChild(e)}if(r.args!==void 0){let e=j(`div`,`persona-space-y-1`),t=j(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Arguments`;let n=j(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,$(n,i),n.textContent=Me(r.args),e.append(t,n),O.appendChild(e)}if(r.chunks&&r.chunks.length){let e=j(`div`,`persona-space-y-1`),t=j(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Activity`;let n=j(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,$(n,i),n.textContent=r.chunks.join(``),e.append(t,n),O.appendChild(e)}if(r.success===!1&&O.appendChild(A(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``}})),r.status===`complete`&&r.result!==void 0){let e=j(`div`,`persona-space-y-1`),t=j(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Result`;let n=j(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,$(n,i),n.textContent=Me(r.result),e.append(t,n),O.appendChild(e)}if(r.status===`complete`&&typeof r.duration==`number`){let e=j(`div`,`persona-text-xs persona-text-persona-muted`);i.contentTextColor&&(e.style.color=i.contentTextColor),e.textContent=`Duration: ${r.duration}ms`,O.appendChild(e)}}return pn({expanded:l,header:p,toggleIcon:E,content:O,collapsedPreview:D,iconColor:T}),a.append(p,D,O),vn(a,e,t,`tool`)},{setLoader:gc,load:_c,provide:vc,getSync:yc}=me({fallbackImport:()=>import(`./chunk-GIqbL2Eg.js`)}),bc=_c,xc=yc,{setLoader:Sc,load:Cc}=me({fallbackImport:()=>import(`./chunk-DvqveR1q.js`)}),wc=Cc,Tc=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:Ec,load:Dc,provide:Oc,getSync:kc}=me({fallbackImport:()=>import(`./chunk-Do_1TKAR.js`)});let Ac=null;const jc=/* @__PURE__ */ new Set,Mc=e=>{if(Ac)return Ac;Ac=e,e.initArtifactsUi({componentRegistry:Ee});for(let t of Tc)Ee.has(t)||Ee.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=ye();t?e.__provideMarkdownParsers(t):Se(()=>{let t=ye();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>he());let n=[...jc];jc.clear();for(let e of n)try{e()}catch{}return e},Nc=()=>Dc().then(Mc),Pc=()=>{if(Ac)return Ac;let e=kc();return e?Mc(e):null},Fc=e=>Ac?()=>{}:(jc.add(e),()=>{jc.delete(e)});function Ic(e){return e?.features?.artifacts?.enabled===!0}function Lc(e,t){if(e.classList.remove(`persona-artifact-border-full`,`persona-artifact-border-left`),e.style.removeProperty(`--persona-artifact-pane-border`),e.style.removeProperty(`--persona-artifact-pane-border-left`),!Ic(t))return;let n=t.features?.artifacts?.layout,r=n?.paneBorder?.trim(),i=n?.paneBorderLeft?.trim();r?(e.classList.add(`persona-artifact-border-full`),e.style.setProperty(`--persona-artifact-pane-border`,r)):i&&(e.classList.add(`persona-artifact-border-left`),e.style.setProperty(`--persona-artifact-pane-border-left`,i))}function Rc(e){e.style.removeProperty(`--persona-artifact-doc-toolbar-icon-color`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-bg`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-border`)}const zc=[`panel`,`seamless`,`detached`];function Bc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&zc.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function Vc(e){return!e||!Ic(e)?!1:Bc(e)===`detached`}function Hc(e,t){if(!Ic(t)){e.style.removeProperty(`--persona-artifact-split-gap`),e.style.removeProperty(`--persona-artifact-pane-width`),e.style.removeProperty(`--persona-artifact-pane-max-width`),e.style.removeProperty(`--persona-artifact-pane-min-width`),e.style.removeProperty(`--persona-artifact-drawer-width`),e.style.removeProperty(`--persona-artifact-pane-bg`),e.style.removeProperty(`--persona-artifact-pane-padding`),Rc(e),Lc(e,t);return}let n=t.features?.artifacts?.layout,r=Bc(t)===`detached`?`var(--persona-panel-inset)`:`0`;e.style.setProperty(`--persona-artifact-split-gap`,n?.splitGap??r),e.style.setProperty(`--persona-artifact-pane-width`,n?.paneWidth??`40%`),e.style.setProperty(`--persona-artifact-pane-max-width`,n?.paneMaxWidth??`28rem`),n?.drawerWidth?e.style.setProperty(`--persona-artifact-drawer-width`,n.drawerWidth):e.style.removeProperty(`--persona-artifact-drawer-width`),n?.paneMinWidth?e.style.setProperty(`--persona-artifact-pane-min-width`,n.paneMinWidth):e.style.removeProperty(`--persona-artifact-pane-min-width`);let i=n?.paneBackground?.trim();i?e.style.setProperty(`--persona-artifact-pane-bg`,i):e.style.removeProperty(`--persona-artifact-pane-bg`);let a=n?.panePadding?.trim();a?e.style.setProperty(`--persona-artifact-pane-padding`,a):e.style.removeProperty(`--persona-artifact-pane-padding`);let o=[[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[t,n]of o){let r=t?.trim();r?e.style.setProperty(n,r):e.style.removeProperty(n)}Lc(e,t)}function Uc(e,t){for(let t of zc)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty(`--persona-artifact-pane-radius`),e.style.removeProperty(`--persona-artifact-pane-shadow`),e.style.removeProperty(`--persona-artifact-chat-shadow`),!Ic(t))return;let n=t.features?.artifacts?.layout,r=Bc(t);e.classList.add(`persona-artifact-appearance-${r}`);let i=n?.paneBorderRadius?.trim();i&&e.style.setProperty(`--persona-artifact-pane-radius`,i);let a=n?.paneShadow?.trim();a&&e.style.setProperty(`--persona-artifact-pane-shadow`,a);let o=n?.chatShadow?.trim();o&&e.style.setProperty(`--persona-artifact-chat-shadow`,o)}function Wc(e,t){return!t||!Ic(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}const Gc=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),Kc=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),qc=/* @__PURE__ */ new Set([`markdown`,`component`]),Jc=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Yc=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Xc=e=>!Gc.has(e),Zc=e=>typeof e==`string`&&Kc.has(e),Qc=e=>Object.keys(e).length>0;function $c(e,t,n,r){e.push({path:t,code:n,message:r})}const el=`Ignored an unsupported value.`,tl={kind:`mode`,message:el},nl={kind:`string`,message:`Expected a CSS length string.`},rl={kind:`boolean`},il={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:rl,showReasoning:rl,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:el},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:el},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:el},expandable:rl,grouped:rl}},reasoningDisplay:{kind:`object`,children:{expandable:rl,activePreview:rl}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:tl,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:tl,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:qc,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:qc}}},filePreview:{kind:`object`,children:{enabled:rl}},layout:{kind:`object`,children:{paneWidth:nl,paneMaxWidth:nl,paneMinWidth:nl,expandedPanelWidth:nl,resizableMinWidth:nl,resizableMaxWidth:nl,expandLauncherPanelWhenOpen:rl,resizable:rl}}}}}};function al(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:$c(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:$c(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:$c(r,n,`invalid_value`,t.message);case`mode`:return Zc(e)?tt(e):$c(r,n,`invalid_value`,t.message);case`modeMap`:{if(!Yc(e))return $c(r,n,`invalid_type`,`Expected an object.`);let i=t.keys===`mediaType`?void 0:t.keys,a={};for(let[t,o]of Object.entries(e)){let e=i?t:nt(t);Xc(t)&&(i?i.has(t):Jc.test(e))?Zc(o)?a[e]=tt(o):$c(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):$c(r,`${n}.${t}`,i?`unknown_key`:`invalid_value`,i?`Ignored an unsupported selector.`:`Expected a MIME type such as "text/html" or a wildcard such as "image/*".`)}return Qc(a)?a:void 0}case`object`:{if(t.bareMode&&Zc(e))return tt(e);if(!Yc(e))return $c(r,n,`invalid_type`,t.message??`Expected an object.`);let i=Object.keys(t.children),a=e=>n?`${n}.${e}`:e;for(let t of Object.keys(e))(!Xc(t)||!i.includes(t))&&$c(r,a(t),`unknown_key`,`Ignored because this key is not part of the persisted preference schema.`);let o={};for(let n of i){let i=t.children[n],s=al(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&$c(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=Yc(l)&&Yc(s)?{...l,...s}:s}return Qc(o)?o:void 0}}}function ol(e){let t=[];return{preferences:(e===null?void 0:al(e,il,``,t))??{},issues:t}}function sl(e){if(Array.isArray(e))return e.map(sl);if(!Yc(e))return e;let t={};for(let[n,r]of Object.entries(e))Xc(n)&&r!==void 0&&(t[n]=sl(r));return t}function cl(e,t){let n=sl(e);for(let[e,r]of Object.entries(t)){if(!Xc(e)||r===void 0)continue;let t=n[e];n[e]=Yc(t)&&Yc(r)?cl(t,r):sl(r)}return n}function ll(e){let t={},n;for(let r of e){let e=ol(r).preferences;n=dl(n,e.artifacts?.display),t=cl(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function ul(e,t){if(t===void 0)return e===void 0?void 0:sl(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byMediaType,...t.byMediaType},a={...r?{default:r}:{},...Qc(i)?{byMediaType:i}:{}};return Qc(a)?a:void 0}function dl(e,t){if(t===void 0)return e===void 0?void 0:sl(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byType,...n.byKind,...t.byType,...t.byKind},a=ul(n.files,t.files),o={...r?{default:r}:{},...Qc(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return Qc(o)?o:void 0}function fl(e={},t){let n=ll(t),r={...e};if(n.showToolCalls!==void 0&&(r.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(r.showReasoning=n.showReasoning),n.toolCallDisplay&&(r.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(r.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let t=e.artifacts??{},i={...t};if(n.artifacts.display!==void 0){let e=dl(t.display,n.artifacts.display);e!==void 0&&(i.display=e)}n.artifacts.filePreview&&(i.filePreview={...t.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...t.layout,...n.artifacts.layout}),r.artifacts=i}return r}function pl(e){let t=e.preferences;return!t||!Qc(t)?e:{...e,features:fl(e.features??{},[t])}}function ml(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function hl(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function gl(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function _l(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function vl(e,t){let n=(t.getComputedStyle(e).gap||`0px`).trim().split(/\s+/)[0]??`0px`,r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(n);return i?Number(i[1]):8}function yl(e,t,n,r,i,a,o=200){let s=ml(i,200),c=_l(t,n,r,o);c=Math.max(s,c);let l=hl(a);return l!==null&&(c=Math.min(c,l)),gl(e,s,c)}const{setLoader:bl,load:xl,provide:Sl,getSync:Cl}=me({fallbackImport:()=>import(`./chunk-Bp9uGcpc.js`)}),wl=xl,Tl=Cl,El=new class{#e=/* @__PURE__ */ 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 t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},Dl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Ol=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),kl=(e,t,n)=>{if(!Dl(e)||!Dl(t)||Ol.has(n))return t;let r={...e};for(let i of Object.keys(t)){if(t[i]===void 0){delete r[i];continue}let a=n?`${n}.${i}`:i;r[i]=kl(e[i],t[i],a)}return r};function Al(e,n){let r=h(u),i=o(e,n,r),a=g(t(kl(e,n,``),r,i),i);return f(l(a),fe(e,n))}const jl=()=>{let e=/* @__PURE__ */ new Map,t=(t,r)=>(e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(r),()=>n(t,r)),n=(t,n)=>{e.get(t)?.delete(n)};return{on:t,off:n,emit:(t,n)=>{e.get(t)?.forEach(e=>{try{e(n)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Event handler error:`,e)}})}}},Ml=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Nl=e=>{let t=e.trim(),n=t.indexOf(`{`);if(n===-1)return null;let r=0;for(let e=n;e<t.length;e+=1){let i=t[e];if(i===`{`&&(r+=1),i===`}`&&(--r,r===0))return t.slice(n,e+1)}return null},Pl=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=Ml(e),n=Nl(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!=`object`||!r.action)return null;let{action:i,...a}=r;return{type:String(i),payload:a,raw:r}}catch{return null}},Fl=e=>typeof e==`string`?e:e==null?``:String(e),Il={message:e=>{if(e.type===`message`)return{handled:!0,displayText:Fl(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=Fl(n.element);if(r&&t.document?.querySelector){let e=t.document.querySelector(r);e?setTimeout(()=>{e.click()},400):typeof console<`u`&&console.warn(`[AgentWidget] Element not found for selector:`,r)}return{handled:!0,displayText:Fl(n.text)}}},Ll=e=>Array.isArray(e)?e.map(e=>String(e)):[],Rl=e=>{let t=new Set(Ll(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Ll(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let n=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!==`assistant`||!n.text||t.has(n.message.id))return null;let i=typeof n.raw==`string`&&n.raw||typeof n.message.rawContent==`string`&&n.message.rawContent||typeof n.text==`string`&&n.text||null;!i&&typeof n.text==`string`&&n.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 a=i?e.parsers.reduce((e,t)=>e||t?.({text:i,message:n.message})||null,null):null;if(!a)return null;t.add(n.message.id),r();let o={action:a,message:n.message};e.emit(`action:detected`,o);for(let t of e.handlers)if(t)try{let r=t(a,{message:n.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit(`action:resubmit`,o)}});if(!r)continue;if(r.handled){let e=r.persistMessage!==!1;return{text:r.displayText===void 0?``:r.displayText,persist:e,resubmit:r.resubmit}}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Action handler error:`,e)}return{text:``,persist:!0}},syncFromMetadata:n}},zl=e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] Failed to parse stored state:`,e),null}},Bl=e=>e.map(e=>({...e,streaming:!1})),Vl=e=>e.map(e=>({...e,status:`complete`})),Hl=(e=`persona-state`)=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?zl(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?Bl(n.messages):void 0,artifacts:n.artifacts?Vl(n.artifacts):void 0};r.setItem(e,JSON.stringify(t))}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to persist state:`,e)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to clear stored state:`,e)}}}},Ul=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,`0`)},Wl=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{}return Ul(e)},Gl=async(e,t)=>{let n=await Wl(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await Wl(`${e}\0${t}`)}`}},Kl=(e,t,n)=>{let r=``,i=``,a=``,o=!1,s=!1,c=0,l=null,u=null,d=/* @__PURE__ */ new Set,f=()=>{if(n||o)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return o=!0,null}},p=()=>{let e=f();if(!e)return l;try{return e.getItem(r)}catch{return o=!0,l}},m=(e,t)=>{if(s||e===l)return;let n=l;l=e,c+=1;let r={previousToken:n,token:e,source:t,revision:c};for(let e of d)e(r)},h=e=>{s||(e.key===null||e.key===r)&&m(e.key===null?null:e.newValue??null,`external`)},g=(async()=>{let o=await Gl(e,t);r=o.storageKey,i=o.leaseKey,a=o.lockName,l=p(),!n&&typeof window<`u`&&window.addEventListener(`storage`,h)})(),_=e=>new Promise(t=>setTimeout(t,e)),v=()=>{let e=f();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let n=JSON.parse(t);return typeof n?.expiresAt==`number`&&typeof n?.ownerNonce==`string`?n:null}catch{return null}},y=e=>{let t=f();if(t)try{v()?.ownerNonce===e&&t.removeItem(i)}catch{}},b=/* @__PURE__ */ new Set,x=e=>s?Promise.reject(/* @__PURE__ */ Error(`Visitor store destroyed before its first init could start`)):e(),S=e=>new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),b.delete(r),window.removeEventListener(`storage`,a),t()}function a(e){(e.key===null||e.key===i)&&r()}b.add(r),window.addEventListener(`storage`,a)}),C=async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=Date.now()+15e3;for(;!s&&Date.now()<n;){let n=f();if(!n)break;let r=Date.now(),a=v();if(a&&a.expiresAt>r&&a.ownerNonce!==t)await S(Math.min(a.expiresAt-r,500));else{try{n.setItem(i,JSON.stringify({ownerNonce:t,expiresAt:r+1e4}))}catch{o=!0;break}if(await _(20+Math.random()*40),v()?.ownerNonce!==t)await S(500);else{u=t;try{return await x(e)}finally{u=null,y(t)}}}}return x(e)};return{ready:g,async get(){return await g,m(p(),`external`),l},async set(e){await g;let t=f();if(t)try{t.setItem(r,e)}catch{o=!0}m(e,`local`)},async clear(){await g;let e=f();if(e)try{e.removeItem(r)}catch{o=!0}m(null,`local`)},revision(){return c},subscribe(e){return d.add(e),()=>{d.delete(e)}},async withFirstInitLock(e){await g;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):f()?C(e):x(e)},matches(r,i,a){return r===e&&i===t&&a===n},destroy(){s=!0,d.clear(),typeof window<`u`&&window.removeEventListener(`storage`,h),u&&y(u);for(let e of[...b])e()}}},{setLoader:ql,load:Jl}=me({fallbackImport:()=>import(`./chunk-Zom7XuVp.js`)}),Yl=Jl,{setLoader:Xl,load:Zl,provide:Ql,getSync:$l}=me({fallbackImport:()=>import(`./chunk-Bvr_E4ga.js`)}),eu=Zl,tu=$l;function nu(){return null}function ru(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=Ee.get(e.component);if(!a){if(Tc.includes(e.component)){Nc().catch(()=>{});let e=j(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o={message:r,config:n,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function iu(e){if(typeof e.rawContent==`string`&&e.rawContent.length>0)return e.rawContent;if(typeof e.content==`string`){let t=e.content.trim();if(t.startsWith(`{`)||t.startsWith(`[`))return e.content}return null}function au(e){let t=iu(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function ou(e){let t=iu(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}const su=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function cu(e){let{onSubmit:t,onDismiss:n,title:r=`How satisfied are you?`,subtitle:i=`Please rate your experience`,commentPlaceholder:a=`Share your thoughts (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,ratingLabels:l=su}=e,u=document.createElement(`div`);u.className=`persona-feedback-container persona-feedback-csat`,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-label`,`Customer satisfaction feedback`);let d=null,f=document.createElement(`div`);f.className=`persona-feedback-content`;let p=document.createElement(`div`);p.className=`persona-feedback-header`;let m=document.createElement(`h3`);m.className=`persona-feedback-title`,m.textContent=r,p.appendChild(m);let h=document.createElement(`p`);h.className=`persona-feedback-subtitle`,h.textContent=i,p.appendChild(h),f.appendChild(p);let g=document.createElement(`div`);g.className=`persona-feedback-rating persona-feedback-rating-csat`,g.setAttribute(`role`,`radiogroup`),g.setAttribute(`aria-label`,`Satisfaction rating from 1 to 5`);let _=[];for(let e=1;e<=5;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-star-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`${e} star${e>1?`s`:``}: ${l[e-1]}`),t.title=l[e-1],t.dataset.rating=String(e),t.innerHTML=`
|
|
20
|
+
`,n.addEventListener(`click`,t);let r=e=>{let t=e.launcher??{},r=xo(e),i=sa(e)===`circle`;i?(n.dataset.personaLauncherVariant=`circle`,n.setAttribute(`aria-label`,t.title??`Open chat`)):(n.removeAttribute(`data-persona-launcher-variant`),n.removeAttribute(`aria-label`));let a=n.querySelector(`[data-role='launcher-title']`);if(a){let e=t.title??`Chat Assistant`;a.textContent=e,a.setAttribute(`title`,e)}let o=n.querySelector(`[data-role='launcher-subtitle']`);if(o){let e=t.subtitle??`Here to help you get answers fast`;o.textContent=e,o.setAttribute(`title`,e)}let s=n.querySelector(`.persona-flex-col`);s&&(t.textHidden||r||i?s.style.display=`none`:s.style.display=``);let c=n.querySelector(`[data-role='launcher-icon']`);if(c){if(t.agentIconHidden)c.style.display=`none`;else{let e=t.agentIconSize??`40px`;if(c.style.height=e,c.style.width=e,t.agentIconBackgroundColor?(c.style.backgroundColor=t.agentIconBackgroundColor,c.classList.remove(`persona-bg-persona-primary`)):(c.style.backgroundColor=``,c.classList.add(`persona-bg-persona-primary`)),c.innerHTML=``,t.agentIconName){let n=parseFloat(e)||24,r=N(t.agentIconName,n*.6,`var(--persona-text-inverse, #ffffff)`,1.5);r?(c.appendChild(r),c.style.display=``):(c.textContent=t.agentIconText??`💬`,c.style.display=``)}else t.iconUrl?c.style.display=`none`:(c.textContent=t.agentIconText??`💬`,c.style.display=``)}}let l=n.querySelector(`[data-role='launcher-image']`);if(l){let e=t.agentIconSize??`40px`;l.style.height=e,l.style.width=e,t.iconUrl&&!t.agentIconName&&!t.agentIconHidden?(l.src=t.iconUrl,l.style.display=`block`):l.style.display=`none`}let u=n.querySelector(`[data-role='launcher-call-to-action-icon']`);if(u){let e=t.callToActionIconSize??`32px`;u.style.height=e,u.style.width=e,t.callToActionIconBackgroundColor?(u.style.backgroundColor=t.callToActionIconBackgroundColor,u.classList.remove(`persona-bg-persona-primary`)):(u.style.backgroundColor=``,u.classList.add(`persona-bg-persona-primary`)),t.callToActionIconColor?(u.style.color=t.callToActionIconColor,u.classList.remove(`persona-text-persona-call-to-action`)):(u.style.color=``,u.classList.add(`persona-text-persona-call-to-action`));let n=0;if(t.callToActionIconPadding?(u.style.boxSizing=`border-box`,u.style.padding=t.callToActionIconPadding,n=(parseFloat(t.callToActionIconPadding)||0)*2):(u.style.boxSizing=``,u.style.padding=``),t.callToActionIconHidden||i)u.style.display=`none`;else if(u.style.display=r?`none`:``,u.innerHTML=``,t.callToActionIconName){let r=Math.max((parseFloat(e)||24)-n,8),i=N(t.callToActionIconName,r,`currentColor`,1.5);i?u.appendChild(i):u.textContent=t.callToActionIconText??`↗`}else u.textContent=t.callToActionIconText??`↗`}let d=t.position&&jo[t.position]?jo[t.position]:jo[`bottom-right`];n.className=r?`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`:`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 ${d}`,r||(n.style.zIndex=String(t.zIndex??1e5)),n.style.border=t.border??`1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))`,n.style.boxShadow=t.shadow===void 0?`var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))`:t.shadow.trim()===``?`none`:t.shadow,r?(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=t.collapsedMaxWidth??``,n.style.justifyContent=``,n.style.padding=``,n.style.overflow=``)};return e&&r(e),{element:n,update:r,destroy:()=>{n.removeEventListener(`click`,t),n.remove()}}},$s=/* @__PURE__ */ new Set,ec=e=>{let t=e?.persistState;return`${(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`}teaser-dismissed`},tc=(e,t)=>{if($s.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)===`1`}catch{return!1}},nc=(e,t)=>{if($s.add(e),t)try{window.localStorage.setItem(e,`1`)}catch{}},rc=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,ic=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||xo(e??{})?null:t},ac=(e,t)=>{let n=M(`div`,`persona-launcher-surface`);n.setAttribute(`data-persona-launcher-surface`,`true`);let r=e??{},i=null,a=null,o=null,s=null,c=null,l=!1,u=!1,d=!1,f=!1,p=()=>(i?.frequency??`once`)===`once`&&r.persistState!==!1,m=()=>{c!==null&&(clearTimeout(c),c=null)},h=()=>{a&&l&&(l=!1,a.hidden=!0)},g=e=>{m(),d=!0,h(),nc(ec(r),e&&p())},_=e=>{i&&!d&&g(e===`user`&&l)},v=()=>{c=null,!(!a||d||f)&&(u=!0,l=!0,a.hidden=!1,!(rc()||typeof a.animate!=`function`)&&a.animate([{opacity:`0`,transform:`translateY(6px)`},{opacity:`1`,transform:`none`}],{duration:220,easing:`ease-out`,fill:`backwards`}))},y=()=>{i&&a&&(d||u||f||tc(ec(r),p())||(m(),c=setTimeout(v,Math.max(0,i.delayMs??0))))},b=()=>{g(p()),t()},x=e=>{e.stopPropagation(),g(p())},S=Qs(e,()=>{_(`user`),t()}),C=()=>{m(),s?.removeEventListener(`click`,b),o?.removeEventListener(`click`,x),a?.remove(),a=null,s=null,o=null,l=!1},w=()=>{s=j(`button`,{className:`persona-launcher-teaser-text`,attrs:{type:`button`}}),s.addEventListener(`click`,b),o=j(`button`,{className:`persona-launcher-teaser-dismiss`,attrs:{type:`button`},text:`×`}),o.addEventListener(`click`,x),a=j(`div`,{className:`persona-launcher-teaser`,attrs:{"data-persona-launcher-teaser":`true`,role:`status`,"aria-live":`polite`,hidden:``}},s,o),n.insertBefore(a,S.element)},T=()=>{let e=r.launcher?.position??`bottom-right`,t=jo[e]??jo[`bottom-right`];a?(n.className=Me(`persona-launcher-surface`,t),n.setAttribute(`data-teaser`,e),n.style.zIndex=String(r.launcher?.zIndex??1e5),S.element.style.position=`static`):(n.className=`persona-launcher-surface`,n.removeAttribute(`data-teaser`),n.style.zIndex=``,S.element.style.position=``)},E=e=>{let t=ic(e);i=t,t?(a||w(),s.textContent=t.text,o.hidden=t.dismissible===!1,o.setAttribute(`aria-label`,t.dismissLabel??`Dismiss message`),y()):C()};return n.appendChild(S.element),e&&(E(e),T()),{element:n,launcher:S,get teaser(){return a?{element:a,show:v,dismiss:g}:null},setPanelOpen:(e,t=`user`)=>{f=e,e&&_(t)},update:e=>{r=e,S.update(e),E(e),T()},destroy:()=>{C(),S.destroy(),n.remove()}}},oc=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:i}=qs(e),a=Zs(e,t),o={wrapper:n,panel:r,pillRoot:i},s={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},l={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:o,panelElements:a,transcript:s,header:c,composer:l,replaceHeader:e=>(c.element.replaceWith(e.header),c.element=e.header,c.iconHolder=e.iconHolder,c.headerTitle=e.headerTitle,c.headerSubtitle=e.headerSubtitle,c.closeButton=e.closeButton,c.closeButtonWrapper=e.closeButtonWrapper,c.clearChatButton=e.clearChatButton,c.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{l.footer.replaceWith(e),l.footer=e}}},sc=({config:e,plugins:t,onToggle:n})=>{let r=t.find(e=>e.renderLauncher);if(r?.renderLauncher){let t=r.renderLauncher({config:e,defaultRenderer:()=>Qs(e,n).element,onToggle:n});if(t)return{instance:null,element:t}}let i=ac(e,n);return{instance:i,element:i.element}},cc=e=>{let t=e?.persistState;return(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`},lc=(e,t,n)=>`${cc(e)}plugin:${t}:${n}`,uc=e=>{let t=/* @__PURE__ */ new Map,n=!1,r=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return i=>{let a=t=>lc(e(),i,t);return{get:e=>{let i=a(e),o=r();if(o)try{return o.getItem(i)}catch{n=!0}return t.get(i)??null},set:(e,i)=>{let o=a(e),s=r();if(s)try{s.setItem(o,i);return}catch{n=!0}t.set(o,i)},remove:e=>{let i=a(e);t.delete(i);let o=r();if(o)try{o.removeItem(i)}catch{n=!0}}}}},$=(e,t)=>{let n=e.reasoning?.chunks.join(``).trim()??``;return n?n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
|
|
21
|
+
`):``},dc=(e,t,n)=>{L(e,t,{stateSet:n,previewKind:`reasoning`,iconColor:`currentColor`})},fc=(e,t,n=/* @__PURE__ */ new Set)=>{t=vn(t,`reasoning`);let r=e.reasoning,i=pn(`persona-reasoning-bubble`,e.id);if(!r)return R(i,e,t,`reasoning`);let a=t?.features?.reasoningDisplay??{},o=a.expandable??_e.expandable,s=o&&n.has(e.id),c=r.status!==`complete`,l=$(e,a.previewMaxLines??_e.previewMaxLines),u=mn({expandable:o,expanded:s,bubbleType:`reasoning`}),f=M(`div`,`persona-flex persona-flex-col persona-text-left`),h=M(`span`,`persona-text-xs persona-text-persona-primary`),g=yn(t,`reasoning`)===`row`,_=g&&!c?`Thought for ${bn(r.durationMs??(r.completedAt!==void 0&&r.startedAt!==void 0?r.completedAt-r.startedAt:void 0))}`:`Thinking...`,v=t?.reasoning??{},y=String(r.startedAt??Date.now()),b=()=>{let e=M(`span`,``);return e.setAttribute(`data-tool-elapsed`,y),e.textContent=m(r),e},x=v.renderCollapsedSummary?.({message:e,reasoning:r,defaultSummary:_,previewText:l,isActive:c,config:t??{},elapsed:m(r),createElapsedElement:b});typeof x==`string`&&x.trim()?(h.textContent=x,f.appendChild(h)):x instanceof HTMLElement?f.appendChild(x):(h.textContent=_,f.appendChild(h));let S=M(`span`,`persona-text-xs persona-text-persona-primary`);S.textContent=p(r),g||f.appendChild(S);let C=a.loadingAnimation??_e.loadingAnimation,w=v.activeTextTemplate,T=v.completeTextTemplate,E=c?w:T,D=x instanceof HTMLElement,ee=(e,t)=>{h.textContent=``;let n=d(e,``),i=0;for(let e of n){let n=e.styles.length>0?(()=>{let t=M(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return h.appendChild(t),t})():h;if(e.isDuration&&c)n.appendChild(b());else{let a=e.isDuration?m(r):e.text;t?i=He(n,a,i):n.appendChild(document.createTextNode(a))}}};if(!D&&E){if(S.style.display=`none`,h.style.display=``,c&&C!==`none`){let e=v.loadingAnimationDuration??2e3;h.setAttribute(`data-preserve-animation`,`true`),C===`pulse`?(h.classList.add(`persona-tool-loading-pulse`),h.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),ee(E,!1)):(h.classList.add(`persona-tool-loading-${C}`),h.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),C===`shimmer-color`&&(v.loadingAnimationColor&&h.style.setProperty(`--persona-tool-anim-color`,v.loadingAnimationColor),v.loadingAnimationSecondaryColor&&h.style.setProperty(`--persona-tool-anim-secondary-color`,v.loadingAnimationSecondaryColor)),ee(E,!0))}else ee(E,!1)}else if(!D&&c&&C!==`none`){h.style.display=``;let e=v.loadingAnimationDuration??2e3;if(h.setAttribute(`data-preserve-animation`,`true`),C===`pulse`)h.classList.add(`persona-tool-loading-pulse`),h.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`);else{h.classList.add(`persona-tool-loading-${C}`),h.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),C===`shimmer-color`&&(v.loadingAnimationColor&&h.style.setProperty(`--persona-tool-anim-color`,v.loadingAnimationColor),v.loadingAnimationSecondaryColor&&h.style.setProperty(`--persona-tool-anim-secondary-color`,v.loadingAnimationSecondaryColor));let t=h.textContent||_;h.textContent=``,He(h,t,0)}r.status===`complete`&&!g&&(h.style.display=`none`)}else D||(r.status===`complete`&&!g?h.style.display=`none`:h.style.display=``);if(a.iconName&&!D){let e=M(`span`,`persona-reasoning-header-icon`),t=N(a.iconName,16,`currentColor`,2);t&&(e.appendChild(t),u.appendChild(e))}let te=`currentColor`,ne=gn(u,f,{expandable:o,expanded:s,iconColor:te,metaGap:!1}),re=_n({bubble:i,previewKind:`reasoning`,expanded:s,isActive:c,previewText:l,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:r,defaultPreview:l,isActive:c,config:t??{}})});if(!o)return i.append(u,re),R(i,e,t,`reasoning`);let ie=M(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3`);ie.style.display=s?``:`none`;let ae=r.chunks.join(``),oe=M(`div`,`persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted`);return oe.textContent=ae||(r.status===`complete`?`No additional context was shared.`:`Waiting for details…`),ie.appendChild(oe),I({expanded:s,header:u,toggleIcon:ne,content:ie,collapsedPreview:re,iconColor:te}),i.append(u,re,ie),R(i,e,t,`reasoning`)},pc=e=>{if(e==null)return!0;if(typeof e==`string`){if(!e.trim())return!0;try{return pc(JSON.parse(e))}catch{return!1}}return typeof e==`object`&&Object.keys(e).length===0},mc=e=>{if(typeof e==`object`&&e)return!0;if(typeof e!=`string`)return!1;try{let t=JSON.parse(e);return typeof t==`object`&&!!t}catch{return!1}};function hc(e,t,n){let r=t.toolCall;if(!r)return;let a=n.toolCall??{},o=(t,n)=>{let r=j(`section`,{className:`persona-tool-detail`,attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:a.codeBlockBackgroundColor,borderColor:a.codeBlockBorderColor,borderWidth:a.codeBlockBorderColor?`1px`:void 0}}),o=j(`div`,{className:`persona-tool-detail-label`,text:t,style:{color:a.labelTextColor}}),s=i(n),c=j(`pre`,{className:`persona-tool-detail-value${mc(n)?` persona-tool-detail-code`:``}`,text:s,attrs:s.length>420||s.split(`
|
|
22
|
+
`).length>7?{tabindex:`0`,"aria-label":`${t} content`}:{},style:{color:a.codeBlockTextColor??a.contentTextColor}}),l=j(`button`,{className:`persona-tool-detail-copy`,attrs:{type:`button`,"data-persona-copy-tool-detail":``,"aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),u=N(`copy`,14,`currentColor`,1.7);u&&l.appendChild(u),r.append(o,c,l),e.appendChild(r)};pc(r.args)||o(`Request`,r.args);let s=r.status===`complete`&&r.result!==void 0?r.result:r.chunks?.join(``);s!==void 0&&(typeof s!=`string`||s.trim())&&o(`Response`,s),r.success===!1&&e.appendChild(j(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``,role:`status`}}))}const gc=/* @__PURE__ */ new WeakMap;async function _c(e){let t=e.closest(`[data-persona-tool-detail]`),n=t?.querySelector(`pre`);if(!n)return;let r=`Copy ${t?.getAttribute(`data-persona-tool-detail`)}`;clearTimeout(gc.get(e));try{await navigator.clipboard.writeText(n.textContent??``),e.dataset.copied=`true`,e.setAttribute(`aria-label`,`Copied`),e.title=`Copied`;let t=N(`check`,14,`currentColor`,2);t&&e.replaceChildren(t)}catch{e.setAttribute(`aria-label`,`Copy failed — try again`),e.title=`Copy failed — try again`}gc.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute(`aria-label`,r),e.title=r;let t=N(`copy`,14,`currentColor`,1.7);t&&e.replaceChildren(t),gc.delete(e)},1800))}const vc=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?`currentColor`:`var(--persona-primary, #171717)`),yc=(e,t)=>{let n=e.toolCall;if(!n)return``;let r=(n.chunks??[]).join(``).trim();if(r)return r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join(`
|
|
23
|
+
`);let a=i(n.args).trim();return a?a.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
+
`):``},bc=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??`var(--persona-container, #f3f4f6)`,e.style.borderColor=t.codeBlockBorderColor??`var(--persona-border, #e5e7eb)`,e.style.color=t.codeBlockTextColor??`var(--persona-text, #171717)`},xc=(e,t)=>{let n=e.toolCall,i=t?.features?.toolCallDisplay,a=i?.collapsedMode??ee.collapsedMode,o=n?.success===!1?n.error||`Tool failed`:yc(e,i?.previewMaxLines??ee.previewMaxLines),s=n?.interrupted?`${n.name?.trim()||`Tool`} · Interrupted`:n?yn(t,`tool`)===`row`?`${n.status===`complete`?`Used`:`Using`} ${n.name?.trim()||`tool`}`:r(n):``;if(!n)return{summary:s,previewText:o,isActive:!1};let l=n.status!==`complete`,u=t?.toolCall??{},d=s;return a===`tool-name`?d=n.name?.trim()||s:a===`tool-preview`&&o&&(d=o),l&&u.activeTextTemplate?d=c(n,u.activeTextTemplate,d):!l&&!n.interrupted&&u.completeTextTemplate&&(d=c(n,u.completeTextTemplate,d)),n.interrupted?d.includes(` · Interrupted`)||(d+=` · Interrupted`):n.success===!1?d+=` · Failed`:n.superseded&&(d+=` · Approved, ran again below`),{summary:d,previewText:o,isActive:l}},Sc=(e,t,n,r)=>{L(e,t,{stateSet:n,previewKind:`tool`,iconColor:vc(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},Cc=(e,t,n=/* @__PURE__ */ new Set)=>{t=vn(t,`tool`);let r=e.toolCall,a=t?.toolCall??{},o=pn(`persona-tool-bubble`,e.id);if(a.backgroundColor&&(o.style.backgroundColor=a.backgroundColor),a.borderColor&&(o.style.borderColor=a.borderColor),a.borderWidth&&(o.style.borderWidth=a.borderWidth),a.borderRadius&&(o.style.borderRadius=a.borderRadius),o.style.boxShadow=a.shadow===void 0?`var(--persona-tool-bubble-shadow)`:a.shadow.trim()===``?`none`:a.shadow,!r)return R(o,e,t,`tool`);let s=t?.features?.toolCallDisplay??{},c=s.expandable??ee.expandable,u=c&&n.has(e.id),{summary:f,previewText:p,isActive:m}=xc(e,t),h=mn({expandable:c,expanded:u,bubbleType:`tool`});a.headerBackgroundColor&&(h.style.backgroundColor=a.headerBackgroundColor),a.headerPaddingX&&(h.style.paddingLeft=a.headerPaddingX,h.style.paddingRight=a.headerPaddingX),a.headerPaddingY&&(h.style.paddingTop=a.headerPaddingY,h.style.paddingBottom=a.headerPaddingY);let g=M(`div`,`persona-flex persona-flex-col persona-text-left`),_=M(`span`,`persona-text-xs persona-text-persona-primary`);a.headerTextColor&&(_.style.color=a.headerTextColor);let v=String(r.startedAt??Date.now()),y=()=>{let e=M(`span`,``);return m&&e.setAttribute(`data-tool-elapsed`,v),e.textContent=l(r),e},b=a.renderCollapsedSummary?.({message:e,toolCall:r,defaultSummary:f,previewText:p,collapsedMode:s.collapsedMode??ee.collapsedMode,isActive:m,config:t??{},elapsed:l(r),createElapsedElement:y});typeof b==`string`&&b.trim()?(_.textContent=b,g.appendChild(_)):b instanceof HTMLElement?g.appendChild(b):(_.textContent=f,g.appendChild(_));let x=s.loadingAnimation??ee.loadingAnimation,S=a.activeTextTemplate,C=r.interrupted?void 0:a.completeTextTemplate,w=m?S:C,T=b instanceof HTMLElement,E=(e,t)=>{_.textContent=``;let n=r.name?.trim()||`tool`,i=d(e,n),a=0;for(let e of i){let n=e.styles.length>0?(()=>{let t=M(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return _.appendChild(t),t})():_;if(e.isDuration&&m)n.appendChild(y());else{let i=e.isDuration?l(r):e.text;t?a=He(n,i,a):n.appendChild(document.createTextNode(i))}}};if(!T){if(m&&x!==`none`){let e=a.loadingAnimationDuration??2e3;if(_.setAttribute(`data-preserve-animation`,`true`),x===`pulse`)_.classList.add(`persona-tool-loading-pulse`),_.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),w&&E(w,!1);else if(_.classList.add(`persona-tool-loading-${x}`),_.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),x===`shimmer-color`&&(a.loadingAnimationColor&&_.style.setProperty(`--persona-tool-anim-color`,a.loadingAnimationColor),a.loadingAnimationSecondaryColor&&_.style.setProperty(`--persona-tool-anim-secondary-color`,a.loadingAnimationSecondaryColor)),w)E(w,!0);else{let e=_.textContent||f;_.textContent=``,He(_,e,0)}}else w&&E(w,!1)}let D=vc(a,yn(t,`tool`)===`row`),te=gn(h,g,{expandable:c,expanded:u,iconColor:D,metaGap:!0}),ne=_n({bubble:o,previewKind:`tool`,expanded:u,isActive:m,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>a.renderCollapsedPreview?.({message:e,toolCall:r,defaultPreview:p,isActive:m,config:t??{}})});if(!c)return o.append(h,ne),R(o,e,t,`tool`);let re=M(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);if(re.style.display=u?``:`none`,a.contentBackgroundColor&&(re.style.backgroundColor=a.contentBackgroundColor),a.contentTextColor&&(re.style.color=a.contentTextColor),a.contentPaddingX&&(re.style.paddingLeft=a.contentPaddingX,re.style.paddingRight=a.contentPaddingX),a.contentPaddingY&&(re.style.paddingTop=a.contentPaddingY,re.style.paddingBottom=a.contentPaddingY),t.future?.v5Defaults===!0)hc(re,e,t);else{if(r.name){let e=M(`div`,`persona-text-xs persona-text-persona-muted persona-italic`);a.contentTextColor?e.style.color=a.contentTextColor:a.headerTextColor&&(e.style.color=a.headerTextColor),e.textContent=r.name,re.appendChild(e)}if(r.args!==void 0){let e=M(`div`,`persona-space-y-1`),t=M(`div`,`persona-text-xs persona-text-persona-muted`);a.labelTextColor&&(t.style.color=a.labelTextColor),t.textContent=`Arguments`;let n=M(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,bc(n,a),n.textContent=i(r.args),e.append(t,n),re.appendChild(e)}if(r.chunks&&r.chunks.length){let e=M(`div`,`persona-space-y-1`),t=M(`div`,`persona-text-xs persona-text-persona-muted`);a.labelTextColor&&(t.style.color=a.labelTextColor),t.textContent=`Activity`;let n=M(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,bc(n,a),n.textContent=r.chunks.join(``),e.append(t,n),re.appendChild(e)}if(r.success===!1&&re.appendChild(j(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``}})),r.status===`complete`&&r.result!==void 0){let e=M(`div`,`persona-space-y-1`),t=M(`div`,`persona-text-xs persona-text-persona-muted`);a.labelTextColor&&(t.style.color=a.labelTextColor),t.textContent=`Result`;let n=M(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,bc(n,a),n.textContent=i(r.result),e.append(t,n),re.appendChild(e)}if(r.status===`complete`&&typeof r.duration==`number`){let e=M(`div`,`persona-text-xs persona-text-persona-muted`);a.contentTextColor&&(e.style.color=a.contentTextColor),e.textContent=`Duration: ${r.duration}ms`,re.appendChild(e)}}return I({expanded:u,header:h,toggleIcon:te,content:re,collapsedPreview:ne,iconColor:D}),o.append(h,ne,re),R(o,e,t,`tool`)},{setLoader:wc,load:Tc,provide:Ec,getSync:Dc}=Ne({fallbackImport:()=>import(`./chunk-Bm2-bemv.js`)}),Oc=Tc,kc=Dc,{setLoader:Ac,load:jc}=Ne({fallbackImport:()=>import(`./chunk-DvqveR1q.js`)}),Mc=jc,Nc=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:Pc,load:Fc,provide:Ic,getSync:Lc}=Ne({fallbackImport:()=>import(`./chunk-Do_1TKAR.js`)});let Rc=null;const zc=/* @__PURE__ */ new Set,Bc=e=>{if(Rc)return Rc;Rc=e,e.initArtifactsUi({componentRegistry:Ge});for(let t of Nc)Ge.has(t)||Ge.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Re();t?e.__provideMarkdownParsers(t):Ve(()=>{let t=Re();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>Pe());let n=[...zc];zc.clear();for(let e of n)try{e()}catch{}return e},Vc=()=>Fc().then(Bc),Hc=()=>{if(Rc)return Rc;let e=Lc();return e?Bc(e):null},Uc=e=>Rc?()=>{}:(zc.add(e),()=>{zc.delete(e)});function Wc(e){return e?.features?.artifacts?.enabled===!0}function Gc(e,t){if(e.classList.remove(`persona-artifact-border-full`,`persona-artifact-border-left`),e.style.removeProperty(`--persona-artifact-pane-border`),e.style.removeProperty(`--persona-artifact-pane-border-left`),!Wc(t))return;let n=t.features?.artifacts?.layout,r=n?.paneBorder?.trim(),i=n?.paneBorderLeft?.trim();r?(e.classList.add(`persona-artifact-border-full`),e.style.setProperty(`--persona-artifact-pane-border`,r)):i&&(e.classList.add(`persona-artifact-border-left`),e.style.setProperty(`--persona-artifact-pane-border-left`,i))}function Kc(e){e.style.removeProperty(`--persona-artifact-doc-toolbar-icon-color`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-bg`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-border`)}const qc=[`panel`,`seamless`,`detached`];function Jc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&qc.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function Yc(e){return!e||!Wc(e)?!1:Jc(e)===`detached`}function Xc(e,t){if(!Wc(t)){e.style.removeProperty(`--persona-artifact-split-gap`),e.style.removeProperty(`--persona-artifact-pane-width`),e.style.removeProperty(`--persona-artifact-pane-max-width`),e.style.removeProperty(`--persona-artifact-pane-min-width`),e.style.removeProperty(`--persona-artifact-drawer-width`),e.style.removeProperty(`--persona-artifact-pane-bg`),e.style.removeProperty(`--persona-artifact-pane-padding`),Kc(e),Gc(e,t);return}let n=t.features?.artifacts?.layout,r=Jc(t)===`detached`?`var(--persona-panel-inset)`:`0`;e.style.setProperty(`--persona-artifact-split-gap`,n?.splitGap??r),e.style.setProperty(`--persona-artifact-pane-width`,n?.paneWidth??`40%`),e.style.setProperty(`--persona-artifact-pane-max-width`,n?.paneMaxWidth??`28rem`),n?.drawerWidth?e.style.setProperty(`--persona-artifact-drawer-width`,n.drawerWidth):e.style.removeProperty(`--persona-artifact-drawer-width`),n?.paneMinWidth?e.style.setProperty(`--persona-artifact-pane-min-width`,n.paneMinWidth):e.style.removeProperty(`--persona-artifact-pane-min-width`);let i=n?.paneBackground?.trim();i?e.style.setProperty(`--persona-artifact-pane-bg`,i):e.style.removeProperty(`--persona-artifact-pane-bg`);let a=n?.panePadding?.trim();a?e.style.setProperty(`--persona-artifact-pane-padding`,a):e.style.removeProperty(`--persona-artifact-pane-padding`);let o=[[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[t,n]of o){let r=t?.trim();r?e.style.setProperty(n,r):e.style.removeProperty(n)}Gc(e,t)}function Zc(e,t){for(let t of qc)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty(`--persona-artifact-pane-radius`),e.style.removeProperty(`--persona-artifact-pane-shadow`),e.style.removeProperty(`--persona-artifact-chat-shadow`),!Wc(t))return;let n=t.features?.artifacts?.layout,r=Jc(t);e.classList.add(`persona-artifact-appearance-${r}`);let i=n?.paneBorderRadius?.trim();i&&e.style.setProperty(`--persona-artifact-pane-radius`,i);let a=n?.paneShadow?.trim();a&&e.style.setProperty(`--persona-artifact-pane-shadow`,a);let o=n?.chatShadow?.trim();o&&e.style.setProperty(`--persona-artifact-chat-shadow`,o)}function Qc(e,t){return!t||!Wc(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}const $c=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),el=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),tl=/* @__PURE__ */ new Set([`markdown`,`component`]),nl=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,rl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),il=e=>!$c.has(e),al=e=>typeof e==`string`&&el.has(e),ol=e=>Object.keys(e).length>0;function sl(e,t,n,r){e.push({path:t,code:n,message:r})}const cl=`Ignored an unsupported value.`,ll={kind:`mode`,message:cl},ul={kind:`string`,message:`Expected a CSS length string.`},dl={kind:`boolean`},fl={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:dl,showReasoning:dl,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:cl},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:cl},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:cl},expandable:dl,grouped:dl}},reasoningDisplay:{kind:`object`,children:{expandable:dl,activePreview:dl}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:ll,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:ll,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:tl,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:tl}}},filePreview:{kind:`object`,children:{enabled:dl}},layout:{kind:`object`,children:{paneWidth:ul,paneMaxWidth:ul,paneMinWidth:ul,expandedPanelWidth:ul,resizableMinWidth:ul,resizableMaxWidth:ul,expandLauncherPanelWhenOpen:dl,resizable:dl}}}}}};function pl(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:sl(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:sl(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:sl(r,n,`invalid_value`,t.message);case`mode`:return al(e)?it(e):sl(r,n,`invalid_value`,t.message);case`modeMap`:{if(!rl(e))return sl(r,n,`invalid_type`,`Expected an object.`);let i=t.keys===`mediaType`?void 0:t.keys,a={};for(let[t,o]of Object.entries(e)){let e=i?t:F(t);il(t)&&(i?i.has(t):nl.test(e))?al(o)?a[e]=it(o):sl(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):sl(r,`${n}.${t}`,i?`unknown_key`:`invalid_value`,i?`Ignored an unsupported selector.`:`Expected a MIME type such as "text/html" or a wildcard such as "image/*".`)}return ol(a)?a:void 0}case`object`:{if(t.bareMode&&al(e))return it(e);if(!rl(e))return sl(r,n,`invalid_type`,t.message??`Expected an object.`);let i=Object.keys(t.children),a=e=>n?`${n}.${e}`:e;for(let t of Object.keys(e))(!il(t)||!i.includes(t))&&sl(r,a(t),`unknown_key`,`Ignored because this key is not part of the persisted preference schema.`);let o={};for(let n of i){let i=t.children[n],s=pl(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&sl(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=rl(l)&&rl(s)?{...l,...s}:s}return ol(o)?o:void 0}}}function ml(e){let t=[];return{preferences:(e===null?void 0:pl(e,fl,``,t))??{},issues:t}}function hl(e){if(Array.isArray(e))return e.map(hl);if(!rl(e))return e;let t={};for(let[n,r]of Object.entries(e))il(n)&&r!==void 0&&(t[n]=hl(r));return t}function gl(e,t){let n=hl(e);for(let[e,r]of Object.entries(t)){if(!il(e)||r===void 0)continue;let t=n[e];n[e]=rl(t)&&rl(r)?gl(t,r):hl(r)}return n}function _l(e){let t={},n;for(let r of e){let e=ml(r).preferences;n=yl(n,e.artifacts?.display),t=gl(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function vl(e,t){if(t===void 0)return e===void 0?void 0:hl(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byMediaType,...t.byMediaType},a={...r?{default:r}:{},...ol(i)?{byMediaType:i}:{}};return ol(a)?a:void 0}function yl(e,t){if(t===void 0)return e===void 0?void 0:hl(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byType,...n.byKind,...t.byType,...t.byKind},a=vl(n.files,t.files),o={...r?{default:r}:{},...ol(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return ol(o)?o:void 0}function bl(e={},t){let n=_l(t),r={...e};if(n.showToolCalls!==void 0&&(r.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(r.showReasoning=n.showReasoning),n.toolCallDisplay&&(r.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(r.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let t=e.artifacts??{},i={...t};if(n.artifacts.display!==void 0){let e=yl(t.display,n.artifacts.display);e!==void 0&&(i.display=e)}n.artifacts.filePreview&&(i.filePreview={...t.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...t.layout,...n.artifacts.layout}),r.artifacts=i}return r}function xl(e){let t=e.preferences;return!t||!ol(t)?e:{...e,features:bl(e.features??{},[t])}}function Sl(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Cl(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function wl(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Tl(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function El(e,t){let n=(t.getComputedStyle(e).gap||`0px`).trim().split(/\s+/)[0]??`0px`,r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(n);return i?Number(i[1]):8}function Dl(e,t,n,r,i,a,o=200){let s=Sl(i,200),c=Tl(t,n,r,o);c=Math.max(s,c);let l=Cl(a);return l!==null&&(c=Math.min(c,l)),wl(e,s,c)}const{setLoader:Ol,load:kl,provide:Al,getSync:jl}=Ne({fallbackImport:()=>import(`./chunk-Bp9uGcpc.js`)}),Ml=kl,Nl=jl,Pl=new class{#e=/* @__PURE__ */ 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 t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},Fl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Il=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),Ll=(e,t,n)=>{if(!Fl(e)||!Fl(t)||Il.has(n))return t;let r={...e};for(let i of Object.keys(t)){if(t[i]===void 0){delete r[i];continue}let a=n?`${n}.${i}`:i;r[i]=Ll(e[i],t[i],a)}return r};function Rl(e,t){let n=se(ne),r=E(e,t,n),i=O(x(Ll(e,t,``),n,r),r);return ie(te(i),je(e,t))}const zl=()=>{let e=/* @__PURE__ */ new Map,t=(t,r)=>(e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(r),()=>n(t,r)),n=(t,n)=>{e.get(t)?.delete(n)};return{on:t,off:n,emit:(t,n)=>{e.get(t)?.forEach(e=>{try{e(n)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Event handler error:`,e)}})}}},Bl=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Vl=e=>{let t=e.trim(),n=t.indexOf(`{`);if(n===-1)return null;let r=0;for(let e=n;e<t.length;e+=1){let i=t[e];if(i===`{`&&(r+=1),i===`}`&&(--r,r===0))return t.slice(n,e+1)}return null},Hl=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=Bl(e),n=Vl(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!=`object`||!r.action)return null;let{action:i,...a}=r;return{type:String(i),payload:a,raw:r}}catch{return null}},Ul=e=>typeof e==`string`?e:e==null?``:String(e),Wl={message:e=>{if(e.type===`message`)return{handled:!0,displayText:Ul(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=Ul(n.element);if(r&&t.document?.querySelector){let e=t.document.querySelector(r);e?setTimeout(()=>{e.click()},400):typeof console<`u`&&console.warn(`[AgentWidget] Element not found for selector:`,r)}return{handled:!0,displayText:Ul(n.text)}}},Gl=e=>Array.isArray(e)?e.map(e=>String(e)):[],Kl=e=>{let t=new Set(Gl(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Gl(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let n=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!==`assistant`||!n.text||t.has(n.message.id))return null;let i=typeof n.raw==`string`&&n.raw||typeof n.message.rawContent==`string`&&n.message.rawContent||typeof n.text==`string`&&n.text||null;!i&&typeof n.text==`string`&&n.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 a=i?e.parsers.reduce((e,t)=>e||t?.({text:i,message:n.message})||null,null):null;if(!a)return null;t.add(n.message.id),r();let o={action:a,message:n.message};e.emit(`action:detected`,o);for(let t of e.handlers)if(t)try{let r=t(a,{message:n.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit(`action:resubmit`,o)}});if(!r)continue;if(r.handled){let e=r.persistMessage!==!1;return{text:r.displayText===void 0?``:r.displayText,persist:e,resubmit:r.resubmit}}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Action handler error:`,e)}return{text:``,persist:!0}},syncFromMetadata:n}},ql=e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] Failed to parse stored state:`,e),null}},Jl=e=>e.map(e=>({...e,streaming:!1})),Yl=e=>e.map(e=>({...e,status:`complete`})),Xl=e=>`${e??`persona-`}state`,Zl=(e=Xl())=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?ql(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?Jl(n.messages):void 0,artifacts:n.artifacts?Yl(n.artifacts):void 0};r.setItem(e,JSON.stringify(t))}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to persist state:`,e)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to clear stored state:`,e)}}}},Ql=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,`0`)},$l=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{}return Ql(e)},eu=async(e,t)=>{let n=await $l(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await $l(`${e}\0${t}`)}`}},tu=(e,t,n)=>{let r=``,i=``,a=``,o=!1,s=!1,c=0,l=null,u=null,d=/* @__PURE__ */ new Set,f=()=>{if(n||o)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return o=!0,null}},p=()=>{let e=f();if(!e)return l;try{return e.getItem(r)}catch{return o=!0,l}},m=(e,t)=>{if(s||e===l)return;let n=l;l=e,c+=1;let r={previousToken:n,token:e,source:t,revision:c};for(let e of d)e(r)},h=e=>{s||(e.key===null||e.key===r)&&m(e.key===null?null:e.newValue??null,`external`)},g=(async()=>{let o=await eu(e,t);r=o.storageKey,i=o.leaseKey,a=o.lockName,l=p(),!n&&typeof window<`u`&&window.addEventListener(`storage`,h)})(),_=e=>new Promise(t=>setTimeout(t,e)),v=()=>{let e=f();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let n=JSON.parse(t);return typeof n?.expiresAt==`number`&&typeof n?.ownerNonce==`string`?n:null}catch{return null}},y=e=>{let t=f();if(t)try{v()?.ownerNonce===e&&t.removeItem(i)}catch{}},b=/* @__PURE__ */ new Set,x=e=>s?Promise.reject(/* @__PURE__ */ Error(`Visitor store destroyed before its first init could start`)):e(),S=e=>new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),b.delete(r),window.removeEventListener(`storage`,a),t()}function a(e){(e.key===null||e.key===i)&&r()}b.add(r),window.addEventListener(`storage`,a)}),C=async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=Date.now()+15e3;for(;!s&&Date.now()<n;){let n=f();if(!n)break;let r=Date.now(),a=v();if(a&&a.expiresAt>r&&a.ownerNonce!==t)await S(Math.min(a.expiresAt-r,500));else{try{n.setItem(i,JSON.stringify({ownerNonce:t,expiresAt:r+1e4}))}catch{o=!0;break}if(await _(20+Math.random()*40),v()?.ownerNonce!==t)await S(500);else{u=t;try{return await x(e)}finally{u=null,y(t)}}}}return x(e)};return{ready:g,async get(){return await g,m(p(),`external`),l},async set(e){await g;let t=f();if(t)try{t.setItem(r,e)}catch{o=!0}m(e,`local`)},async clear(){await g;let e=f();if(e)try{e.removeItem(r)}catch{o=!0}m(null,`local`)},revision(){return c},subscribe(e){return d.add(e),()=>{d.delete(e)}},async withFirstInitLock(e){await g;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):f()?C(e):x(e)},matches(r,i,a){return r===e&&i===t&&a===n},destroy(){s=!0,d.clear(),typeof window<`u`&&window.removeEventListener(`storage`,h),u&&y(u);for(let e of[...b])e()}}},{setLoader:nu,load:ru}=Ne({fallbackImport:()=>import(`./chunk-Zom7XuVp.js`)}),iu=ru,{setLoader:au,load:ou,provide:su,getSync:cu}=Ne({fallbackImport:()=>import(`./chunk-Bvr_E4ga.js`)}),lu=ou,uu=cu;function du(){return null}function fu(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=Ge.get(e.component);if(!a){if(Nc.includes(e.component)){Vc().catch(()=>{});let e=M(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o={message:r,config:n,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function pu(e){if(typeof e.rawContent==`string`&&e.rawContent.length>0)return e.rawContent;if(typeof e.content==`string`){let t=e.content.trim();if(t.startsWith(`{`)||t.startsWith(`[`))return e.content}return null}function mu(e){let t=pu(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function hu(e){let t=pu(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}const gu=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function _u(e){let{onSubmit:t,onDismiss:n,title:r=`How satisfied are you?`,subtitle:i=`Please rate your experience`,commentPlaceholder:a=`Share your thoughts (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,ratingLabels:l=gu}=e,u=document.createElement(`div`);u.className=`persona-feedback-container persona-feedback-csat`,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-label`,`Customer satisfaction feedback`);let d=null,f=document.createElement(`div`);f.className=`persona-feedback-content`;let p=document.createElement(`div`);p.className=`persona-feedback-header`;let m=document.createElement(`h3`);m.className=`persona-feedback-title`,m.textContent=r,p.appendChild(m);let h=document.createElement(`p`);h.className=`persona-feedback-subtitle`,h.textContent=i,p.appendChild(h),f.appendChild(p);let g=document.createElement(`div`);g.className=`persona-feedback-rating persona-feedback-rating-csat`,g.setAttribute(`role`,`radiogroup`),g.setAttribute(`aria-label`,`Satisfaction rating from 1 to 5`);let _=[];for(let e=1;e<=5;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-star-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`${e} star${e>1?`s`:``}: ${l[e-1]}`),t.title=l[e-1],t.dataset.rating=String(e),t.innerHTML=`
|
|
25
25
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
26
26
|
<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>
|
|
27
27
|
</svg>
|
|
28
|
-
`,t.addEventListener(`click`,()=>{d=e,_.forEach((t,n)=>{let r=n<e;t.classList.toggle(`selected`,r),t.setAttribute(`aria-checked`,n===e-1?`true`:`false`)})}),_.push(t),g.appendChild(t)}f.appendChild(g);let v=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,v=document.createElement(`textarea`),v.className=`persona-feedback-comment`,v.placeholder=a,v.rows=3,v.setAttribute(`aria-label`,`Additional comments`),e.appendChild(v),f.appendChild(e)}let y=document.createElement(`div`);y.className=`persona-feedback-actions`;let b=document.createElement(`button`);b.type=`button`,b.className=`persona-feedback-btn persona-feedback-btn-skip`,b.textContent=s,b.addEventListener(`click`,()=>{n?.(),u.remove()});let x=document.createElement(`button`);return x.type=`button`,x.className=`persona-feedback-btn persona-feedback-btn-submit`,x.textContent=o,x.addEventListener(`click`,async()=>{if(d===null)g.classList.add(`persona-feedback-shake`),setTimeout(()=>g.classList.remove(`persona-feedback-shake`),500);else{x.disabled=!0,x.textContent=`Submitting...`;try{let e=v?.value.trim()||void 0;await t(d,e),u.remove()}catch(e){x.disabled=!1,x.textContent=o,console.error(`[CSAT Feedback] Failed to submit:`,e)}}}),y.appendChild(b),y.appendChild(x),f.appendChild(y),u.appendChild(f),u}function lu(e){let{onSubmit:t,onDismiss:n,title:r=`How likely are you to recommend us?`,subtitle:i=`On a scale of 0 to 10`,commentPlaceholder:a=`What could we do better? (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,lowLabel:l=`Not likely`,highLabel:u=`Very likely`}=e,d=document.createElement(`div`);d.className=`persona-feedback-container persona-feedback-nps`,d.setAttribute(`role`,`dialog`),d.setAttribute(`aria-label`,`Net Promoter Score feedback`);let f=null,p=document.createElement(`div`);p.className=`persona-feedback-content`;let m=document.createElement(`div`);m.className=`persona-feedback-header`;let h=document.createElement(`h3`);h.className=`persona-feedback-title`,h.textContent=r,m.appendChild(h);let g=document.createElement(`p`);g.className=`persona-feedback-subtitle`,g.textContent=i,m.appendChild(g),p.appendChild(m);let _=document.createElement(`div`);_.className=`persona-feedback-rating persona-feedback-rating-nps`,_.setAttribute(`role`,`radiogroup`),_.setAttribute(`aria-label`,`Likelihood rating from 0 to 10`);let v=document.createElement(`div`);v.className=`persona-feedback-labels`;let y=document.createElement(`span`);y.className=`persona-feedback-label-low`,y.textContent=l;let b=document.createElement(`span`);b.className=`persona-feedback-label-high`,b.textContent=u,v.appendChild(y),v.appendChild(b);let x=document.createElement(`div`);x.className=`persona-feedback-numbers`;let S=[];for(let e=0;e<=10;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-number-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add(`persona-feedback-detractor`):e<=8?t.classList.add(`persona-feedback-passive`):t.classList.add(`persona-feedback-promoter`),t.addEventListener(`click`,()=>{f=e,S.forEach((t,n)=>{t.classList.toggle(`selected`,n===e),t.setAttribute(`aria-checked`,n===e?`true`:`false`)})}),S.push(t),x.appendChild(t)}_.appendChild(v),_.appendChild(x),p.appendChild(_);let C=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,C=document.createElement(`textarea`),C.className=`persona-feedback-comment`,C.placeholder=a,C.rows=3,C.setAttribute(`aria-label`,`Additional comments`),e.appendChild(C),p.appendChild(e)}let w=document.createElement(`div`);w.className=`persona-feedback-actions`;let T=document.createElement(`button`);T.type=`button`,T.className=`persona-feedback-btn persona-feedback-btn-skip`,T.textContent=s,T.addEventListener(`click`,()=>{n?.(),d.remove()});let E=document.createElement(`button`);return E.type=`button`,E.className=`persona-feedback-btn persona-feedback-btn-submit`,E.textContent=o,E.addEventListener(`click`,async()=>{if(f===null)x.classList.add(`persona-feedback-shake`),setTimeout(()=>x.classList.remove(`persona-feedback-shake`),500);else{E.disabled=!0,E.textContent=`Submitting...`;try{let e=C?.value.trim()||void 0;await t(f,e),d.remove()}catch(e){E.disabled=!1,E.textContent=o,console.error(`[NPS Feedback] Failed to submit:`,e)}}}),w.appendChild(T),w.appendChild(E),p.appendChild(w),d.appendChild(p),d}const uu=`persona-chat-history`,du=`data-persona-composer-reason`,fu=`data-persona-composer-notice`,pu={"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 mu(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let e of n){if(e.kind!==`file`||!e.type.startsWith(`image/`))continue;let n=e.getAsFile();if(!n)continue;if(n.name){t.push(n);continue}let r=pu[n.type]??`png`;t.push(new File([n],`clipboard-image-${Date.now()}.${r}`,{type:n.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith(`image/`)&&t.push(n);return t}function hu(e){if(!e)return!1;let t=e.types;return t?typeof t.contains==`function`?t.contains(`Files`):Array.from(t).includes(`Files`):!1}function gu(e){return e?e===!0?{storage:`session`,keyPrefix:`persona-`,persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??`session`,keyPrefix:e.keyPrefix??`persona-`,persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function _u(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const vu=e=>!e||typeof e!=`object`?{}:{...e},yu=e=>e.map(e=>({...e,streaming:!1})),bu=(e,t,n)=>{let r=e?.markdown?De(e.markdown):null,i=xe(e?.sanitize);e?.postprocessMessage&&i&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,o=a=>{let o=a.text??``,s=a.message.rawContent??null;if(t){let e=t.process({text:o,raw:s??o,message:a.message,streaming:a.streaming});e!==null&&(o=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&n&&n())}let c=ye()!==null,l;if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:o,raw:s??a.text??``});l=i?i(t):t}else if(r){let e=a.streaming?Tn(o):o,t=r(e);l=i&&c?i(t):t}else l=ve(o);return l};return e=>{try{return o(e)}catch(t){return a||(a=!0,console.error(`[Persona] markdown rendering failed; falling back to plain text:`,t)),ve(e.text??``)}}};function xu(e){let t=j(`div`,`persona-attachment-drop-overlay`);e?.background&&t.style.setProperty(`--persona-drop-overlay-bg`,e.background),e?.backdropBlur!==void 0&&t.style.setProperty(`--persona-drop-overlay-blur`,e.backdropBlur),e?.border&&t.style.setProperty(`--persona-drop-overlay-border`,e.border),e?.borderRadius&&t.style.setProperty(`--persona-drop-overlay-radius`,e.borderRadius),e?.inset&&t.style.setProperty(`--persona-drop-overlay-inset`,e.inset),e?.labelSize&&t.style.setProperty(`--persona-drop-overlay-label-size`,e.labelSize),e?.labelColor&&t.style.setProperty(`--persona-drop-overlay-label-color`,e.labelColor);let n=e?.iconName??`upload`,r=e?.iconSize??`48px`,i=e?.iconColor??`rgba(59, 130, 246, 0.6)`,a=e?.iconStrokeWidth??.5,o=M(n,r,i,a);if(o&&t.appendChild(o),e?.label){let n=j(`span`,`persona-drop-overlay-label`);n.textContent=e.label,t.appendChild(n)}return t}const Su=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t?{...t,...r}:r}return n},Cu=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Su(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),wu=(t,a,o)=>{if(t==null)throw 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 c=l(a),u=/* @__PURE__ */ new Set,d=/* @__PURE__ */ new Set,f=yn((e,t)=>{vs.delete(e);let n=Array.from(B.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?mc(e,n,u,c):ic(e,n,d))}),p=/* @__PURE__ */ new Map,m=()=>{le({delayMs:c.tooltip?.delayMs??200,skipDelayMs:c.tooltip?.skipDelayMs??300})};m();let h=c.features;c=pl(c);let g=El.getForInstance(c.plugins),x=ft(t),S=[],C=!1,D=nc(()=>c),O=null,k=null,ee=null,re=!1,oe=null,fe=e=>{O=e,e.initApprovalUi({webMcpToolTitle:Oe});let t=e.createBuiltInApprovalPlugin(p);k=t.plugin,ee=t.teardown},pe=()=>{if(O)return O;let e=xc();return e?(fe(e),e):(bc().then(e=>{re||O||(fe(e),oe?.())}).catch(()=>{}),null)},A=!1,me=!1,he=null,_e=(e,t,n,r)=>{if(!e.querySelector(`[data-tv-form]`))return;let i=Tl();i?i.enhanceWithForms(e,t,n,r):wl().then(()=>{A||me||!he||(me=!0,he())}).catch(()=>{})};c.components&&Ee.registerAll(c.components);let be=jl(),xe=c.persistState===!1?null:c.storageAdapter??Hl(),Ce=!!c.clientToken&&typeof c.reconnectStream!=`function`,Te={},De=null,ke,Ae=new Promise(e=>{ke=e}),je=()=>{},Me=new Promise(e=>{je=e}),Pe,Fe=!1,Ie=e=>{if(c.onStateLoaded)try{let t=c.onStateLoaded(e);if(t&&typeof t==`object`&&`state`in t){let{state:e,open:n}=t;return n&&(Fe=!0),e}return t}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}return e};if(xe?.load)try{let e=xe.load();if(e&&typeof e.then==`function`)De=e.then(e=>Ie(e??{messages:[],metadata:{}}));else{let t=Ie(e??{messages:[],metadata:{}});t.metadata&&(Te=vu(t.metadata)),t.messages?.length&&(c={...c,initialMessages:t.messages}),t.artifacts?.length&&(c={...c,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),Pe=t.draft}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to load stored state:`,e)}else if(c.onStateLoaded)try{let e=Ie({messages:[],metadata:{}});e.messages?.length&&(c={...c,initialMessages:e.messages})}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}De||ke();let Le=()=>Te,Re=e=>{Te=e({...Te})??{},kc()},ze=c.actionParsers&&c.actionParsers.length?c.actionParsers:[Pl],Be=c.actionHandlers&&c.actionHandlers.length?c.actionHandlers:[Il.message,Il.messageAndClick],Ve=Rl({parsers:ze,handlers:Be,getSessionMetadata:Le,updateSessionMetadata:Re,emit:be.emit,documentRef:typeof document<`u`?document:null});Ve.syncFromMetadata();let He=c.launcher?.enabled??!0,We=c.launcher?.autoExpand??!1,Ge=c.autoFocusInput??!1,$e=We,tt=He,nt=c.layout?.header?.layout,rt=!1,N=()=>mo(c),at=()=>He||N(),P=N()?!1:!He||We,ot=!1,st=null,ct=()=>{ot=!0,st&&clearTimeout(st),st=setTimeout(()=>{ot&&=(typeof console<`u`&&console.warn(`[AgentWidget] Resubmit requested but no injection occurred within 10s`),!1)},1e4)},ut=bu(c,Ve,ct),dt=c.features?.showReasoning??!0,pt=c.features?.showToolCalls??!0,mt=c.features?.showEventStreamToggle??!1,ht=c.features?.scrollToBottom??{},_t=c.features?.scrollBehavior??{},yt=()=>(typeof c.persistState==`object`?c.persistState?.keyPrefix:void 0)??`persona-`,xt=`${yt()}event-stream`,Ct=null,Gt=c.features?.eventStream?.maxEvents??2e3,qt=null,Jt=null,Yt=null,Xt=!1,Qt=null,$t=!1,en=null,tn=0,nn=(e,t)=>{qt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},rn=(e,t)=>{Jt?.processEvent(e,t),qt?nn(e,t):Yt&&(Yt.length>=Gt&&Yt.shift(),Yt.push({type:e,payload:t}))},an=()=>{!qt&&mt&&(Yt??=[],wc().then(e=>{if(Xt||qt||!mt)return;Ct=new e.EventStreamStore(xt),qt=new e.EventStreamBuffer(Gt,Ct),Jt??=new e.ThroughputTracker,Ct.open().then(()=>qt?.restore()).catch(e=>{c.debug&&console.warn(`[AgentWidget] IndexedDB not available for event stream:`,e)});let t=Yt??[];Yt=null;for(let e of t)Jt?.processEvent(e.type,e.payload),nn(e.type,e.payload)}).catch(()=>{}))};mt&&an();let on=!1,sn=null,cn=()=>{},ln=()=>{},un=()=>{},dn=()=>{},fn=()=>{},pn=()=>$t||on&&sn===`panel`,mn={onCopy:e=>{be.emit(`message:copy`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.id,`copy`).catch(e=>{c.debug&&console.error(`[AgentWidget] Failed to submit copy feedback:`,e)}),c.messageActions?.onCopy?.(e)},onFeedback:e=>{be.emit(`message:feedback`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.messageId,e.type).catch(e=>{c.debug&&console.error(`[AgentWidget] Failed to submit feedback:`,e)}),c.messageActions?.onFeedback?.(e)}};c.statusIndicator;let hn=(e,t=c.statusIndicator??{})=>e===`idle`?t.idleText??gt.idle:e===`connecting`?t.connectingText??gt.connecting:e===`connected`?t.connectedText??gt.connected:e===`error`?t.errorText??gt.error:e===`paused`?t.pausedText??gt.paused:e===`resuming`?t.resumingText??gt.resuming:gt[e];function vn(e,t,n,a){if(!N()&&(n.mode===`transient`||e.classList.contains(`persona-mb-2`))&&(r(e,kn,n),i(e,n,a)),!(e.hasAttribute(du)||e.hasAttribute(fu))){if(a===`idle`&&n.idleLink){e.textContent=``;let r=document.createElement(`a`);r.href=n.idleLink,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=t,r.style.color=`inherit`,r.style.textDecoration=`none`,e.appendChild(r)}else e.textContent=t}}let xn=Qs({config:c,showClose:at()}),{wrapper:F,panel:I,pillRoot:Cn}=xn.shell,L=xn.panelElements,{container:R,body:z,messagesWrapper:B,starterSuggestions:wn,transcriptSuggestions:Tn,suggestions:En,textarea:V,sendButton:H,composerForm:kn,statusText:U,welcomeHost:An,welcomeIconHolder:jn,greetingHost:Nn,introKicker:Pn,introTitle:Fn,introSubtitle:In,closeButton:W,iconHolder:Ln,headerTitle:Rn,headerSubtitle:zn,header:Bn,footer:G,actionsRow:Vn}=L,Hn=L.leftActions,Un=L.rightActions,Wn=L.sendButtonWrapper,Gn=L.setSendButtonMode,K=L.micButton,Kn=L.micButtonWrapper,Jn=L.attachmentButton,Yn=L.attachmentButtonWrapper,Xn=L.attachmentInput,Zn=L.attachmentPreviewsContainer;R.classList.add(`persona-relative`),z.classList.add(`persona-relative`);let Qn=()=>ht.label??``,$n=()=>ht.iconName??`arrow-down`,er=()=>ht.enabled!==!1,tr=()=>_t.mode??`anchor-top`,nr=()=>tr()===`follow`||tr()===`anchor-top`&&Ys,rr=()=>_t.anchorTopOffset??16,ir=()=>_t.restorePosition??`bottom`,sr=()=>_t.pauseOnInteraction===!0,cr=()=>_t.showActivityWhilePinned!==!1,lr=()=>_t.announce===!0,ur=()=>_t.scrollbar??`on-scroll`,dr=j(`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`);dr.type=`button`,dr.style.display=`none`,dr.setAttribute(`data-persona-scroll-to-bottom`,`true`);let fr=j(`span`,`persona-flex persona-items-center`),pr=j(`span`,``),mr=j(`span`,``);mr.setAttribute(`data-persona-scroll-to-bottom-count`,``),mr.style.display=`none`,dr.append(fr,pr,mr),R.appendChild(dr);let hr=j(`div`,`persona-stream-anchor-spacer`);hr.setAttribute(`aria-hidden`,`true`),hr.setAttribute(`data-persona-anchor-spacer`,``),hr.style.flexShrink=`0`,hr.style.pointerEvents=`none`,hr.style.height=`0px`,hr.style.display=`none`,z.appendChild(hr);let gr=j(`div`,`persona-sr-only`);gr.setAttribute(`aria-live`,`polite`),gr.setAttribute(`aria-atomic`,`true`),gr.setAttribute(`role`,`status`),gr.setAttribute(`data-persona-live-region`,``),Object.assign(gr.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`}),R.appendChild(gr);let _r=null,xr=null,Sr=e=>{lr()&&e&&(xr=e,_r===null&&(_r=setTimeout(()=>{_r=null,xr&&lr()&&(gr.textContent=xr),xr=null},400)))},Cr=()=>{let e=t.ownerDocument.defaultView??window;return(c.launcher?.mobileFullscreen??!0)&&e.innerWidth<=(c.launcher?.mobileBreakpoint??640)&&(He||po(c))||c.launcher?.fullHeight===!0&&!c.launcher.sidebarMode&&!po(c)},wr=()=>js(c,Cr()),Tr=`empty`,Er=0,Dr=()=>Er||parseFloat(t.style.getPropertyValue(`--persona-composer-lift`))||0,Ar=()=>{let e=G.style.display===`none`?0:G.offsetHeight;dr.style.bottom=`${e+Dr()+12}px`};Ar();let jr=()=>{mi||(G.style.marginBottom=Er>0?`${Er}px`:``)},Mr=()=>{let e=Ka(c,N()),n=wr();t.setAttribute(`data-persona-welcome-fullscreen`,String(Cr())),t.setAttribute(`data-persona-welcome-layout`,n.layout??`top`),t.setAttribute(`data-persona-welcome-layout-explicit`,c.welcome?.layout??``),t.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`);let r=G.style.display===`none`?0:G.offsetHeight,i=n.anchor===`center`&&Tr===`empty`?qa(n.anchorComposerTop)??qa(`44%`):null,a=i!==null&&n.layout===`centered`&&c.welcome?.anchor===void 0&&c.welcome?.anchorComposerTop===void 0,o=a?getComputedStyle(z):null,s=parseFloat(t.style.getPropertyValue(`--persona-composer-overlay-height`))||0,l=parseFloat(t.style.getPropertyValue(`--persona-composer-lift`))||0,u=Math.max(0,(parseFloat(o?.paddingBottom??``)||0)-(e===`overlay`?s+l:0)),d=a?z.getBoundingClientRect().top-R.getBoundingClientRect().top:0,f=!a||An.hidden?0:(An.querySelector(`[data-persona-welcome-plugin]`)??An).offsetHeight,p=i===null||N()?0:a?Math.max(0,Math.round((R.clientHeight-d-f-u-r)/2)):Ja({columnHeight:R.clientHeight,footerHeight:r,fraction:i});t.style.setProperty(`--persona-composer-overlay-height`,`${r}px`),t.style.setProperty(`--persona-composer-lift`,`${e===`overlay`?p:0}px`),Er=e===`block`?p:0,jr(),Ar()},Nr=()=>{let e=!!Qn();dr.setAttribute(`aria-label`,Qn()||`Jump to latest`),dr.title=Qn(),dr.setAttribute(`data-persona-scroll-to-bottom-has-label`,e?`true`:`false`),fr.innerHTML=``;let t=M($n(),`14px`,`currentColor`,2);t?(fr.appendChild(t),fr.style.display=``):fr.style.display=`none`,pr.textContent=Qn(),pr.style.display=e?``:`none`};Nr();let q=null,Pr=null,J=Yr();J.subscribe(e=>{try{R.dispatchEvent(new CustomEvent(`persona:composer:state`,{detail:e,bubbles:!0,composed:!0}))}catch{}});let Fr=()=>{J.setText(V?.value??``)},Ir=()=>{J.setMentionRefs(Pr?.getMentionRefs()??[])},Lr=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),Rr=e=>{let t=Object.freeze(e.map(Lr));J.setAttachments(t);try{c.attachments?.onChange?.(t)}catch(e){console.error(`[AgentWidget] attachments.onChange failed:`,e)}Au()};J.setSelectedModelId(c.composer?.selectedModelId);let zr=()=>c.composer?.modes??[],Vr=()=>Mi(zr(),c.composer?.modeGroups);{let e=Fi(c.composer?.defaultActiveModeIds??[],zr());e.length&&J.setActiveModeIds(e)}function Hr(e){if(J.getState().selectedModelId!==e){J.setSelectedModelId(e),Gr?.repaint();try{c.composer?.onModelChange?.(e)}catch(e){console.error(`[AgentWidget] composer.onModelChange failed:`,e)}}}function Ur(e){J.setActiveModeIds(e),Jr?.render(e,Vr()),Xr.forEach(e=>e.repaint()),ji?.resolve(),id(),ra()}function Wr(e){Ur(Pi(J.getState().activeModeIds,e,zr(),c.composer?.modeGroups))}let Gr=null,qr=null,Jr=null,Xr=/* @__PURE__ */ new Map,Zr=null;function $r(e){J.setQuote(e),Zr?.render(J.getState().quote),ra(),Lc()}let ei=!1;function ti(){let e=c.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?c.clientToken?`interrupt`:(!ei&&c.debug===!0&&(ei=!0,typeof console<`u`&&console.warn(`[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".`)),`block`):e}let ni=null;function ri(e){J.setPendingSubmission(e),ni?.render(J.getState().pendingSubmission),ra()}let ii=e=>{let t=Xr.get(e);if(t)return t;let n=Ri({groupId:e,getGroup:()=>c.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>zr().filter(t=>t.groupId===e),getActiveIds:()=>J.getState().activeModeIds,onSelect:e=>Wr(e)});return Xr.set(e,n),n},oi=()=>{let e=[],t=J.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(zr().forEach((r,i)=>{if(Ai(r.groupId,c.composer?.modeGroups)){let t=r.groupId;if(n.has(t))return;n.add(t);let a=ii(t);a.action.order=Oi(i),a.action.label=c.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(a.action)}else e.push({id:Di(r.id),kind:`button`,placement:`start`,order:Oi(i),presentation:r.presentation??`auto`,label:r.label,shortLabel:r.shortLabel,iconName:r.iconName,pressed:t.includes(r.id),onSelect:()=>Wr(r.id)})}),c.composer?.models?.length&&!g.some(e=>e.renderComposer)){let t=c.composer?.modelPicker?.presentation??`native`;(!Gr||qr!==t)&&(qr=t,Gr=Ti({getModels:()=>c.composer?.models??[],getSelectedModelId:()=>J.getState().selectedModelId,onSelect:e=>Hr(e),presentation:t,getSuffix:()=>c.composer?.modelPicker?.suffix})),e.push(Gr.action)}return e},si=null,ci=g.find(e=>e.renderHeader);if(ci?.renderHeader){let e=ci.renderHeader({config:c,defaultRenderer:()=>{let e=No({config:c,showClose:at()});return Po(R,e,c),e.header},onClose:()=>wu(!1,`user`)});if(e){let t=Bn;t&&(t.replaceWith(e),Bn=e,xn.header.element=e)}}let li=()=>{Qt&&(z.style.display=`none`,G.parentNode?.insertBefore(Qt.element,G),Qt.update())},ui=()=>{if(!qt){an();return}if($t=!0,Qt?li():wc().then(e=>{!Qt&&$t&&qt&&(Qt=e.createEventStreamView({buffer:qt,getFullHistory:()=>qt.getAllFromStore(),onClose:()=>di(),config:c,plugins:g,getThroughput:()=>Jt?.getMetric()??{status:`idle`},renderIconByName:M}),li())}).catch(()=>{di()}),fi){fi.style.boxShadow=`inset 0 0 0 1.5px ${Ao.actionIconColor}`;let e=c.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&fi.classList.add(e))}let e=()=>{if(!$t)return;let t=Date.now();t-tn>=200&&(Qt?.update(),tn=t),en=requestAnimationFrame(e)};tn=0,en=requestAnimationFrame(e),tl(),be.emit(`eventStream:opened`,{timestamp:Date.now()})},di=()=>{if($t){if($t=!1,Qt&&Qt.element.remove(),z.style.display=``,fi){fi.style.boxShadow=``;let e=c.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&fi.classList.remove(e))}en!==null&&(cancelAnimationFrame(en),en=null),tl(),be.emit(`eventStream:closed`,{timestamp:Date.now()})}},fi=null;if(mt){let t=c.features?.eventStream?.classNames,n=`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`+(t?.toggleButton?` `+t.toggleButton:``);fi=j(`button`,n),fi.style.width=`28px`,fi.style.height=`28px`,fi.style.color=Ao.actionIconColor,fi.type=`button`,fi.setAttribute(`aria-label`,`Event Stream`),fi.title=`Event Stream`;let r=e(Wt,`18px`,`currentColor`,1.5);r&&fi.appendChild(r);let i=L.clearChatButtonWrapper,a=L.closeButtonWrapper,o=i||a;o&&o.parentNode===Bn?Bn.insertBefore(fi,o):Bn.appendChild(fi),fi.addEventListener(`click`,()=>{$t?di():ui()})}let pi=e=>{let t=c.attachments;if(!t?.enabled)return;let n=e.querySelector(`[data-persona-composer-attachment-previews]`)??e.querySelector(`.persona-attachment-previews`);if(!n){n=j(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let t=e.querySelector(`[data-persona-composer-form]`);t?.parentNode?t.parentNode.insertBefore(n,t):e.insertBefore(n,e.firstChild)}if(!(e.querySelector(`[data-persona-composer-attachment-input]`)??e.querySelector(`input[type="file"]`))){let n=j(`input`);n.type=`file`,n.setAttribute(`data-persona-composer-attachment-input`,``),n.accept=(t.allowedTypes??lt).join(`,`),n.multiple=(t.maxFiles??4)>1,n.style.display=`none`,n.setAttribute(`aria-label`,t.buttonTooltipText??`Attach files`),e.appendChild(n)}},mi=!1,hi=e=>{let t=g.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let n=c.composer,r=C?Q.isStreaming():!1;return t.renderComposer({config:c,defaultRenderer:e,requestRender:()=>Wp(),storage:D(t.id),onSubmit:e=>{Q&&!Q.isStreaming()&&wf(e.trim(),{consumeDraft:!1})},streaming:r,disabled:r,openAttachmentPicker:()=>{Eu()||Xn?.click()},models:n?.models,selectedModelId:J.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>Hr(e),onVoiceToggle:c.voiceRecognition?.enabled===!0?()=>{si?.()}:void 0})},gi=hi(()=>zo({config:c}).footer);gi&&(xn.replaceComposer(gi),G=xn.composer.footer,mi=!0);let Y=null,_i=e=>{kn=e.form,V=e.input,Wn=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(H=e.sendButton),e.micButton&&(K=e.micButton,Kn=e.micButton.parentElement),e.found.status&&(U=e.found.status),e.found.suggestions&&(En=e.found.suggestions),e.attachmentButton&&(Jn=e.attachmentButton,Yn=e.attachmentButton.parentElement),Xn=e.attachmentInput??null,Zn=e.attachmentPreviews??null,e.found.actionsRow&&(Vn=e.found.actionsRow),Hn=e.found.actionsStart,Un=e.found.actionsEnd};function vi(){let e=V;if(!e)return;let t=c.composer?.inputAttributes,n=!t?.ariaLabel&&!(e instanceof HTMLTextAreaElement)?e.getAttribute(`aria-label`):null;w(e,t),n&&e.setAttribute(`aria-label`,n),T(e,{submitKey:c.composer?.submitKey,insertNewlineOnTouchEnter:c.composer?.insertNewlineOnTouchEnter,coarsePointer:ce(e)}),v(e,ue(c.composer?.maxLines,N()?5:3))}let yi=e=>{Y=Qr(e,{debug:c.debug===!0}),Y&&_i(Y),vi()};pi(G),yi(G),Fr();let bi=Ga(c,N());bi&&(B.style.maxWidth=bi,B.style.marginLeft=`auto`,B.style.marginRight=`auto`,B.style.width=`100%`,Nn.style.maxWidth=bi,Nn.style.marginLeft=`auto`,Nn.style.marginRight=`auto`,Nn.style.width=`100%`,wn.style.maxWidth=bi,Tn.style.maxWidth=bi,Tn.style.marginLeft=`auto`,Tn.style.marginRight=`auto`,Tn.style.width=`100%`);let xi=()=>{let e=Ga(c,N());if(e&&!N())for(let t of[kn,En,Zn,U])t&&(t.style.maxWidth=e,t.style.marginLeft=`auto`,t.style.marginRight=`auto`,t.style.width=`100%`)};xi();let Ci=()=>{c.attachments?.enabled&&Xn&&Zn&&(q?q.remountPreviews(Zn):(q=Kr.fromConfig(c.attachments,Rr),q.setPreviewsContainer(Zn)),Y?.addListener(Xn,`change`,e=>{let t=e.target;q?.handleFileSelect(t.files),t.value=``}),R.querySelector(`.persona-attachment-drop-overlay`)||R.appendChild(xu(c.attachments.dropOverlay)))};Ci();let wi=()=>Pr?.prefetch(),ki=()=>{if(!c.contextMentions?.enabled||!V)return;let e=or();if(!e){let e=V;ar().then(()=>{!Pr&&V===e&&e.isConnected&&(ki(),ji?.resolve())},()=>{});return}let t=Y?.header??null,n=t?bt(t):void 0;if(Pr=e.createContextMentionOrchestrator({deps:{loadContextMentions:E,loadContextMentionsInline:ie,renderLucideIcon:M,createMentionButton:te},config:c,textarea:V,anchor:kn??V,getMessages:()=>Q.getMessages(),liveRegionHost:R,chipRow:n}),Pr&&!n){let e=V;e.parentElement?.insertBefore(Pr.contextRow,e)}};ki();let ji=null,Ni={getState:()=>J.getState(),getValue:()=>V?.value??``,setValue:e=>{V&&(V.value=e,V.dispatchEvent(new Event(`input`,{bubbles:!0})),Fr())},submit:()=>{wt(Y?.form??null)},openAttachmentPicker:()=>{Eu()||Xn?.click()},toggleVoice:()=>{si?.()},requestRender:()=>ji?.resolve()},Xi=()=>{let e=[];return(Pr?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:ai.mention+n,element:t,managed:!0})}),Yn&&e.push({id:`core:attachment`,placement:`start`,order:ai.attachment,element:Yn}),Kn&&e.push({id:`core:mic`,placement:`end`,order:ai.mic,element:Kn}),Wn&&e.push({id:`core:send`,placement:`end`,order:ai.send,element:Wn}),e},Zi=()=>{ji?.destroy(),ji=Si({getBindings:()=>Y,collect:()=>({builtIns:Xi(),configActions:[...oi(),...c.composer?.actions??[]],plugins:g,contributionContext:{config:c,getState:()=>J.getState(),requestRender:()=>ji?.resolve()},debug:c.debug===!0}),actionContext:Ni,getState:()=>J.getState(),getOverflow:()=>c.composer?.actionOverflow,reportError:(e,t)=>{typeof console<`u`&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),ji.resolve()};Zi();let $i=()=>{if(Jr?.destroy(),Jr=null,!Vr().length)return;let e=Y?.header;e&&(Jr=Ei({row:bt(e),onRemove:e=>Wr(e),initialIds:J.getState().activeModeIds}),Jr.render(J.getState().activeModeIds,Vr()))};$i();let ea=()=>{Zr?.destroy(),Zr=null,ni?.destroy(),ni=null;let e=Y?.header;e&&(Zr=zi({onDismiss:()=>$r(void 0)}),e.appendChild(Zr.element),Zr.render(J.getState().quote),ti()===`defer-one`&&(ni=Bi({onEdit:()=>pf(),onRemove:()=>ri(void 0)}),e.appendChild(ni.element),ni.render(J.getState().pendingSubmission)))};ea();let ta=Ki(),na=()=>{let e=Y?.header?.querySelector(St);if(e)return e.childElementCount>0;let t=J.getState();return t.mentionRefs.length>0||Fi(t.activeModeIds,Vr()).length>0};function ra(){let e=J.getState(),t=ta.observe(qi(V),e.text);G.toggleAttribute(`data-persona-composer-compact`,Gi({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:na(),hasQuote:e.quote!==void 0,hasPendingSubmission:e.pendingSubmission!==void 0}))}function ia(){c.composer?.layout===`single-row`&&!N()?G.setAttribute(`data-persona-composer-layout`,`single-row`):G.removeAttribute(`data-persona-composer-layout`)}ia(),J.subscribe(()=>{ji?.sync(),Au(),ju(),ra(),Lc()}),ju();let aa=!1,oa=e=>{if(aa||c.debug!==!0)return;let t=[`messages`,`composer`].filter(t=>e[t]);t.length&&(aa=!0,console.warn(`[persona] layout.slots.${t.join(` and layout.slots.`)} ${t.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 e=c.layout?.slots??{};oa(e);let t=e=>{switch(e){case`body-top`:return z.querySelector(`[data-persona-intro-card]`);case`messages`:return B;case`footer-top`:return En;case`composer`:return kn;case`footer-bottom`:return U;default:return null}},n=(e,t)=>{switch(e){case`header-left`:case`header-center`:case`header-right`:if(e===`header-left`)Bn.insertBefore(t,Bn.firstChild);else if(e===`header-right`)Bn.appendChild(t);else{let e=Bn.querySelector(`.persona-flex-col`);e?e.parentNode?.insertBefore(t,e.nextSibling):Bn.appendChild(t)}break;case`body-top`:{let e=z.querySelector(`[data-persona-intro-card]`);e?e.replaceWith(t):z.insertBefore(t,z.firstChild);break}case`body-bottom`:z.appendChild(t);break;case`footer-top`:En.replaceWith(t);break;case`footer-bottom`:U.replaceWith(t)}};for(let[r,i]of Object.entries(e))if(i)try{let e=i({config:c,defaultContent:()=>t(r)});e&&n(r,e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Error rendering slot "${r}":`,e)}})(),B.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`button[data-persona-copy-tool-detail]`);n&&(e.preventDefault(),e.stopPropagation(),uc(n))});let sa=e=>{let t=e.target.closest(`button[data-expand-header="true"]`);if(!t)return;let n=t.closest(`.persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;tc(),nl();let i=t.getAttribute(`data-bubble-type`);if(n.classList.contains(`persona-activity-row`)){f.manual(r);let e=n.parentElement?.closest(`[data-persona-tool-group]`);e?.dataset.messageId&&f.manual(e.dataset.messageId)}if(i===`reasoning`)d.has(r)?d.delete(r):d.add(r),ic(r,n,d);else if(i===`tool`)u.has(r)?u.delete(r):u.add(r),mc(r,n,u,c);else if(i===`approval`&&O){let e=((c.approval===!1?void 0:c.approval)?.detailsDisplay??`collapsed`)===`expanded`,t=p.get(r)??e;p.set(r,!t),O.updateApprovalDetailsUI(r,n,c,p)}vs.delete(r)};B.addEventListener(`pointerdown`,e=>{e.target.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),sa(e))}),B.addEventListener(`click`,e=>{e.detail===0&&e.target.closest(`.persona-activity-row`)&&sa(e)}),B.addEventListener(`keydown`,e=>{let t=e.target;(e.key===`Enter`||e.key===` `)&&t.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),sa(e))}),B.addEventListener(`copy`,e=>{let{clipboardData:t}=e;if(!t)return;let n=B.getRootNode(),r=typeof n.getSelection==`function`?n.getSelection():window.getSelection();if(!r||r.isCollapsed)return;let i=r.toString(),a=Xa(i);a&&a!==i&&(t.setData(`text/plain`,a),e.preventDefault())});let ca=/* @__PURE__ */ new Map,la=null,ua=`idle`,da={idle:{icon:`volume-2`,label:`Read aloud`},loading:{icon:`loader-circle`,label:`Loading…`},playing:{icon:`pause`,label:`Pause`},paused:{icon:`play`,label:`Resume`}},fa=(e,t)=>{let{icon:n,label:r}=da[t];e.setAttribute(`aria-label`,r),e.title=r,e.setAttribute(`aria-pressed`,t===`idle`?`false`:`true`),e.classList.toggle(`persona-message-action-active`,t!==`idle`),e.classList.toggle(`persona-message-action-loading`,t===`loading`);let i=M(n,14,`currentColor`,2);i&&(e.innerHTML=``,e.appendChild(i))},pa=()=>{B.querySelectorAll(`[data-action="read-aloud"]`).forEach(e=>{let t=e.closest(`[data-actions-for]`)?.getAttribute(`data-actions-for`)??null;fa(e,t&&t===la?ua:`idle`)})};B.addEventListener(`click`,t=>{let n=t.target.closest(`.persona-message-action-btn[data-action]`);if(!n)return;t.preventDefault(),t.stopPropagation();let r=n.closest(`[data-actions-for]`);if(!r)return;let i=r.getAttribute(`data-actions-for`);if(!i)return;let a=n.getAttribute(`data-action`);if(a===`copy`){let t=Q.getMessages().find(e=>e.id===i);if(t&&mn.onCopy){let r=t.content||``;navigator.clipboard.writeText(r).then(()=>{n.classList.add(`persona-message-action-success`);let t=e(Kt,14,`currentColor`,2);t&&(n.innerHTML=``,n.appendChild(t)),setTimeout(()=>{n.classList.remove(`persona-message-action-success`);let t=e(Zt,14,`currentColor`,2);t&&(n.innerHTML=``,n.appendChild(t))},2e3)}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to copy message:`,e)}),mn.onCopy(t)}}else if(a===`read-aloud`)Q.toggleReadAloud(i);else if(a===`upvote`||a===`downvote`){let e=(ca.get(i)??null)===a,t=a===`upvote`?`thumbs-up`:`thumbs-down`;if(e){ca.delete(i),n.classList.remove(`persona-message-action-active`);let e=M(t,14,`currentColor`,2);e&&(n.innerHTML=``,n.appendChild(e))}else{let e=a===`upvote`?`downvote`:`upvote`,o=r.querySelector(`[data-action="${e}"]`);if(o){o.classList.remove(`persona-message-action-active`);let t=M(e===`upvote`?`thumbs-up`:`thumbs-down`,14,`currentColor`,2);t&&(o.innerHTML=``,o.appendChild(t))}ca.set(i,a),n.classList.add(`persona-message-action-active`);let s=M(t,14,`currentColor`,2);s&&(s.setAttribute(`fill`,`currentColor`),n.innerHTML=``,n.appendChild(s)),n.classList.remove(`persona-message-action-pop`),n.offsetWidth,n.classList.add(`persona-message-action-pop`);let c=Q.getMessages().find(e=>e.id===i);c&&mn.onFeedback&&mn.onFeedback({type:a,messageId:c.id,message:c})}}else if(a===`regenerate`)ma?.regenerate(i);else if(a===`edit`)ma?.edit(i);else if(a===`quote`)ma?.quote(i);else if(a?.startsWith(`custom:`)){let e=a.slice(7),t=c.messageActions?.custom?.find(t=>t.id===e),n=Q.getMessages().find(e=>e.id===i);if(!t||!n)return;try{t.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let ma=null;B.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-approval-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`.persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;let i=t.getAttribute(`data-approval-action`);if(!i)return;let a=i===`approve`?`approved`:`denied`,o=Q.getMessages().find(e=>e.id===r);if(!o?.approval)return;let s=n.querySelector(`[data-approval-buttons]`);s&&s.querySelectorAll(`button`).forEach(e=>{e.disabled=!0,e.style.opacity=`0.5`,e.style.cursor=`not-allowed`}),o.approval.toolType===`webmcp`?Q.resolveWebMcpApproval(r,a):Q.resolveApproval(o.approval,a)});let X=null,ga=!1,_a=null,va=()=>{},ya=`none`,ba=null,xa={artifacts:[],selectedId:null},Sa=!1,Ca=!1,wa=!1,Ta=!1,Ea=()=>Ta||xa.artifacts.some(e=>et(c.features?.artifacts,e)===`panel`),Da=()=>xa.artifacts.length>0&&!Sa&&Ea(),Oa={current:null},ka=(e,t)=>{let n=Q.getArtifactById(t),r=n?.markdown,i=n?.title||`artifact`,a=n?.file,o=n?.artifactType??`markdown`;if(!r){let t=(e.closest(`[data-open-artifact], [data-artifact-inline]`)?.closest(`[data-message-id]`))?.getAttribute(`data-message-id`);if(t){let e=Q.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);r=t?.props?.markdown,i=t?.props?.title||i,t?.props?.file&&typeof t.props.file==`object`&&(a=t.props.file),!n&&typeof t?.props?.artifactType==`string`&&(o=t.props.artifactType)}catch{}}}return{markdown:r,title:i,file:a,artifactType:o}};B.addEventListener(`click`,e=>{let t=e.target.closest(`[data-download-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-download-artifact`);if(!n||c.features?.artifacts?.onArtifactAction?.({type:`download`,artifactId:n})===!0)return;let{markdown:r,title:i,file:a}=ka(t,n);if(!r)return;let o=Pc();o&&o.triggerArtifactDownload(o.downloadInfoFor({title:i,markdown:r,file:a}))}),B.addEventListener(`click`,e=>{let t=e.target.closest(`[data-artifact-custom-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-artifact-custom-action`);if(!n)return;let r=t.closest(`[data-artifact-inline]`),i=r?null:t.closest(`[data-open-artifact]`),a=r?r.getAttribute(`data-artifact-inline`):i?.getAttribute(`data-open-artifact`)??null,o=(r?c.features?.artifacts?.inlineActions:c.features?.artifacts?.cardActions)?.find(e=>e.id===n);if(!o)return;let{markdown:s,title:l,file:u,artifactType:d}=ka(t,a??``),f={artifactId:a,title:l,artifactType:d,markdown:s,file:u};try{Promise.resolve(o.onClick(f)).catch(()=>{})}catch{}}),B.addEventListener(`click`,t=>{let n=t.target.closest(`[data-copy-artifact]`);if(!n)return;t.preventDefault(),t.stopPropagation();let r=n.getAttribute(`data-copy-artifact`);if(!r)return;let i=Q.getArtifactById(r),a=Pc();if(!a)return;let o=``;if(i)o=a.artifactCopyText(i);else{let{markdown:e,file:t,artifactType:i}=ka(n,r);i===`markdown`&&(o=a.artifactCopyText({id:r,artifactType:`markdown`,status:`complete`,markdown:e??``,...t?{file:t}:{}}))}o&&navigator.clipboard.writeText(o).then(()=>{let t=e(Kt,16,`currentColor`,2);t&&(n.replaceChildren(t),setTimeout(()=>{let t=e(Zt,16,`currentColor`,2);t&&n.replaceChildren(t)},1500))}).catch(()=>{})}),B.addEventListener(`click`,e=>{let t=e.target.closest(`[data-expand-artifact-inline]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-expand-artifact-inline`);n&&c.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:n})!==!0&&(Sa=!1,Ta=!0,Ca=!0,wa=!0,Q.selectArtifact(n),To())}),B.addEventListener(`click`,e=>{let t=e.target;if(t.closest(`[data-download-artifact]`)||t.closest(`[data-artifact-custom-action]`))return;let n=t.closest(`[data-open-artifact]`);if(!n)return;let r=n.getAttribute(`data-open-artifact`);r&&c.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:r})!==!0&&(e.preventDefault(),e.stopPropagation(),Sa=!1,Ta=!0,Q.selectArtifact(r),To())}),B.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target;(t.hasAttribute(`data-open-artifact`)||t.hasAttribute(`data-expand-artifact-inline`))&&(e.preventDefault(),t.click())});let Aa=L.composerOverlay,ja=e=>{ar().catch(()=>{}),qe(e,c,Aa)},Ma=null,Na={mount:t,overlay:Aa,sessionRef:Oa,config:()=>c},Pa=!1,Fa=e=>t=>{let n=t.target,r=n?.closest?.(`[data-persona-ask-sheet-for]`);if(!r||!(e===`click`?n?.closest(`[data-ask-user-action]`):t.key===`Enter`&&n?.matches?.(`[data-ask-free-text-input="true"]`)))return;let i=n=>{Ma??=n.createAskUserSheetHandlers(Na),Ma[e](t)},a=or();a?i(a):Pa||(Pa=!0,ar().then(e=>{Pa=!1,r.isConnected&&i(e)},()=>{Pa=!1}))};Aa.addEventListener(`click`,Fa(`click`)),Aa.addEventListener(`keydown`,Fa(`keydown`));let Ia=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)return;let n=Aa.querySelector(`[data-persona-ask-sheet-for]`);if(!n||n.getAttribute(`data-ask-layout`)!==`rows`||n.getAttribute(`data-multi-select`)===`true`)return;let r=Number(e.key),i=n.querySelectorAll(`[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]`)[r-1];i&&(e.preventDefault(),i.click())};document.addEventListener(`keydown`,Ia);let La=null,za=null,Ba=null,Ha=null,io=()=>{},ao=!1,co=``,lo=``;function fo(){Ha?.(),Ha=null}let go=()=>{let e=Nd?.railShell?Nd.railHost:null,t=e?.isConnected?e:null,n=t?t.getBoundingClientRect().width:0;return n<=0?200:n+360},vo=()=>{if(!La||!za)return;let e=t.classList.contains(`persona-artifact-welded-split`),n=t.ownerDocument.defaultView??window,r=n.innerWidth<=640;if(!e||t.classList.contains(`persona-artifact-narrow-host`)||r){za.style.removeProperty(`position`),za.style.removeProperty(`left`),za.style.removeProperty(`top`),za.style.removeProperty(`bottom`),za.style.removeProperty(`width`),za.style.removeProperty(`z-index`);return}let i=La.firstElementChild;if(!i||i===za)return;za.style.position=`absolute`,za.style.top=`0`,za.style.bottom=`0`,za.style.width=`10px`,za.style.zIndex=`5`;let a=vl(La,n),o=i.offsetWidth+a/2-5;za.style.left=`${Math.max(0,o)}px`},yo=()=>{},bo=()=>{let e=t.ownerDocument.defaultView??window,n=c.launcher?.mobileFullscreen??!0,r=c.launcher?.mobileBreakpoint??640;return!n||e.innerWidth>r?!1:He||po(c)},wo=()=>!Ic(c)||!Da()||t.classList.contains(`persona-artifact-narrow-host`)||bo()||(t.ownerDocument.defaultView??window).innerWidth<641?`none`:Vc(c)?`detached`:`welded`,To=()=>{if(!X||!Ic(c))return;Hc(t,c),Uc(t,c),yo();let e=c.features?.artifacts?.layout?.narrowHostMaxWidth??520,n=I.getBoundingClientRect().width||0;t.classList.toggle(`persona-artifact-narrow-host`,n>0&&n<=e);let r=Da();X.setVisible(r),X.update(xa),Sa?(X.setMobileOpen(!1),X.element.classList.add(`persona-hidden`),X.backdrop?.classList.add(`persona-hidden`),Ca=!1,wa=!1):xa.artifacts.length>0&&Ea()?(X.element.classList.remove(`persona-hidden`),X.setMobileOpen(!0)):(X.setMobileOpen(!1),X.element.classList.add(`persona-hidden`),X.backdrop?.classList.add(`persona-hidden`),Ca=!1,wa=!1);let i=c.features?.artifacts?.layout?.showExpandToggle===!0;if(X.setExpandToggleVisible(i),X.setCopyButtonVisible(c.features?.artifacts?.layout?.showCopyButton===!0),X.setRefreshButtonVisible(typeof c.features?.artifacts?.layout?.onDocumentToolbarRefresh==`function`),X.setCustomActions(c.features?.artifacts?.toolbarActions??[]),X.setTabFade(c.features?.artifacts?.layout?.tabFade),X.setRenderTabBar(c.features?.artifacts?.renderTabBar),!i&&!wa&&(Ca=!1),Ca!==ao){let e=X.element;Ca?(co=e.style.width,lo=e.style.maxWidth,e.style.removeProperty(`width`),e.style.removeProperty(`max-width`)):(co&&(e.style.width=co),lo&&(e.style.maxWidth=lo),co=``,lo=``),ao=Ca}t.classList.toggle(`persona-artifact-expanded`,Ca),X.setExpanded(Ca);let a=wo();a!==ya&&(ya=a,va()),io()};if(Ic(c)){I.style.position=`relative`;let e=j(`div`,`persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0`),n=j(`div`,`persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root`);e.appendChild(R),La=n,n.appendChild(e),I.appendChild(n);let r=e=>{ga||X||(X=e.createArtifactPane(c,{onSelect:e=>Oa.current?.selectArtifact(e),onDismiss:()=>{Sa=!0,To()},onToggleExpand:()=>{let e=!Ca,t=xa.selectedId??xa.artifacts[xa.artifacts.length-1]?.id??null;c.features?.artifacts?.onArtifactAction?.({type:`expand`,artifactId:t,expanded:e})!==!0&&(Ca=e,e||(wa=!1),To())}}),X.element.classList.add(`persona-hidden`),n.appendChild(X.element),X.backdrop&&I.appendChild(X.backdrop),io(),To())},i=Pc();i?r(i):(Fc(()=>{let e=Pc();e&&r(e)}),Nc().catch(()=>{})),io=()=>{if(La&&X){if(c.features?.artifacts?.layout?.resizable!==!0)Ba?.(),Ba=null,fo(),za&&=(za.remove(),null),X.element.style.removeProperty(`width`),X.element.style.removeProperty(`maxWidth`);else{if(!za){let e=j(`div`,`persona-artifact-split-handle persona-shrink-0 persona-h-full`);e.setAttribute(`role`,`separator`),e.setAttribute(`aria-orientation`,`vertical`),e.setAttribute(`aria-label`,`Resize artifacts panel`),e.tabIndex=0;let n=t.ownerDocument,r=n.defaultView??window,i=i=>{if(!X||i.button!==0||t.classList.contains(`persona-artifact-narrow-host`)||t.classList.contains(`persona-artifact-expanded`)||r.innerWidth<=640)return;i.preventDefault(),fo();let a=i.clientX,o=X.element.getBoundingClientRect().width,s=c.features?.artifacts?.layout,l=n=>{let i=La.getBoundingClientRect().width,c=t.classList.contains(`persona-artifact-welded-split`),l=vl(La,r),u=c?0:e.getBoundingClientRect().width||6,d=yl(o-(n.clientX-a),i,l,u,s?.resizableMinWidth,s?.resizableMaxWidth,go());X.element.style.width=`${d}px`,X.element.style.maxWidth=`none`,vo()},u=()=>{n.removeEventListener(`pointermove`,l),n.removeEventListener(`pointerup`,u),n.removeEventListener(`pointercancel`,u),Ha=null;try{e.releasePointerCapture(i.pointerId)}catch{}};Ha=u,n.addEventListener(`pointermove`,l),n.addEventListener(`pointerup`,u),n.addEventListener(`pointercancel`,u);try{e.setPointerCapture(i.pointerId)}catch{}};e.addEventListener(`pointerdown`,i),za=e,La.insertBefore(e,X.element),Ba=()=>{e.removeEventListener(`pointerdown`,i)}}if(za){let e=Da();za.classList.toggle(`persona-hidden`,!e),vo()}}}},yo=()=>{if(!He||!X||(c.launcher?.sidebarMode??!1)||po(c)&&ho(c).reveal===`emerge`)return;let e=t.ownerDocument.defaultView??window,n=c.launcher?.mobileFullscreen??!0,r=c.launcher?.mobileBreakpoint??640;if(n&&e.innerWidth<=r||!Wc(c,He))return;let i=Fs(c).width,a=c.features?.artifacts?.layout?.expandedPanelWidth??`min(720px, calc(100vw - 24px))`;Da()?(I.style.width=a,I.style.maxWidth=a):(I.style.width=i,I.style.maxWidth=i)},typeof ResizeObserver<`u`&&(_a=new ResizeObserver(()=>{To()}),_a.observe(I))}else I.appendChild(R);N()&&Cn&&(L.peekBanner&&Cn.appendChild(L.peekBanner),Cn.appendChild(G)),t.appendChild(F),Cn&&t.appendChild(Cn);let Oo=()=>{let e=bo()||N()&&c.launcher?.composerBar?.expandedSize===`fullscreen`||c.launcher?.fullHeight===!0&&!c.launcher?.sidebarMode&&!po(c);if(B.style.gap=e?`var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))`:`var(--persona-components-message-gap, 12px)`,B.style.setProperty(`--persona-transcript-gap`,B.style.gap),N()){I.style.width=`100%`,I.style.maxWidth=`100%`;let e=c.launcher?.composerBar??{},t=F.dataset.state===`expanded`,n=e.expandedSize??`anchored`;if(!(t&&n!==`fullscreen`)){R.style.background=``,R.style.border=``,R.style.borderRadius=``,R.style.overflow=``,R.style.boxShadow=``;return}let r=c.theme?.components?.panel,i=Va(c),a=(e,t)=>e==null||e===``?t:ha(i,e)??e;R.style.background=`var(--persona-surface, #ffffff)`,R.style.border=a(r?.border,`1px solid var(--persona-border)`),R.style.borderRadius=a(r?.borderRadius,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`),R.style.boxShadow=a(r?.shadow,`var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))`),R.style.overflow=`hidden`;return}let n=po(c),r=c.launcher?.sidebarMode??!1,i=n||r||(c.launcher?.fullHeight??!1),a=c.launcher?.enabled===!1,o=c.launcher?.detachedPanel===!0,l=c.theme?.components?.panel,u=c.darkTheme?.components?.panel,d=Ra(c)===`dark`?_(l??{},u??{}):l,f=Va(c),p=(e,t)=>e==null||e===``?t:ha(f,e)??e,m=t.ownerDocument.defaultView??window,h=c.launcher?.mobileFullscreen??!0,g=c.launcher?.mobileBreakpoint??640,v=m.innerWidth<=g,y=h&&v&&He,b=n&&h&&v,x=c.launcher?.position??`bottom-left`,S=x===`bottom-left`||x===`top-left`,C=c.launcher?.zIndex??1e5,w=(e,t,n)=>`var(--persona-components-panel-modes-${e}-${t}, ${n})`,T=d?.modes?.floating,E=p(T?.border??d?.border,w(`floating`,`border`,`var(--persona-panel-border, 1px solid var(--persona-border))`)),D=p(T?.shadow??d?.shadow,w(`floating`,`shadow`,`var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))`)),O=p(T?.borderRadius??d?.borderRadius,w(`floating`,`borderRadius`,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`)),k=o&&!y&&!b,ee=y||b?`mobile`:k?`floating`:n?`docked`:r?`sidebar`:a?`inline`:`floating`,te=d?.modes?.[ee];k?t.setAttribute(`data-persona-panel-detached`,`true`):t.removeAttribute(`data-persona-panel-detached`);let ne=k?E:r||y?`none`:E,re=k?D:y?`none`:r?S?`2px 0 12px rgba(0, 0, 0, 0.08)`:`-2px 0 12px rgba(0, 0, 0, 0.08)`:a?`none`:D;n&&!y&&!k&&(re=`none`,ne=`none`);let ie=k?O:r||y?`0`:O,ae=p(te?.border??d?.border,w(ee,`border`,ne)),oe=p(te?.shadow??d?.shadow,w(ee,`shadow`,re)),se=p(te?.borderRadius??d?.borderRadius,w(ee,`borderRadius`,ie)),ce=wo(),le=ce===`detached`,ue=ce===`welded`;t.classList.toggle(`persona-artifact-detached-split`,le),t.classList.toggle(`persona-artifact-welded-split`,ue);let de=`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)))))`,fe=(c.features?.artifacts?.layout?.chatSurface===`flush`?`flush`:`card`)==`flush`&&Ic(c)&&Vc(c)&&a&&!n;t.classList.toggle(`persona-artifact-chat-flush`,fe);let pe=le||fe?`none`:oe,A=le?E:ue?`none`:ae,j=le?O:se;fe&&(A=`none`,j=`0`);let me=te?.borderRadius!=null&&te.borderRadius!==``||d?.borderRadius!=null&&d.borderRadius!==``,M=fe&&!me?`0`:se,he=z.scrollTop;t.style.cssText=``,F.style.cssText=``,I.style.cssText=``,R.style.cssText=``,z.style.cssText=``,mi||(G.style.cssText=``),$t&&(z.style.display=`none`),(i||a)&&(t.style.minWidth=`0`);let ge=()=>{he<=0||(z.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(z.scrollTop===he)return;let e=z.scrollHeight-z.clientHeight;e<=0||(z.scrollTop=Math.min(he,e))})};if(y){F.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`),F.style.cssText=`
|
|
28
|
+
`,t.addEventListener(`click`,()=>{d=e,_.forEach((t,n)=>{let r=n<e;t.classList.toggle(`selected`,r),t.setAttribute(`aria-checked`,n===e-1?`true`:`false`)})}),_.push(t),g.appendChild(t)}f.appendChild(g);let v=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,v=document.createElement(`textarea`),v.className=`persona-feedback-comment`,v.placeholder=a,v.rows=3,v.setAttribute(`aria-label`,`Additional comments`),e.appendChild(v),f.appendChild(e)}let y=document.createElement(`div`);y.className=`persona-feedback-actions`;let b=document.createElement(`button`);b.type=`button`,b.className=`persona-feedback-btn persona-feedback-btn-skip`,b.textContent=s,b.addEventListener(`click`,()=>{n?.(),u.remove()});let x=document.createElement(`button`);return x.type=`button`,x.className=`persona-feedback-btn persona-feedback-btn-submit`,x.textContent=o,x.addEventListener(`click`,async()=>{if(d===null)g.classList.add(`persona-feedback-shake`),setTimeout(()=>g.classList.remove(`persona-feedback-shake`),500);else{x.disabled=!0,x.textContent=`Submitting...`;try{let e=v?.value.trim()||void 0;await t(d,e),u.remove()}catch(e){x.disabled=!1,x.textContent=o,console.error(`[CSAT Feedback] Failed to submit:`,e)}}}),y.appendChild(b),y.appendChild(x),f.appendChild(y),u.appendChild(f),u}function vu(e){let{onSubmit:t,onDismiss:n,title:r=`How likely are you to recommend us?`,subtitle:i=`On a scale of 0 to 10`,commentPlaceholder:a=`What could we do better? (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,lowLabel:l=`Not likely`,highLabel:u=`Very likely`}=e,d=document.createElement(`div`);d.className=`persona-feedback-container persona-feedback-nps`,d.setAttribute(`role`,`dialog`),d.setAttribute(`aria-label`,`Net Promoter Score feedback`);let f=null,p=document.createElement(`div`);p.className=`persona-feedback-content`;let m=document.createElement(`div`);m.className=`persona-feedback-header`;let h=document.createElement(`h3`);h.className=`persona-feedback-title`,h.textContent=r,m.appendChild(h);let g=document.createElement(`p`);g.className=`persona-feedback-subtitle`,g.textContent=i,m.appendChild(g),p.appendChild(m);let _=document.createElement(`div`);_.className=`persona-feedback-rating persona-feedback-rating-nps`,_.setAttribute(`role`,`radiogroup`),_.setAttribute(`aria-label`,`Likelihood rating from 0 to 10`);let v=document.createElement(`div`);v.className=`persona-feedback-labels`;let y=document.createElement(`span`);y.className=`persona-feedback-label-low`,y.textContent=l;let b=document.createElement(`span`);b.className=`persona-feedback-label-high`,b.textContent=u,v.appendChild(y),v.appendChild(b);let x=document.createElement(`div`);x.className=`persona-feedback-numbers`;let S=[];for(let e=0;e<=10;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-number-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add(`persona-feedback-detractor`):e<=8?t.classList.add(`persona-feedback-passive`):t.classList.add(`persona-feedback-promoter`),t.addEventListener(`click`,()=>{f=e,S.forEach((t,n)=>{t.classList.toggle(`selected`,n===e),t.setAttribute(`aria-checked`,n===e?`true`:`false`)})}),S.push(t),x.appendChild(t)}_.appendChild(v),_.appendChild(x),p.appendChild(_);let C=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,C=document.createElement(`textarea`),C.className=`persona-feedback-comment`,C.placeholder=a,C.rows=3,C.setAttribute(`aria-label`,`Additional comments`),e.appendChild(C),p.appendChild(e)}let w=document.createElement(`div`);w.className=`persona-feedback-actions`;let T=document.createElement(`button`);T.type=`button`,T.className=`persona-feedback-btn persona-feedback-btn-skip`,T.textContent=s,T.addEventListener(`click`,()=>{n?.(),d.remove()});let E=document.createElement(`button`);return E.type=`button`,E.className=`persona-feedback-btn persona-feedback-btn-submit`,E.textContent=o,E.addEventListener(`click`,async()=>{if(f===null)x.classList.add(`persona-feedback-shake`),setTimeout(()=>x.classList.remove(`persona-feedback-shake`),500);else{E.disabled=!0,E.textContent=`Submitting...`;try{let e=C?.value.trim()||void 0;await t(f,e),d.remove()}catch(e){E.disabled=!1,E.textContent=o,console.error(`[NPS Feedback] Failed to submit:`,e)}}}),w.appendChild(T),w.appendChild(E),p.appendChild(w),d.appendChild(p),d}const yu=`persona-chat-history`,bu=`data-persona-composer-reason`,xu=`data-persona-composer-notice`,Su={"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 Cu(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let e of n){if(e.kind!==`file`||!e.type.startsWith(`image/`))continue;let n=e.getAsFile();if(!n)continue;if(n.name){t.push(n);continue}let r=Su[n.type]??`png`;t.push(new File([n],`clipboard-image-${Date.now()}.${r}`,{type:n.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith(`image/`)&&t.push(n);return t}function wu(e){if(!e)return!1;let t=e.types;return t?typeof t.contains==`function`?t.contains(`Files`):Array.from(t).includes(`Files`):!1}function Tu(e){return e?e===!0?{storage:`session`,keyPrefix:`persona-`,persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??`session`,keyPrefix:e.keyPrefix??`persona-`,persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function Eu(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const Du=e=>!e||typeof e!=`object`?{}:{...e},Ou=e=>e.filter(e=>!bt(e)).map(e=>({...e,streaming:!1})),ku=(e,t,n)=>{let r=e?.markdown?Ke(e.markdown):null,i=Be(e?.sanitize);e?.postprocessMessage&&i&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,o=a=>{let o=a.text??``,s=a.message.rawContent??null;if(t){let e=t.process({text:o,raw:s??o,message:a.message,streaming:a.streaming});e!==null&&(o=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&n&&n())}let c=Re()!==null,l;if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:o,raw:s??a.text??``});l=i?i(t):t}else if(r){let e=a.streaming?W(o):o,t=r(e);l=i&&c?i(t):t}else l=Le(o);return l};return e=>{try{return o(e)}catch(t){return a||(a=!0,console.error(`[Persona] markdown rendering failed; falling back to plain text:`,t)),Le(e.text??``)}}};function Au(e){let t=M(`div`,`persona-attachment-drop-overlay`);e?.background&&t.style.setProperty(`--persona-drop-overlay-bg`,e.background),e?.backdropBlur!==void 0&&t.style.setProperty(`--persona-drop-overlay-blur`,e.backdropBlur),e?.border&&t.style.setProperty(`--persona-drop-overlay-border`,e.border),e?.borderRadius&&t.style.setProperty(`--persona-drop-overlay-radius`,e.borderRadius),e?.inset&&t.style.setProperty(`--persona-drop-overlay-inset`,e.inset),e?.labelSize&&t.style.setProperty(`--persona-drop-overlay-label-size`,e.labelSize),e?.labelColor&&t.style.setProperty(`--persona-drop-overlay-label-color`,e.labelColor);let n=e?.iconName??`upload`,r=e?.iconSize??`48px`,i=e?.iconColor??`rgba(59, 130, 246, 0.6)`,a=e?.iconStrokeWidth??.5,o=N(n,r,i,a);if(o&&t.appendChild(o),e?.label){let n=M(`span`,`persona-drop-overlay-label`);n.textContent=e.label,t.appendChild(n)}return t}const ju=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t?{...t,...r}:r}return n},Mu=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:ju(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),Nu=(t,n,r)=>{if(t==null)throw 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 i=te(n),o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=xn((e,t)=>{gs.delete(e);let n=Array.from(V.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?Sc(e,n,o,i):dc(e,n,s))}),l=/* @__PURE__ */ new Map,u=()=>{Oe({delayMs:i.tooltip?.delayMs??200,skipDelayMs:i.tooltip?.skipDelayMs??300})};u();let d=i.features;i=xl(i);let f=Pl.getForInstance(i.plugins),p=gt(t),m=[],g=!1,_=uc(()=>i),y=null,x=null,T=null,E=!1,ee=null,ne=t=>{y=t,t.initApprovalUi({webMcpToolTitle:e});let n=t.createBuiltInApprovalPlugin(l);x=n.plugin,T=n.teardown},re=()=>{if(y)return y;let e=kc();return e?(ne(e),e):(Oc().then(e=>{E||y||(ne(e),ee?.())}).catch(()=>{}),null)},ie=!1,ae=!1,oe=null,se=(e,t,n,r)=>{if(!e.querySelector(`[data-tv-form]`))return;let i=Nl();i?i.enhanceWithForms(e,t,n,r):Ml().then(()=>{ie||ae||!oe||(ae=!0,oe())}).catch(()=>{})};i.components&&Ge.registerAll(i.components);let O=zl(),fe=i.persistState===!1?null:i.storageAdapter??Zl(Xl(typeof i.persistState==`object`?i.persistState.keyPrefix:void 0)),k=!!i.clientToken&&typeof i.reconnectStream!=`function`,pe={},_e=null,ve,ye=new Promise(e=>{ve=e}),A=()=>{},Se=new Promise(e=>{A=e}),Te,je=!1,Me=e=>{if(i.onStateLoaded)try{let t=i.onStateLoaded(e);if(t&&typeof t==`object`&&`state`in t){let{state:e,open:n}=t;return n&&(je=!0),e}return t}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}return e};if(fe?.load)try{let e=fe.load();if(e&&typeof e.then==`function`)_e=e.then(e=>Me(e??{messages:[],metadata:{}}));else{let t=Me(e??{messages:[],metadata:{}});t.metadata&&(pe=Du(t.metadata)),t.messages?.length&&(i={...i,initialMessages:t.messages}),t.artifacts?.length&&(i={...i,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),Te=t.draft}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to load stored state:`,e)}else if(i.onStateLoaded)try{let e=Me({messages:[],metadata:{}});e.messages?.length&&(i={...i,initialMessages:e.messages})}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}_e||ve();let j=()=>pe,Ne=e=>{pe=e({...pe})??{},Dc()},Pe=i.actionParsers&&i.actionParsers.length?i.actionParsers:[Hl],Ie=i.actionHandlers&&i.actionHandlers.length?i.actionHandlers:[Wl.message,Wl.messageAndClick],ze=Kl({parsers:Pe,handlers:Ie,getSessionMetadata:j,updateSessionMetadata:Ne,emit:O.emit,documentRef:typeof document<`u`?document:null});ze.syncFromMetadata();let Be=i.launcher?.enabled??!0,He=i.launcher?.autoExpand??!1,We=i.autoFocusInput??!1,Ke=He,qe=Be,Je=i.layout?.header?.layout,Ye=!1,P=()=>So(i),it=()=>Be||P(),F=P()?!1:!Be||He,at=!1,ot=null,ct=()=>{at=!0,ot&&clearTimeout(ot),ot=setTimeout(()=>{at&&=(typeof console<`u`&&console.warn(`[AgentWidget] Resubmit requested but no injection occurred within 10s`),!1)},1e4)},lt=ku(i,ze,ct),ut=i.features?.showReasoning??!0,dt=i.features?.showToolCalls??!0,ft=i.features?.showEventStreamToggle??!1,mt=i.features?.scrollToBottom??{},ht=i.features?.scrollBehavior??{},_t=()=>(typeof i.persistState==`object`?i.persistState?.keyPrefix:void 0)??`persona-`,vt=`${_t()}event-stream`,yt=null,bt=i.features?.eventStream?.maxEvents??2e3,St=null,wt=null,Et=null,Ot=!1,Xt=null,Qt=!1,$t=null,en=0,tn=(e,t)=>{St?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},rn=(e,t)=>{wt?.processEvent(e,t),St?tn(e,t):Et&&(Et.length>=bt&&Et.shift(),Et.push({type:e,payload:t}))},an=()=>{!St&&ft&&(Et??=[],Mc().then(e=>{if(Ot||St||!ft)return;yt=new e.EventStreamStore(vt),St=new e.EventStreamBuffer(bt,yt),wt??=new e.ThroughputTracker,yt.open().then(()=>St?.restore()).catch(e=>{i.debug&&console.warn(`[AgentWidget] IndexedDB not available for event stream:`,e)});let t=Et??[];Et=null;for(let e of t)wt?.processEvent(e.type,e.payload),tn(e.type,e.payload)}).catch(()=>{}))};ft&&an();let on=!1,sn=null,cn=()=>{},ln=()=>{},un=()=>{},dn=()=>{},fn=()=>{},pn=()=>Qt||on&&sn===`panel`,mn={onCopy:e=>{O.emit(`message:copy`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.id,`copy`).catch(e=>{i.debug&&console.error(`[AgentWidget] Failed to submit copy feedback:`,e)}),i.messageActions?.onCopy?.(e)},onFeedback:e=>{O.emit(`message:feedback`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.messageId,e.type).catch(e=>{i.debug&&console.error(`[AgentWidget] Failed to submit feedback:`,e)}),i.messageActions?.onFeedback?.(e)}};i.statusIndicator;let hn=(e,t=i.statusIndicator??{})=>e===`idle`?t.idleText??xt.idle:e===`connecting`?t.connectingText??xt.connecting:e===`connected`?t.connectedText??xt.connected:e===`error`?t.errorText??xt.error:e===`paused`?t.pausedText??xt.paused:e===`resuming`?t.resumingText??xt.resuming:xt[e];function gn(e,t,n,r){if(!P()&&(n.mode===`transient`||e.classList.contains(`persona-mb-2`))&&(C(e,Dn,n),w(e,n,r)),!(e.hasAttribute(bu)||e.hasAttribute(xu))){if(r===`idle`&&n.idleLink){e.textContent=``;let r=document.createElement(`a`);r.href=n.idleLink,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=t,r.style.color=`inherit`,r.style.textDecoration=`none`,e.appendChild(r)}else e.textContent=t}}let _n=oc({config:i,showClose:it()}),{wrapper:I,panel:L,pillRoot:vn}=_n.shell,R=_n.panelElements,{container:z,body:B,messagesWrapper:V,starterSuggestions:wn,transcriptSuggestions:Tn,suggestions:En,textarea:H,sendButton:U,composerForm:Dn,statusText:W,welcomeHost:On,welcomeIconHolder:kn,greetingHost:jn,introKicker:Nn,introTitle:Pn,introSubtitle:Fn,closeButton:G,iconHolder:Ln,headerTitle:Rn,headerSubtitle:zn,header:Bn,footer:K,actionsRow:Vn}=R,Hn=R.leftActions,Un=R.rightActions,Wn=R.sendButtonWrapper,Gn=R.setSendButtonMode,q=R.micButton,Kn=R.micButtonWrapper,qn=R.attachmentButton,Jn=R.attachmentButtonWrapper,Yn=R.attachmentInput,Xn=R.attachmentPreviewsContainer;z.classList.add(`persona-relative`),B.classList.add(`persona-relative`);let Zn=()=>mt.label??``,$n=()=>mt.iconName??`arrow-down`,er=()=>mt.enabled!==!1,tr=()=>ht.mode??`anchor-top`,nr=()=>tr()===`follow`||tr()===`anchor-top`&&Xs,rr=()=>ht.anchorTopOffset??16,ir=()=>ht.restorePosition??`bottom`,ar=()=>ht.pauseOnInteraction===!0,or=()=>ht.showActivityWhilePinned!==!1,sr=()=>ht.announce===!0,cr=()=>ht.scrollbar??`on-scroll`,lr=M(`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`);lr.type=`button`,lr.style.display=`none`,lr.setAttribute(`data-persona-scroll-to-bottom`,`true`);let fr=M(`span`,`persona-flex persona-items-center`),pr=M(`span`,``),mr=M(`span`,``);mr.setAttribute(`data-persona-scroll-to-bottom-count`,``),mr.style.display=`none`,lr.append(fr,pr,mr),z.appendChild(lr);let hr=M(`div`,`persona-stream-anchor-spacer`);hr.setAttribute(`aria-hidden`,`true`),hr.setAttribute(`data-persona-anchor-spacer`,``),hr.style.flexShrink=`0`,hr.style.pointerEvents=`none`,hr.style.height=`0px`,hr.style.display=`none`,B.appendChild(hr);let gr=M(`div`,`persona-sr-only`);gr.setAttribute(`aria-live`,`polite`),gr.setAttribute(`aria-atomic`,`true`),gr.setAttribute(`role`,`status`),gr.setAttribute(`data-persona-live-region`,``),Object.assign(gr.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`}),z.appendChild(gr);let _r=null,vr=null,yr=e=>{sr()&&e&&(vr=e,_r===null&&(_r=setTimeout(()=>{_r=null,vr&&sr()&&(gr.textContent=vr),vr=null},400)))},br=()=>{let e=t.ownerDocument.defaultView??window;return(i.launcher?.mobileFullscreen??!0)&&e.innerWidth<=(i.launcher?.mobileBreakpoint??640)&&(Be||xo(i))||i.launcher?.fullHeight===!0&&!i.launcher.sidebarMode&&!xo(i)},xr=()=>zs(i,br()),Sr=`empty`,Cr=0,wr=()=>Cr||parseFloat(t.style.getPropertyValue(`--persona-composer-lift`))||0,Or=()=>{let e=K.style.display===`none`?0:K.offsetHeight;lr.style.bottom=`${e+wr()+12}px`};Or();let kr=()=>{hi||(K.style.marginBottom=Cr>0?`${Cr}px`:``)},Ar=()=>{let e=eo(i,P()),n=xr();t.setAttribute(`data-persona-welcome-fullscreen`,String(br())),t.setAttribute(`data-persona-welcome-layout`,n.layout??`top`),t.setAttribute(`data-persona-welcome-layout-explicit`,i.welcome?.layout??``),t.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`);let r=K.style.display===`none`?0:K.offsetHeight,a=n.anchor===`center`&&Sr===`empty`?to(n.anchorComposerTop)??to(`44%`):null,o=a!==null&&n.layout===`centered`&&i.welcome?.anchor===void 0&&i.welcome?.anchorComposerTop===void 0,s=o?getComputedStyle(B):null,c=parseFloat(t.style.getPropertyValue(`--persona-composer-overlay-height`))||0,l=parseFloat(t.style.getPropertyValue(`--persona-composer-lift`))||0,u=Math.max(0,(parseFloat(s?.paddingBottom??``)||0)-(e===`overlay`?c+l:0)),d=o?B.getBoundingClientRect().top-z.getBoundingClientRect().top:0,f=!o||On.hidden?0:(On.querySelector(`[data-persona-welcome-plugin]`)??On).offsetHeight,p=a===null||P()?0:o?Math.max(0,Math.round((z.clientHeight-d-f-u-r)/2)):no({columnHeight:z.clientHeight,footerHeight:r,fraction:a});t.style.setProperty(`--persona-composer-overlay-height`,`${r}px`),t.style.setProperty(`--persona-composer-lift`,`${e===`overlay`?p:0}px`),Cr=e===`block`?p:0,kr(),Or()},jr=()=>{let e=!!Zn();lr.setAttribute(`aria-label`,Zn()||`Jump to latest`),lr.title=Zn(),lr.setAttribute(`data-persona-scroll-to-bottom-has-label`,e?`true`:`false`),fr.innerHTML=``;let t=N($n(),`14px`,`currentColor`,2);t?(fr.appendChild(t),fr.style.display=``):fr.style.display=`none`,pr.textContent=Zn(),pr.style.display=e?``:`none`};jr();let Mr=null,Nr=null,J=ri();J.subscribe(e=>{try{z.dispatchEvent(new CustomEvent(`persona:composer:state`,{detail:e,bubbles:!0,composed:!0}))}catch{}});let Ir=()=>{J.setText(H?.value??``)},Lr=()=>{J.setMentionRefs(Nr?.getMentionRefs()??[])},Rr=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),zr=e=>{let t=Object.freeze(e.map(Rr));J.setAttachments(t);try{i.attachments?.onChange?.(t)}catch(e){console.error(`[AgentWidget] attachments.onChange failed:`,e)}ju()};J.setSelectedModelId(i.composer?.selectedModelId);let Br=()=>i.composer?.modes??[],Vr=()=>Bi(Br(),i.composer?.modeGroups);{let e=Ui(i.composer?.defaultActiveModeIds??[],Br());e.length&&J.setActiveModeIds(e)}function Hr(e){if(J.getState().selectedModelId!==e){J.setSelectedModelId(e),Gr?.repaint();try{i.composer?.onModelChange?.(e)}catch(e){console.error(`[AgentWidget] composer.onModelChange failed:`,e)}}}function Ur(e){J.setActiveModeIds(e),qr?.render(e,Vr()),Yr.forEach(e=>e.repaint()),Ei?.resolve(),od(),Vi()}function Wr(e){Ur(Hi(J.getState().activeModeIds,e,Br(),i.composer?.modeGroups))}let Gr=null,Kr=null,qr=null,Yr=/* @__PURE__ */ new Map,Xr=null;function Zr(e){J.setQuote(e),Xr?.render(J.getState().quote),Vi(),Pc()}let Qr=!1;function $r(){let e=i.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?i.clientToken?`interrupt`:(!Qr&&i.debug===!0&&(Qr=!0,typeof console<`u`&&console.warn(`[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".`)),`block`):e}let ti=null;function ni(e){J.setPendingSubmission(e),ti?.render(J.getState().pendingSubmission),Vi()}let ii=e=>{let t=Yr.get(e);if(t)return t;let n=Ki({groupId:e,getGroup:()=>i.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>Br().filter(t=>t.groupId===e),getActiveIds:()=>J.getState().activeModeIds,onSelect:e=>Wr(e)});return Yr.set(e,n),n},ai=()=>{let e=[],t=J.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(Br().forEach((r,a)=>{if(Ri(r.groupId,i.composer?.modeGroups)){let t=r.groupId;if(n.has(t))return;n.add(t);let o=ii(t);o.action.order=Ii(a),o.action.label=i.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(o.action)}else e.push({id:Fi(r.id),kind:`button`,placement:`start`,order:Ii(a),presentation:r.presentation??`auto`,label:r.label,shortLabel:r.shortLabel,iconName:r.iconName,pressed:t.includes(r.id),onSelect:()=>Wr(r.id)})}),i.composer?.models?.length&&!f.some(e=>e.renderComposer)){let t=i.composer?.modelPicker?.presentation??`native`;(!Gr||Kr!==t)&&(Kr=t,Gr=Ni({getModels:()=>i.composer?.models??[],getSelectedModelId:()=>J.getState().selectedModelId,onSelect:e=>Hr(e),presentation:t,getSuffix:()=>i.composer?.modelPicker?.suffix})),e.push(Gr.action)}return e},si=null,ci=f.find(e=>e.renderHeader);if(ci?.renderHeader){let e=ci.renderHeader({config:i,defaultRenderer:()=>{let e=Bo({config:i,showClose:it()});return Vo(z,e,i),e.header},onClose:()=>ou(!1,`user`)});if(e){let t=Bn;t&&(t.replaceWith(e),Bn=e,_n.header.element=e)}}let li=()=>{Xt&&(B.style.display=`none`,K.parentNode?.insertBefore(Xt.element,K),Xt.update())},ui=()=>{if(!St){an();return}if(Qt=!0,Xt?li():Mc().then(e=>{!Xt&&Qt&&St&&(Xt=e.createEventStreamView({buffer:St,getFullHistory:()=>St.getAllFromStore(),onClose:()=>di(),config:i,plugins:f,getThroughput:()=>wt?.getMetric()??{status:`idle`},renderIconByName:N}),li())}).catch(()=>{di()}),fi){fi.style.boxShadow=`inset 0 0 0 1.5px ${Lo.actionIconColor}`;let e=i.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&fi.classList.add(e))}let e=()=>{if(!Qt)return;let t=Date.now();t-en>=200&&(Xt?.update(),en=t),$t=requestAnimationFrame(e)};en=0,$t=requestAnimationFrame(e),nl(),O.emit(`eventStream:opened`,{timestamp:Date.now()})},di=()=>{if(Qt){if(Qt=!1,Xt&&Xt.element.remove(),B.style.display=``,fi){fi.style.boxShadow=``;let e=i.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&fi.classList.remove(e))}$t!==null&&(cancelAnimationFrame($t),$t=null),nl(),O.emit(`eventStream:closed`,{timestamp:Date.now()})}},fi=null;if(ft){let e=i.features?.eventStream?.classNames,t=`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`+(e?.toggleButton?` `+e.toggleButton:``);fi=M(`button`,t),fi.style.width=`28px`,fi.style.height=`28px`,fi.style.color=Lo.actionIconColor,fi.type=`button`,fi.setAttribute(`aria-label`,`Event Stream`),fi.title=`Event Stream`;let n=b(Yt,`18px`,`currentColor`,1.5);n&&fi.appendChild(n);let r=R.clearChatButtonWrapper,a=R.closeButtonWrapper,o=r||a;o&&o.parentNode===Bn?Bn.insertBefore(fi,o):Bn.appendChild(fi),fi.addEventListener(`click`,()=>{Qt?di():ui()})}let mi=e=>{let t=i.attachments;if(!t?.enabled)return;let n=e.querySelector(`[data-persona-composer-attachment-previews]`)??e.querySelector(`.persona-attachment-previews`);if(!n){n=M(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let t=e.querySelector(`[data-persona-composer-form]`);t?.parentNode?t.parentNode.insertBefore(n,t):e.insertBefore(n,e.firstChild)}if(!(e.querySelector(`[data-persona-composer-attachment-input]`)??e.querySelector(`input[type="file"]`))){let n=M(`input`);n.type=`file`,n.setAttribute(`data-persona-composer-attachment-input`,``),n.accept=(t.allowedTypes??pt).join(`,`),n.multiple=(t.maxFiles??4)>1,n.style.display=`none`,n.setAttribute(`aria-label`,t.buttonTooltipText??`Attach files`),e.appendChild(n)}},hi=!1,gi=e=>{let t=f.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let n=i.composer,r=g?Q.isStreaming():!1;return t.renderComposer({config:i,defaultRenderer:e,requestRender:()=>Kp(),storage:_(t.id),onSubmit:e=>{Q&&!Q.isStreaming()&&Ef(e.trim(),{consumeDraft:!1})},streaming:r,disabled:r,openAttachmentPicker:()=>{cu()||Yn?.click()},models:n?.models,selectedModelId:J.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>Hr(e),onVoiceToggle:i.voiceRecognition?.enabled===!0?()=>{si?.()}:void 0})},_i=gi(()=>qo({config:i}).footer);_i&&(_n.replaceComposer(_i),K=_n.composer.footer,hi=!0);let Y=null,vi=e=>{Dn=e.form,H=e.input,Wn=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(U=e.sendButton),e.micButton&&(q=e.micButton,Kn=e.micButton.parentElement),e.found.status&&(W=e.found.status),e.found.suggestions&&(En=e.found.suggestions),e.attachmentButton&&(qn=e.attachmentButton,Jn=e.attachmentButton.parentElement),Yn=e.attachmentInput??null,Xn=e.attachmentPreviews??null,e.found.actionsRow&&(Vn=e.found.actionsRow),Hn=e.found.actionsStart,Un=e.found.actionsEnd};function yi(){let e=H;if(!e)return;let t=i.composer?.inputAttributes,n=!t?.ariaLabel&&!(e instanceof HTMLTextAreaElement)?e.getAttribute(`aria-label`):null;me(e,t),n&&e.setAttribute(`aria-label`,n),he(e,{submitKey:i.composer?.submitKey,insertNewlineOnTouchEnter:i.composer?.insertNewlineOnTouchEnter,coarsePointer:De(e)}),le(e,ke(i.composer?.maxLines,P()?5:3))}let bi=e=>{Y=oi(e,{debug:i.debug===!0}),Y&&vi(Y),yi()};mi(K),bi(K),Ir();let xi=$a(i,P());xi&&(V.style.maxWidth=xi,V.style.marginLeft=`auto`,V.style.marginRight=`auto`,V.style.width=`100%`,jn.style.maxWidth=xi,jn.style.marginLeft=`auto`,jn.style.marginRight=`auto`,jn.style.width=`100%`,wn.style.maxWidth=xi,Tn.style.maxWidth=xi,Tn.style.marginLeft=`auto`,Tn.style.marginRight=`auto`,Tn.style.width=`100%`);let Si=()=>{let e=$a(i,P());if(e&&!P())for(let t of[Dn,En,Xn,W])t&&(t.style.maxWidth=e,t.style.marginLeft=`auto`,t.style.marginRight=`auto`,t.style.width=`100%`)};Si();let Ci=()=>{i.attachments?.enabled&&Yn&&Xn&&(Mr?Mr.remountPreviews(Xn):(Mr=ei.fromConfig(i.attachments,zr),Mr.setPreviewsContainer(Xn)),Y?.addListener(Yn,`change`,e=>{let t=e.target;Mr?.handleFileSelect(t.files),t.value=``}),z.querySelector(`.persona-attachment-drop-overlay`)||z.appendChild(Au(i.attachments.dropOverlay)))};Ci();let wi=()=>Nr?.prefetch(),Ti=()=>{if(!i.contextMentions?.enabled||!H)return;let e=dr();if(!e){let e=H;ur().then(()=>{!Nr&&H===e&&e.isConnected&&(Ti(),Ei?.resolve())},()=>{});return}let t=Y?.header??null,n=t?Tt(t):void 0;if(Nr=e.createContextMentionOrchestrator({deps:{loadContextMentions:ge,loadContextMentionsInline:Ce,renderLucideIcon:N,createMentionButton:be},config:i,textarea:H,anchor:Dn??H,getMessages:()=>Q.getMessages(),liveRegionHost:z,chipRow:n}),Nr&&!n){let e=H;e.parentElement?.insertBefore(Nr.contextRow,e)}};Ti();let Ei=null,Di={getState:()=>J.getState(),getValue:()=>H?.value??``,setValue:e=>{H&&(H.value=e,H.dispatchEvent(new Event(`input`,{bubbles:!0})),Ir())},submit:()=>{kt(Y?.form??null)},openAttachmentPicker:()=>{cu()||Yn?.click()},toggleVoice:()=>{si?.()},requestRender:()=>Ei?.resolve()},Oi=()=>{let e=[];return(Nr?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:pi.mention+n,element:t,managed:!0})}),Jn&&e.push({id:`core:attachment`,placement:`start`,order:pi.attachment,element:Jn}),Kn&&e.push({id:`core:mic`,placement:`end`,order:pi.mic,element:Kn}),Wn&&e.push({id:`core:send`,placement:`end`,order:pi.send,element:Wn}),e},ki=()=>{Ei?.destroy(),Ei=Ai({getBindings:()=>Y,collect:()=>({builtIns:Oi(),configActions:[...ai(),...i.composer?.actions??[]],plugins:f,contributionContext:{config:i,getState:()=>J.getState(),requestRender:()=>Ei?.resolve()},debug:i.debug===!0}),actionContext:Di,getState:()=>J.getState(),getOverflow:()=>i.composer?.actionOverflow,reportError:(e,t)=>{typeof console<`u`&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),Ei.resolve()};ki();let ji=()=>{if(qr?.destroy(),qr=null,!Vr().length)return;let e=Y?.header;e&&(qr=Pi({row:Tt(e),onRemove:e=>Wr(e),initialIds:J.getState().activeModeIds}),qr.render(J.getState().activeModeIds,Vr()))};ji();let Mi=()=>{Xr?.destroy(),Xr=null,ti?.destroy(),ti=null;let e=Y?.header;e&&(Xr=qi({onDismiss:()=>Zr(void 0)}),e.appendChild(Xr.element),Xr.render(J.getState().quote),$r()===`defer-one`&&(ti=Ji({onEdit:()=>hf(),onRemove:()=>ni(void 0)}),e.appendChild(ti.element),ti.render(J.getState().pendingSubmission)))};Mi();let Li=ea(),zi=()=>{let e=Y?.header?.querySelector(Dt);if(e)return e.childElementCount>0;let t=J.getState();return t.mentionRefs.length>0||Ui(t.activeModeIds,Vr()).length>0};function Vi(){let e=J.getState(),t=Li.observe(ta(H),e.text);K.toggleAttribute(`data-persona-composer-compact`,$i({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:zi(),hasQuote:e.quote!==void 0,hasPendingSubmission:e.pendingSubmission!==void 0}))}function ia(){i.composer?.layout===`single-row`&&!P()?K.setAttribute(`data-persona-composer-layout`,`single-row`):K.removeAttribute(`data-persona-composer-layout`)}ia(),J.subscribe(()=>{Ei?.sync(),ju(),Nu(),Vi(),Pc()}),Nu();let aa=!1,sa=e=>{if(aa||i.debug!==!0)return;let t=[`messages`,`composer`].filter(t=>e[t]);t.length&&(aa=!0,console.warn(`[persona] layout.slots.${t.join(` and layout.slots.`)} ${t.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 e=i.layout?.slots??{};sa(e);let t=e=>{switch(e){case`body-top`:return B.querySelector(`[data-persona-intro-card]`);case`messages`:return V;case`footer-top`:return En;case`composer`:return Dn;case`footer-bottom`:return W;default:return null}},n=(e,t)=>{switch(e){case`header-left`:case`header-center`:case`header-right`:if(e===`header-left`)Bn.insertBefore(t,Bn.firstChild);else if(e===`header-right`)Bn.appendChild(t);else{let e=Bn.querySelector(`.persona-flex-col`);e?e.parentNode?.insertBefore(t,e.nextSibling):Bn.appendChild(t)}break;case`body-top`:{let e=B.querySelector(`[data-persona-intro-card]`);e?e.replaceWith(t):B.insertBefore(t,B.firstChild);break}case`body-bottom`:B.appendChild(t);break;case`footer-top`:En.replaceWith(t);break;case`footer-bottom`:W.replaceWith(t)}};for(let[r,a]of Object.entries(e))if(a)try{let e=a({config:i,defaultContent:()=>t(r)});e&&n(r,e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Error rendering slot "${r}":`,e)}})(),V.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`button[data-persona-copy-tool-detail]`);n&&(e.preventDefault(),e.stopPropagation(),_c(n))});let ca=e=>{let t=e.target.closest(`button[data-expand-header="true"]`);if(!t)return;let n=t.closest(`.persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;ec(),rl();let a=t.getAttribute(`data-bubble-type`);if(n.classList.contains(`persona-activity-row`)){c.manual(r);let e=n.parentElement?.closest(`[data-persona-tool-group]`);e?.dataset.messageId&&c.manual(e.dataset.messageId)}if(a===`reasoning`)s.has(r)?s.delete(r):s.add(r),dc(r,n,s);else if(a===`tool`)o.has(r)?o.delete(r):o.add(r),Sc(r,n,o,i);else if(a===`approval`&&y){let e=((i.approval===!1?void 0:i.approval)?.detailsDisplay??`collapsed`)===`expanded`,t=l.get(r)??e;l.set(r,!t),y.updateApprovalDetailsUI(r,n,i,l)}gs.delete(r)};V.addEventListener(`pointerdown`,e=>{e.target.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),ca(e))}),V.addEventListener(`click`,e=>{e.detail===0&&e.target.closest(`.persona-activity-row`)&&ca(e)}),V.addEventListener(`keydown`,e=>{let t=e.target;(e.key===`Enter`||e.key===` `)&&t.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),ca(e))}),V.addEventListener(`copy`,e=>{let{clipboardData:t}=e;if(!t)return;let n=V.getRootNode(),r=typeof n.getSelection==`function`?n.getSelection():window.getSelection();if(!r||r.isCollapsed)return;let i=r.toString(),a=io(i);a&&a!==i&&(t.setData(`text/plain`,a),e.preventDefault())});let la=/* @__PURE__ */ new Map,ua=null,da=`idle`,fa={idle:{icon:`volume-2`,label:`Read aloud`},loading:{icon:`loader-circle`,label:`Loading…`},playing:{icon:`pause`,label:`Pause`},paused:{icon:`play`,label:`Resume`}},pa=(e,t)=>{let{icon:n,label:r}=fa[t];e.setAttribute(`aria-label`,r),e.title=r,e.setAttribute(`aria-pressed`,t===`idle`?`false`:`true`),e.classList.toggle(`persona-message-action-active`,t!==`idle`),e.classList.toggle(`persona-message-action-loading`,t===`loading`);let i=N(n,14,`currentColor`,2);i&&(e.innerHTML=``,e.appendChild(i))},ma=()=>{V.querySelectorAll(`[data-action="read-aloud"]`).forEach(e=>{let t=e.closest(`[data-actions-for]`)?.getAttribute(`data-actions-for`)??null;pa(e,t&&t===ua?da:`idle`)})};V.addEventListener(`click`,e=>{let t=e.target.closest(`.persona-message-action-btn[data-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`[data-actions-for]`);if(!n)return;let r=n.getAttribute(`data-actions-for`);if(!r)return;let a=t.getAttribute(`data-action`);if(a===`copy`){let e=Q.getMessages().find(e=>e.id===r);if(e&&mn.onCopy){let n=e.content||``;navigator.clipboard.writeText(n).then(()=>{t.classList.add(`persona-message-action-success`);let e=b(Zt,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e)),setTimeout(()=>{t.classList.remove(`persona-message-action-success`);let e=b(nn,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))},2e3)}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to copy message:`,e)}),mn.onCopy(e)}}else if(a===`read-aloud`)Q.toggleReadAloud(r);else if(a===`upvote`||a===`downvote`){let e=(la.get(r)??null)===a,i=a===`upvote`?`thumbs-up`:`thumbs-down`;if(e){la.delete(r),t.classList.remove(`persona-message-action-active`);let e=N(i,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))}else{let e=a===`upvote`?`downvote`:`upvote`,o=n.querySelector(`[data-action="${e}"]`);if(o){o.classList.remove(`persona-message-action-active`);let t=N(e===`upvote`?`thumbs-up`:`thumbs-down`,14,`currentColor`,2);t&&(o.innerHTML=``,o.appendChild(t))}la.set(r,a),t.classList.add(`persona-message-action-active`);let s=N(i,14,`currentColor`,2);s&&(s.setAttribute(`fill`,`currentColor`),t.innerHTML=``,t.appendChild(s)),t.classList.remove(`persona-message-action-pop`),t.offsetWidth,t.classList.add(`persona-message-action-pop`);let c=Q.getMessages().find(e=>e.id===r);c&&mn.onFeedback&&mn.onFeedback({type:a,messageId:c.id,message:c})}}else if(a===`regenerate`)ha?.regenerate(r);else if(a===`edit`)ha?.edit(r);else if(a===`quote`)ha?.quote(r);else if(a?.startsWith(`custom:`)){let e=a.slice(7),t=i.messageActions?.custom?.find(t=>t.id===e),n=Q.getMessages().find(e=>e.id===r);if(!t||!n)return;try{t.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let ha=null;V.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-approval-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`.persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;let i=t.getAttribute(`data-approval-action`);if(!i)return;let a=i===`approve`?`approved`:`denied`,o=Q.getMessages().find(e=>e.id===r);if(!o?.approval)return;let s=n.querySelector(`[data-approval-buttons]`);s&&s.querySelectorAll(`button`).forEach(e=>{e.disabled=!0,e.style.opacity=`0.5`,e.style.cursor=`not-allowed`}),v(o.approval)?Q.resolveWebMcpApproval(r,a):Q.resolveApproval(o.approval,a)});let X=null,ga=!1,_a=null,va=()=>{},ya=`none`,ba=null,xa={artifacts:[],selectedId:null},Sa=!1,wa=!1,Ta=!1,Ea=!1,Da=()=>Ea||xa.artifacts.some(e=>rt(i.features?.artifacts,e)===`panel`),Oa=()=>xa.artifacts.length>0&&!Sa&&Da(),ka={current:null},Aa=(e,t)=>{let n=Q.getArtifactById(t),r=n?.markdown,i=n?.title||`artifact`,a=n?.file,o=n?.artifactType??`markdown`;if(!r){let t=(e.closest(`[data-open-artifact], [data-artifact-inline]`)?.closest(`[data-message-id]`))?.getAttribute(`data-message-id`);if(t){let e=Q.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);r=t?.props?.markdown,i=t?.props?.title||i,t?.props?.file&&typeof t.props.file==`object`&&(a=t.props.file),!n&&typeof t?.props?.artifactType==`string`&&(o=t.props.artifactType)}catch{}}}return{markdown:r,title:i,file:a,artifactType:o}};V.addEventListener(`click`,e=>{let t=e.target.closest(`[data-download-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-download-artifact`);if(!n||i.features?.artifacts?.onArtifactAction?.({type:`download`,artifactId:n})===!0)return;let{markdown:r,title:a,file:o}=Aa(t,n);if(!r)return;let s=Hc();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:a,markdown:r,file:o}))}),V.addEventListener(`click`,e=>{let t=e.target.closest(`[data-artifact-custom-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-artifact-custom-action`);if(!n)return;let r=t.closest(`[data-artifact-inline]`),a=r?null:t.closest(`[data-open-artifact]`),o=r?r.getAttribute(`data-artifact-inline`):a?.getAttribute(`data-open-artifact`)??null,s=(r?i.features?.artifacts?.inlineActions:i.features?.artifacts?.cardActions)?.find(e=>e.id===n);if(!s)return;let{markdown:c,title:l,file:u,artifactType:d}=Aa(t,o??``),f={artifactId:o,title:l,artifactType:d,markdown:c,file:u};try{Promise.resolve(s.onClick(f)).catch(()=>{})}catch{}}),V.addEventListener(`click`,e=>{let t=e.target.closest(`[data-copy-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-copy-artifact`);if(!n)return;let r=Q.getArtifactById(n),i=Hc();if(!i)return;let a=``;if(r)a=i.artifactCopyText(r);else{let{markdown:e,file:r,artifactType:o}=Aa(t,n);o===`markdown`&&(a=i.artifactCopyText({id:n,artifactType:`markdown`,status:`complete`,markdown:e??``,...r?{file:r}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=b(Zt,16,`currentColor`,2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=b(nn,16,`currentColor`,2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),V.addEventListener(`click`,e=>{let t=e.target.closest(`[data-expand-artifact-inline]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-expand-artifact-inline`);n&&i.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:n})!==!0&&(Sa=!1,Ea=!0,wa=!0,Ta=!0,Q.selectArtifact(n),vo())}),V.addEventListener(`click`,e=>{let t=e.target;if(t.closest(`[data-download-artifact]`)||t.closest(`[data-artifact-custom-action]`))return;let n=t.closest(`[data-open-artifact]`);if(!n)return;let r=n.getAttribute(`data-open-artifact`);r&&i.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:r})!==!0&&(e.preventDefault(),e.stopPropagation(),Sa=!1,Ea=!0,Q.selectArtifact(r),vo())}),V.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target;(t.hasAttribute(`data-open-artifact`)||t.hasAttribute(`data-expand-artifact-inline`))&&(e.preventDefault(),t.click())});let ja=R.composerOverlay,Ma=e=>{ur().catch(()=>{}),Ze(e,i,ja)},Na=null,Pa={mount:t,overlay:ja,sessionRef:ka,config:()=>i},Fa=!1,Ia=e=>t=>{let n=t.target,r=n?.closest?.(`[data-persona-ask-sheet-for]`);if(!r||!(e===`click`?n?.closest(`[data-ask-user-action]`):t.key===`Enter`&&n?.matches?.(`[data-ask-free-text-input="true"]`)))return;let i=n=>{Na??=n.createAskUserSheetHandlers(Pa),Na[e](t)},a=dr();a?i(a):Fa||(Fa=!0,ur().then(e=>{Fa=!1,r.isConnected&&i(e)},()=>{Fa=!1}))};ja.addEventListener(`click`,Ia(`click`)),ja.addEventListener(`keydown`,Ia(`keydown`));let La=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)return;let n=ja.querySelector(`[data-persona-ask-sheet-for]`);if(!n||n.getAttribute(`data-ask-layout`)!==`rows`||n.getAttribute(`data-multi-select`)===`true`)return;let r=Number(e.key),i=n.querySelectorAll(`[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]`)[r-1];i&&(e.preventDefault(),i.click())};document.addEventListener(`keydown`,La);let Ra=null,za=null,Ba=null,Va=null,Ha=()=>{},Ua=!1,Wa=``,Ga=``;function qa(){Va?.(),Va=null}let Ja=()=>{let e=Fd?.railShell?Fd.railHost:null,t=e?.isConnected?e:null,n=t?t.getBoundingClientRect().width:0;return n<=0?200:n+360},Xa=()=>{if(!Ra||!za)return;let e=t.classList.contains(`persona-artifact-welded-split`),n=t.ownerDocument.defaultView??window,r=n.innerWidth<=640;if(!e||t.classList.contains(`persona-artifact-narrow-host`)||r){za.style.removeProperty(`position`),za.style.removeProperty(`left`),za.style.removeProperty(`top`),za.style.removeProperty(`bottom`),za.style.removeProperty(`width`),za.style.removeProperty(`z-index`);return}let i=Ra.firstElementChild;if(!i||i===za)return;za.style.position=`absolute`,za.style.top=`0`,za.style.bottom=`0`,za.style.width=`10px`,za.style.zIndex=`5`;let a=El(Ra,n),o=i.offsetWidth+a/2-5;za.style.left=`${Math.max(0,o)}px`},po=()=>{},mo=()=>{let e=t.ownerDocument.defaultView??window,n=i.launcher?.mobileFullscreen??!0,r=i.launcher?.mobileBreakpoint??640;return!n||e.innerWidth>r?!1:Be||xo(i)},_o=()=>!Wc(i)||!Oa()||t.classList.contains(`persona-artifact-narrow-host`)||mo()||(t.ownerDocument.defaultView??window).innerWidth<641?`none`:Yc(i)?`detached`:`welded`,vo=()=>{if(!X||!Wc(i))return;Xc(t,i),Zc(t,i),po();let e=i.features?.artifacts?.layout?.narrowHostMaxWidth??520,n=L.getBoundingClientRect().width||0;t.classList.toggle(`persona-artifact-narrow-host`,n>0&&n<=e);let r=Oa();X.setVisible(r),X.update(xa),Sa?(X.setMobileOpen(!1),X.element.classList.add(`persona-hidden`),X.backdrop?.classList.add(`persona-hidden`),wa=!1,Ta=!1):xa.artifacts.length>0&&Da()?(X.element.classList.remove(`persona-hidden`),X.setMobileOpen(!0)):(X.setMobileOpen(!1),X.element.classList.add(`persona-hidden`),X.backdrop?.classList.add(`persona-hidden`),wa=!1,Ta=!1);let a=i.features?.artifacts?.layout?.showExpandToggle===!0;if(X.setExpandToggleVisible(a),X.setCopyButtonVisible(i.features?.artifacts?.layout?.showCopyButton===!0),X.setRefreshButtonVisible(typeof i.features?.artifacts?.layout?.onDocumentToolbarRefresh==`function`),X.setCustomActions(i.features?.artifacts?.toolbarActions??[]),X.setTabFade(i.features?.artifacts?.layout?.tabFade),X.setRenderTabBar(i.features?.artifacts?.renderTabBar),!a&&!Ta&&(wa=!1),wa!==Ua){let e=X.element;wa?(Wa=e.style.width,Ga=e.style.maxWidth,e.style.removeProperty(`width`),e.style.removeProperty(`max-width`)):(Wa&&(e.style.width=Wa),Ga&&(e.style.maxWidth=Ga),Wa=``,Ga=``),Ua=wa}t.classList.toggle(`persona-artifact-expanded`,wa),X.setExpanded(wa);let o=_o();o!==ya&&(ya=o,va()),Ha()};if(Wc(i)){L.style.position=`relative`;let e=M(`div`,`persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0`),n=M(`div`,`persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root`);e.appendChild(z),Ra=n,n.appendChild(e),L.appendChild(n);let r=e=>{ga||X||(X=e.createArtifactPane(i,{onSelect:e=>ka.current?.selectArtifact(e),onDismiss:()=>{Sa=!0,vo()},onToggleExpand:()=>{let e=!wa,t=xa.selectedId??xa.artifacts[xa.artifacts.length-1]?.id??null;i.features?.artifacts?.onArtifactAction?.({type:`expand`,artifactId:t,expanded:e})!==!0&&(wa=e,e||(Ta=!1),vo())}}),X.element.classList.add(`persona-hidden`),n.appendChild(X.element),X.backdrop&&L.appendChild(X.backdrop),Ha(),vo())},a=Hc();a?r(a):(Uc(()=>{let e=Hc();e&&r(e)}),Vc().catch(()=>{})),Ha=()=>{if(Ra&&X){if(i.features?.artifacts?.layout?.resizable!==!0)Ba?.(),Ba=null,qa(),za&&=(za.remove(),null),X.element.style.removeProperty(`width`),X.element.style.removeProperty(`maxWidth`);else{if(!za){let e=M(`div`,`persona-artifact-split-handle persona-shrink-0 persona-h-full`);e.setAttribute(`role`,`separator`),e.setAttribute(`aria-orientation`,`vertical`),e.setAttribute(`aria-label`,`Resize artifacts panel`),e.tabIndex=0;let n=t.ownerDocument,r=n.defaultView??window,a=a=>{if(!X||a.button!==0||t.classList.contains(`persona-artifact-narrow-host`)||t.classList.contains(`persona-artifact-expanded`)||r.innerWidth<=640)return;a.preventDefault(),qa();let o=a.clientX,s=X.element.getBoundingClientRect().width,c=i.features?.artifacts?.layout,l=n=>{let i=Ra.getBoundingClientRect().width,a=t.classList.contains(`persona-artifact-welded-split`),l=El(Ra,r),u=a?0:e.getBoundingClientRect().width||6,d=Dl(s-(n.clientX-o),i,l,u,c?.resizableMinWidth,c?.resizableMaxWidth,Ja());X.element.style.width=`${d}px`,X.element.style.maxWidth=`none`,Xa()},u=()=>{n.removeEventListener(`pointermove`,l),n.removeEventListener(`pointerup`,u),n.removeEventListener(`pointercancel`,u),Va=null;try{e.releasePointerCapture(a.pointerId)}catch{}};Va=u,n.addEventListener(`pointermove`,l),n.addEventListener(`pointerup`,u),n.addEventListener(`pointercancel`,u);try{e.setPointerCapture(a.pointerId)}catch{}};e.addEventListener(`pointerdown`,a),za=e,Ra.insertBefore(e,X.element),Ba=()=>{e.removeEventListener(`pointerdown`,a)}}if(za){let e=Oa();za.classList.toggle(`persona-hidden`,!e),Xa()}}}},po=()=>{if(!Be||!X||(i.launcher?.sidebarMode??!1)||xo(i)&&Co(i).reveal===`emerge`)return;let e=t.ownerDocument.defaultView??window,n=i.launcher?.mobileFullscreen??!0,r=i.launcher?.mobileBreakpoint??640;if(n&&e.innerWidth<=r||!Qc(i,Be))return;let a=Us(i).width,o=i.features?.artifacts?.layout?.expandedPanelWidth??`min(720px, calc(100vw - 24px))`;Oa()?(L.style.width=o,L.style.maxWidth=o):(L.style.width=a,L.style.maxWidth=a)},typeof ResizeObserver<`u`&&(_a=new ResizeObserver(()=>{vo()}),_a.observe(L))}else L.appendChild(z);P()&&vn&&(R.peekBanner&&vn.appendChild(R.peekBanner),vn.appendChild(K)),t.appendChild(I),vn&&t.appendChild(vn);let bo=()=>{let e=mo()||P()&&i.launcher?.composerBar?.expandedSize===`fullscreen`||i.launcher?.fullHeight===!0&&!i.launcher?.sidebarMode&&!xo(i);if(V.style.gap=e?`var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))`:`var(--persona-components-message-gap, 12px)`,V.style.setProperty(`--persona-transcript-gap`,V.style.gap),P()){L.style.width=`100%`,L.style.maxWidth=`100%`;let e=i.launcher?.composerBar??{},t=I.dataset.state===`expanded`,n=e.expandedSize??`anchored`;if(!(t&&n!==`fullscreen`)){z.style.background=``,z.style.border=``,z.style.borderRadius=``,z.style.overflow=``,z.style.boxShadow=``;return}let r=i.theme?.components?.panel,a=Ya(i),o=(e,t)=>e==null||e===``?t:Ca(a,e)??e;z.style.background=`var(--persona-surface, #ffffff)`,z.style.border=o(r?.border,`1px solid var(--persona-border)`),z.style.borderRadius=o(r?.borderRadius,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`),z.style.boxShadow=o(r?.shadow,`var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))`),z.style.overflow=`hidden`;return}let n=xo(i),r=i.launcher?.sidebarMode??!1,a=n||r||(i.launcher?.fullHeight??!1),o=i.launcher?.enabled===!1,s=i.launcher?.detachedPanel===!0,c=i.theme?.components?.panel,l=i.darkTheme?.components?.panel,u=Ka(i)===`dark`?ce(c??{},l??{}):c,d=Ya(i),f=(e,t)=>e==null||e===``?t:Ca(d,e)??e,p=t.ownerDocument.defaultView??window,m=i.launcher?.mobileFullscreen??!0,h=i.launcher?.mobileBreakpoint??640,g=p.innerWidth<=h,_=m&&g&&Be,v=n&&m&&g,y=i.launcher?.position??`bottom-left`,b=y===`bottom-left`||y===`top-left`,x=i.launcher?.zIndex??1e5,S=(e,t,n)=>`var(--persona-components-panel-modes-${e}-${t}, ${n})`,C=u?.modes?.floating,w=f(C?.border??u?.border,S(`floating`,`border`,`var(--persona-panel-border, 1px solid var(--persona-border))`)),T=f(C?.shadow??u?.shadow,S(`floating`,`shadow`,`var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))`)),E=f(C?.borderRadius??u?.borderRadius,S(`floating`,`borderRadius`,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`)),ee=s&&!_&&!v,te=_||v?`mobile`:ee?`floating`:n?`docked`:r?`sidebar`:o?`inline`:`floating`,ne=u?.modes?.[te];ee?t.setAttribute(`data-persona-panel-detached`,`true`):t.removeAttribute(`data-persona-panel-detached`);let re=ee?w:r||_?`none`:w,ie=ee?T:_?`none`:r?b?`2px 0 12px rgba(0, 0, 0, 0.08)`:`-2px 0 12px rgba(0, 0, 0, 0.08)`:o?`none`:T;n&&!_&&!ee&&(ie=`none`,re=`none`);let ae=ee?E:r||_?`0`:E,oe=f(ne?.border??u?.border,S(te,`border`,re)),se=f(ne?.shadow??u?.shadow,S(te,`shadow`,ie)),O=f(ne?.borderRadius??u?.borderRadius,S(te,`borderRadius`,ae)),le=_o(),ue=le===`detached`,de=le===`welded`;t.classList.toggle(`persona-artifact-detached-split`,ue),t.classList.toggle(`persona-artifact-welded-split`,de);let fe=`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)))))`,k=(i.features?.artifacts?.layout?.chatSurface===`flush`?`flush`:`card`)==`flush`&&Wc(i)&&Yc(i)&&o&&!n;t.classList.toggle(`persona-artifact-chat-flush`,k);let pe=ue||k?`none`:se,me=ue?w:de?`none`:oe,he=ue?E:O;k&&(me=`none`,he=`0`);let ge=ne?.borderRadius!=null&&ne.borderRadius!==``||u?.borderRadius!=null&&u.borderRadius!==``,_e=k&&!ge?`0`:O,ve=B.scrollTop;t.style.cssText=``,I.style.cssText=``,L.style.cssText=``,z.style.cssText=``,B.style.cssText=``,hi||(K.style.cssText=``),Qt&&(B.style.display=`none`),(a||o)&&(t.style.minWidth=`0`);let ye=()=>{ve<=0||(B.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(B.scrollTop===ve)return;let e=B.scrollHeight-B.clientHeight;e<=0||(B.scrollTop=Math.min(ve,e))})};if(_){I.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`),I.style.cssText=`
|
|
29
29
|
position: fixed !important;
|
|
30
30
|
inset: 0 !important;
|
|
31
31
|
width: 100% !important;
|
|
@@ -35,9 +35,9 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
35
35
|
padding: 0 !important;
|
|
36
36
|
display: flex !important;
|
|
37
37
|
flex-direction: column !important;
|
|
38
|
-
z-index: ${
|
|
38
|
+
z-index: ${x} !important;
|
|
39
39
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
40
|
-
`,
|
|
40
|
+
`,L.style.cssText=`
|
|
41
41
|
position: relative !important;
|
|
42
42
|
display: flex !important;
|
|
43
43
|
flex-direction: column !important;
|
|
@@ -50,7 +50,7 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
50
50
|
padding: 0 !important;
|
|
51
51
|
box-shadow: none !important;
|
|
52
52
|
border-radius: 0 !important;
|
|
53
|
-
`,
|
|
53
|
+
`,z.style.cssText=`
|
|
54
54
|
display: flex !important;
|
|
55
55
|
flex-direction: column !important;
|
|
56
56
|
flex: 1 1 0% !important;
|
|
@@ -61,7 +61,7 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
61
61
|
overflow: hidden !important;
|
|
62
62
|
border-radius: 0 !important;
|
|
63
63
|
border: none !important;
|
|
64
|
-
`,
|
|
64
|
+
`,B.style.flex=`1 1 0%`,B.style.minHeight=`0`,B.style.overflowY=`auto`,K.style.flexShrink=`0`,kr(),Ye=!0,ye();return}let A=Us(i);if(!r&&!n)o&&a?(L.style.width=`100%`,L.style.maxWidth=`100%`):(L.style.width=A.width,L.style.maxWidth=A.maxWidth);else if(n){if(Co(i).reveal===`emerge`&&!s){let e=Co(i).width;L.style.width=e,L.style.maxWidth=e}else L.style.width=`100%`,L.style.maxWidth=`100%`}if(po(),L.style.boxShadow=pe,L.style.borderRadius=_e,ue?L.style.border=`none`:de&&(L.style.border=oe),z.style.border=me,z.style.borderRadius=he,z.style.boxShadow=ue&&!k?fe:``,k&&(z.style.background=`transparent`,B.style.background=`transparent`,K.style.background=`transparent`,K.style.borderTop=`none`),de){let e=i.features?.artifacts?.layout;ba=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||O}else ba=null;let be=ne?.border!=null||u?.border!=null;if(n&&!_&&!ee&&!ue&&!de&&!be&&(z.style.border=`none`,Co(i).side===`right`?z.style.borderLeft=`1px solid var(--persona-border)`:z.style.borderRight=`1px solid var(--persona-border)`),n&&!_&&de&&!be&&(Co(i).side===`right`?L.style.borderLeft=`1px solid var(--persona-border)`:L.style.borderRight=`1px solid var(--persona-border)`),a&&(t.style.display=`flex`,t.style.flexDirection=`column`,t.style.height=`100%`,t.style.minHeight=`0`,o&&(t.style.width=`100%`),I.style.display=`flex`,I.style.flexDirection=`column`,I.style.flex=`1 1 0%`,I.style.minHeight=`0`,I.style.maxHeight=`100%`,I.style.height=`100%`,o&&(I.style.overflow=`hidden`),L.style.display=`flex`,L.style.flexDirection=`column`,L.style.flex=`1 1 0%`,L.style.minHeight=`0`,L.style.maxHeight=`100%`,L.style.height=`100%`,ue||(L.style.overflow=`hidden`),z.style.display=`flex`,z.style.flexDirection=`column`,z.style.flex=`1 1 0%`,z.style.minHeight=`0`,z.style.maxHeight=`100%`,z.style.overflow=`hidden`,B.style.flex=`1 1 0%`,B.style.minHeight=`0`,B.style.overflowY=`auto`,K.style.flexShrink=`0`),o&&(ee||ue||k)&&!n&&(k||(I.style.padding=`var(--persona-panel-inset)`),I.style.background=`var(--persona-panel-canvas-bg)`),I.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`),!r&&!o&&!n&&(jo[y]??jo[`bottom-right`]).split(` `).forEach(e=>I.classList.add(e)),r){let e=D(i).sidebarWidth?i.launcher?.sidebarWidth??`420px`:Ca(Ya(i),`components.panel.width`)??`420px`;s?I.style.cssText=`
|
|
65
65
|
position: fixed !important;
|
|
66
66
|
top: var(--persona-panel-inset) !important;
|
|
67
67
|
bottom: var(--persona-panel-inset) !important;
|
|
@@ -72,9 +72,9 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
72
72
|
padding: 0 !important;
|
|
73
73
|
display: flex !important;
|
|
74
74
|
flex-direction: column !important;
|
|
75
|
-
z-index: ${
|
|
76
|
-
${
|
|
77
|
-
`:
|
|
75
|
+
z-index: ${x} !important;
|
|
76
|
+
${b?`left: var(--persona-panel-inset) !important; right: auto !important;`:`left: auto !important; right: var(--persona-panel-inset) !important;`}
|
|
77
|
+
`:I.style.cssText=`
|
|
78
78
|
position: fixed !important;
|
|
79
79
|
top: 0 !important;
|
|
80
80
|
bottom: 0 !important;
|
|
@@ -85,9 +85,9 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
85
85
|
padding: 0 !important;
|
|
86
86
|
display: flex !important;
|
|
87
87
|
flex-direction: column !important;
|
|
88
|
-
z-index: ${
|
|
89
|
-
${
|
|
90
|
-
`,
|
|
88
|
+
z-index: ${x} !important;
|
|
89
|
+
${b?`left: 0 !important; right: auto !important;`:`left: auto !important; right: 0 !important;`}
|
|
90
|
+
`,L.style.cssText=`
|
|
91
91
|
position: relative !important;
|
|
92
92
|
display: flex !important;
|
|
93
93
|
flex-direction: column !important;
|
|
@@ -99,9 +99,9 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
99
99
|
margin: 0 !important;
|
|
100
100
|
padding: 0 !important;
|
|
101
101
|
box-shadow: ${pe} !important;
|
|
102
|
-
border-radius: ${
|
|
103
|
-
${
|
|
104
|
-
`,
|
|
102
|
+
border-radius: ${_e} !important;
|
|
103
|
+
${ue?`border: none !important;`:de?`border: ${oe} !important;`:``}
|
|
104
|
+
`,L.style.setProperty(`width`,`100%`,`important`),L.style.setProperty(`max-width`,`100%`,`important`),z.style.cssText=`
|
|
105
105
|
display: flex !important;
|
|
106
106
|
flex-direction: column !important;
|
|
107
107
|
flex: 1 1 0% !important;
|
|
@@ -110,16 +110,16 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
110
110
|
min-height: 0 !important;
|
|
111
111
|
max-height: 100% !important;
|
|
112
112
|
overflow: hidden !important;
|
|
113
|
-
border-radius: ${
|
|
114
|
-
border: ${
|
|
115
|
-
${
|
|
116
|
-
${
|
|
117
|
-
`,
|
|
113
|
+
border-radius: ${he} !important;
|
|
114
|
+
border: ${me} !important;
|
|
115
|
+
${ue&&!k?`box-shadow: ${fe} !important;`:``}
|
|
116
|
+
${k?`background: transparent !important;`:``}
|
|
117
|
+
`,hi||(K.style.cssText=`
|
|
118
118
|
flex-shrink: 0 !important;
|
|
119
119
|
border-top: none !important;
|
|
120
120
|
padding: 8px 16px 12px 16px !important;
|
|
121
|
-
${
|
|
122
|
-
`)}if(!a&&!n){let e=r?``:`padding-top: 1.25em !important;`,t=r?``:`z-index: ${c.launcher?.zIndex??1e5} !important;`;F.style.cssText+=`max-height: -moz-available !important; max-height: stretch !important;`+e+t}jr(),ge()},ko=()=>{t.style.setProperty(`--persona-content-max-width`,Ga(c,N()))},jo=!1;function Mo(){c.layout?.topFade&&z.scrollTop>1?z.setAttribute(`data-persona-top-fade`,`true`):z.removeAttribute(`data-persona-top-fade`)}let Fo=()=>{Mo();let e=Ka(c,N());N()&&c.composer?.placement&&c.debug===!0&&!jo&&(jo=!0,console.warn(`[persona] composer.placement is ignored in composer-bar mount mode.`));let n=wr();t.setAttribute(`data-persona-composer-placement`,e),t.setAttribute(`data-persona-conversation-state`,Tr),t.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`),t.style.setProperty(`--persona-composer-anchor-gap`,n.composerGap??`24px`),Mr()},Io=()=>{if(N())return;let e=po(c),n=c.launcher?.sidebarMode??!1;if(e||n||(c.launcher?.fullHeight??!1)||!He)return;let r=t.ownerDocument.defaultView??window,i=c.launcher?.mobileFullscreen??!0,a=c.launcher?.mobileBreakpoint??640;if(i&&r.innerWidth<=a)return;let o=Fs(c);I.style.height=o.height,I.style.maxHeight=o.maxHeight};Oo(),Ua(t,c),Hc(t,c),Uc(t,c),ko(),Fo(),va=()=>{Oo(),Io(),Ua(t,c),Hc(t,c),Uc(t,c),ko(),Fo(),ba?t.style.setProperty(`--persona-artifact-welded-outer-radius`,ba):t.style.removeProperty(`--persona-artifact-welded-outer-radius`),ln(),cn()};let Z=[];Z.push(()=>{ga=!0}),Z.push(()=>{S.forEach(e=>e()),x.destroy()}),Z.push(()=>{document.removeEventListener(`keydown`,Ia)}),Z.push(()=>{_r!==null&&clearTimeout(_r)});let Lo=null,Bo=null;Z.push(()=>{Lo?.(),Lo=null,Bo?.(),Bo=null}),_a&&Z.push(()=>{_a?.disconnect(),_a=null}),Z.push(()=>{Ba?.(),Ba=null,fo(),za&&=(za.remove(),null),X?.element.style.removeProperty(`width`),X?.element.style.removeProperty(`maxWidth`),X?.destroy()}),mt&&Z.push(()=>{Xt=!0,Yt=null,en!==null&&(cancelAnimationFrame(en),en=null),Qt?.destroy(),Qt=null,qt?.destroy(),qt=null,Ct=null});let Ho=null,Uo=()=>{Ho&&=(Ho(),null),c.colorScheme===`auto`&&(Ho=Wa(()=>{Ua(t,c)}))};Uo(),Z.push(()=>{Ho&&=(Ho(),null)}),Z.push(()=>{re=!0,ee?.()}),Z.push(()=>{A=!0});let Wo=!1;Z.push(()=>{Wo=!0});let Go=(e,n)=>{let r=Lt(e,n);return r||!Ht.includes(e)?r:(oo().then(r=>{if(Wo)return;Vt(r.wipe),Vt(r.glyphCycle);let i=Lt(e,n);i&&zt(i,t)}).catch(()=>{}),null)},Ko=c.features?.streamAnimation;if(Ko?.type&&Ko.type!==`none`){let e=Go(Ko.type,Ko.plugins);e&&zt(e,t),Z.push(()=>Pt(t))}let qo=So(En),Jo=So(wn),Yo=So(Tn),Xo=[qo,Jo,Yo];Z.push(()=>{Xo.forEach(e=>e.destroy())});let Zo=null,Q,Qo=null,$o=!1,es=0,ts=null,ns=e=>e.reduce((e,t)=>t.role===`user`?e+1:e,0),is=e=>{for(let t=e.length-1;t>=0;t--)if(Qe(e[t]))return e[t].id??null;return null},as=!1,os=()=>{as||c.debug!==!0||(as=!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".`))},cs=!1,ls=!1,us=(e,t)=>{cs||c.debug!==!0||t.enabled&&!t.expose&&($o||ls&&(Q.isStreaming()||e.some(Qe)||(cs=!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.`))))},ds=e=>{if(!Q)return;let t=e??Q.getMessages(),n=e=>{e.render([],Q,V,t)},r=e=>{Xo.forEach(t=>{t!==e&&n(t)})};Qo&&(ns(t)>es||is(t)!==ts)&&(Qo=null);let i=Xe(c);us(t,i);let a=i.enabled?Ze(t):null,o=Qo??a,s=Qo?`host`:`agent`;if(o){let e=c.suggestions?.followUps,n=e?.placement??(e?`auto`:`composer`),i=(n===`auto`?N()?`composer`:`after-message`:n)===`after-message`?Yo:qo;r(i),i.render(o,Q,V,t,c.suggestionChipsConfig,{source:s,surface:`followUp`,variant:e?.variant??`chip`,behavior:e?.behavior??`send`,overflow:e?.overflow??`wrap`,maxItems:e?.maxItems??4,config:c,plugins:g,submitPrompt:Cf});return}if(t.some(e=>e.role===`user`)){Xo.forEach(n);return}let l=c.future?.v5Defaults===!0,u=Cr(),d=c.suggestions?.starters??(l?{}:void 0);if(d){let e=Ns(wr(),t),i=d.placement??`auto`,a=i===`auto`?e?`welcome`:`composer`:i;if(a===`welcome`&&!e){os(),Xo.forEach(n);return}let o=a===`welcome`?Jo:qo;r(o),o.render(d.items??c.suggestionChips,Q,V,t,c.suggestionChipsConfig,{surface:`starter`,variant:d.variant??(l&&!u?`chip`:`card`),behavior:d.behavior??`send`,overflow:d.overflow??`wrap`,maxItems:d.maxItems??(l&&!u?3:4),config:c,plugins:g,submitPrompt:Cf})}else r(qo),qo.render(c.suggestionChips,Q,V,t,c.suggestionChipsConfig,{surface:`starter`,variant:`chip`,behavior:`send`,overflow:`wrap`,maxItems:4,config:c,plugins:g,submitPrompt:Cf})},fs=()=>{Qo&&(Qo=null,ds())},ms=e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length){fs();return}let n=Q?Q.getMessages():[];Qo=t,$o=!0,es=ns(n),ts=is(n),ds(n)},hs=!1,vs=eo(),ys=/* @__PURE__ */ new Map,bs=/* @__PURE__ */ new Map,Cs=/* @__PURE__ */ new Map,Ts=null,Os=null;function ks(){if(!Ts)return;let e=Ts;Ts=null,Os?.destroy(),Os=null,vs.delete(e),R.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),Q&&Ul(B,Q.getMessages(),ut)}let As=0,Ps=ye()!==null,Is=jt(),zs=0,Bs=null,Vs=!1,Hs=!1,Us=0,Ws=null,Gs=null,Ks=!1,qs=!1,Js=null,Ys=!0,Xs=!1,Zs=null,ec=!1,tc=()=>{ec=!0,cc()},rc=null,oc=null,sc=()=>{t.setAttribute(`data-persona-scrollbar`,ur()),ur()!==`on-scroll`&&(oc!==null&&clearTimeout(oc),oc=null,z.removeAttribute(`data-persona-scrollbar-visible`))},cc=()=>{ur()===`on-scroll`&&(z.setAttribute(`data-persona-scrollbar-visible`,``),oc!==null&&clearTimeout(oc),oc=setTimeout(()=>{oc=null,Mt(z,24)&&z.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};sc(),Z.push(()=>{oc!==null&&clearTimeout(oc)});let lc=/* @__PURE__ */ new Map,dc=!1,fc=null,$={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};ra();let pc=c.voiceRecognition?.autoResume??!1,gc=()=>Q.isVoiceActive()||Q.isBargeInActive(),_c=!1,vc=e=>{be.emit(`voice:state`,{active:$.active,source:e,timestamp:Date.now()})},yc=()=>{Re(e=>({...e,voiceState:{active:$.active,timestamp:Date.now(),manuallyDeactivated:$.manuallyDeactivated}}))},Sc=()=>{if(c.voiceRecognition?.enabled===!1)return;let e=vu(Te.voiceState),t=!!e.active,n=Number(e.timestamp??0);$.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-n<3e4&&setTimeout(()=>{$.active||($.manuallyDeactivated=!1,Sn(c.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=gc(),vc(`restore`),$.active?ip():(yc(),ff(`Tap the mic to resume your voice call`,1e4))}):ep(`restore`))},Sn(c.voiceRecognition?.provider)?0:1e3)},Cc=e=>{_c=!e.persisted,$.active&&yc()};typeof window<`u`&&(window.addEventListener(`pagehide`,Cc),Z.push(()=>window.removeEventListener(`pagehide`,Cc)));let Tc=()=>Q?yu(Q.getMessages()).filter(e=>!e.__skipPersist):[],Ec=null,Dc=(e,t)=>{typeof console<`u`&&console.error(e,t)},Oc=(e,t)=>{let n=()=>{try{let n=e();return!n||typeof n.then!=`function`?null:Promise.resolve(n).catch(e=>{Dc(t,e)})}catch(e){return Dc(t,e),null}},r=Ec,i=r?r.then(()=>n()??void 0):n();if(!i)return;let a=i.finally(()=>{Ec===a&&(Ec=null)});Ec=a};function kc(e){if(!xe?.save)return;let t=e?yu(e):Q?Tc():[],n=Ce&&Q?.getResumableHandle();n&&(Te={...Te,durableResume:{executionId:n.executionId,after:n.lastEventId}});let r={messages:t,metadata:Te,artifacts:xa.artifacts,selectedArtifactId:xa.selectedId,...Ac?{draft:Ac}:{}};Oc(()=>xe.save(r),`[AgentWidget] Failed to persist state:`)}let Ac,jc=()=>!xe?.save||c.persistState===!1?!1:typeof c.persistState!=`object`||c.persistState.persist?.draft!==!1,Mc=Wi({write:()=>{if(!jc())return;let e=J.getState(),t=Hi({text:e.text,mentionRefs:e.mentionRefs,contentSegments:sf(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(Ac)&&(Ac=t,kc())}});function Lc(){jc()&&Mc.schedule()}function Rc(){Mc.flush()}function zc(e){if(!jc())return;let t=Ui(e,{mentionSourceIds:(c.contextMentions?.sources??[]).map(e=>e.id),modelIds:(c.composer?.models??[]).map(e=>e.id),modes:c.composer?.modes??[]});t&&(Ac=e,V&&!V.value&&(V.value=t.text,V.dispatchEvent(new Event(`input`,{bubbles:!0})),Fr()),t.selectedModelId&&(J.setSelectedModelId(t.selectedModelId),Gr?.repaint()),Ur(t.activeModeIds??[]),t.quote&&$r(t.quote),Mc.cancel())}function Bc(){Mc.cancel(),Ac&&(Ac=void 0,jc()&&kc())}let Gc=null,Kc=()=>F.querySelector(`#persona-scroll-container`)||z,qc=()=>{Gc!==null&&(cancelAnimationFrame(Gc),Gc=null),Vs=!1},Jc=()=>{Bs!==null&&(cancelAnimationFrame(Bs),Bs=null),Hs=!1,qc()},Yc=()=>hs&&$c()&&(tr()!==`anchor-top`||cr()),Xc=()=>{let e=Qn()||`Jump to latest`,t=Yc();dr.toggleAttribute(`data-persona-scroll-to-bottom-streaming`,t),Us>0?(mr.textContent=String(Us),mr.style.display=``,dr.setAttribute(`aria-label`,`${e} (${Us} new)`)):(mr.textContent=``,mr.style.display=`none`,dr.setAttribute(`aria-label`,t?`${e} (response streaming below)`:e))},Zc=()=>{Us!==0&&(Us=0,Xc())},Qc=()=>{let e=Ws?.spacerHeight??0;return e<=0?Mt(z,24):ml(e)-z.scrollTop-z.clientHeight<=24},$c=()=>nr()?!Is.isFollowing():!Qc(),el=()=>!!Q&&Q.getMessages().length>0,tl=()=>{if(!er()||pn()){dr.parentNode&&dr.remove(),dr.style.display=`none`;return}dr.parentNode!==R&&R.appendChild(dr),Ar();let e=Dt(z)>0&&$c()&&el();e?Xc():Zc(),dr.style.display=e?``:`none`},nl=()=>{Is.pause()&&(Jc(),tl())},rl=()=>{Is.resume(),Zc(),tl()},il=(e=!1)=>{nr()&&el()&&Is.isFollowing()&&(e||hs)&&(Bs!==null&&(cancelAnimationFrame(Bs),Bs=null),Hs=!0,Bs=requestAnimationFrame(()=>{Bs=null,Hs=!1,Is.isFollowing()&&ol(Kc(),e?220:140)}))},al=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(qc(),Math.abs(o)<1){Vs=!0,e.scrollTop=a,zs=e.scrollTop,Vs=!1;return}let s=performance.now();Vs=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){qc();return}let d=t();d!==a&&(a=d,o=a-i);let f=u-s,p=Math.min(f/n,1),m=c(p);e.scrollTop=i+o*m,zs=e.scrollTop,p<1?Gc=requestAnimationFrame(l):(e.scrollTop=a,zs=e.scrollTop,Gc=null,Vs=!1)};Gc=requestAnimationFrame(l)},ol=(e,t=500)=>{let n=Dt(e)-e.scrollTop;Math.abs(n)<1?zs=e.scrollTop:Math.abs(n)>=80?(qc(),Vs=!0,e.scrollTop=Dt(e),zs=e.scrollTop,Vs=!1):al(e,()=>Dt(e),t,()=>Is.isFollowing())},sl=()=>{if(!el()){tl();return}let e=Kc();Vs=!0,e.scrollTop=Dt(e),zs=e.scrollTop,Vs=!1,tl()},cl=e=>{let t=0,n=e;for(;n&&n!==z;)t+=n.offsetTop,n=n.offsetParent;return t},ll=()=>{let e=z.getRootNode();return(typeof e.getSelection==`function`?e.getSelection():null)??z.ownerDocument.getSelection()},ul=()=>Tt(ll(),z),dl=()=>{if(ir()!==`last-user-turn`)return!1;let e=Q?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>e.role===`user`);if(!t)return!1;let n=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(t.id):t.id.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),r=z.querySelector(`[data-message-id="${n}"]`);if(!r)return!1;let i=Math.min(Math.max(0,cl(r)-rr()),Dt(z));return Vs=!0,z.scrollTop=i,zs=z.scrollTop,Vs=!1,tr()===`follow`&&!Mt(z,24)&&Is.pause(),tl(),!0},fl=e=>{let t=Math.max(0,Math.round(e));hr.style.height=`${t}px`,hr.style.display=t>0?``:`none`,Ws&&(Ws.spacerHeight=Math.max(0,e))},ml=e=>{let t=parseFloat(getComputedStyle(z).paddingBottom)||0,n=0;for(let e of Array.from(z.children)){if(e===hr||e.offsetHeight===0)continue;let t=cl(e)+e.offsetHeight;t>n&&(n=t)}let r=z.scrollHeight-e;return n>0?Math.min(n+t,r):r},hl=()=>{if(!Ws||Ws.spacerHeight<=0)return;let e=ml(Ws.spacerHeight),t=Math.max(0,Math.round(z.scrollTop)+z.clientHeight-e+24);t<Ws.spacerHeight&&(fl(t),tl())},gl=()=>{Gs!==null&&(cancelAnimationFrame(Gs),Gs=null),qc(),Ws=null,hr.style.height=`0px`,hr.style.display=`none`},_l=e=>typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),bl=e=>z.querySelector(`[data-message-id="${_l(e)}"]`),xl=e=>{Gs!==null&&cancelAnimationFrame(Gs),Gs=requestAnimationFrame(()=>{Gs=null;let t=_l(e),n=z.querySelector(`[data-message-id="${t}"]`);if(!n)return;let r=cl(n),i=Ws?.spacerHeight??0,a=ml(i),{targetScrollTop:o,spacerHeight:s}=Nt({anchorOffsetTop:r,topOffset:rr(),viewportHeight:z.clientHeight,contentHeight:a,slack:24});Ws={initialSpacerHeight:s,contentHeightAtAnchor:a,spacerHeight:s},fl(s),al(z,()=>n.isConnected?Math.max(0,cl(n)-rr()):o,220)})},Sl=()=>{if(tr()!==`anchor-top`||!Ws||!Zs)return;let e=bl(Zs);if(!e)return;qc();let t=Ws.spacerHeight,n=ml(t),{targetScrollTop:r,spacerHeight:i}=Nt({anchorOffsetTop:cl(e),topOffset:rr(),viewportHeight:z.clientHeight,contentHeight:n,slack:24});Ws={initialSpacerHeight:i,contentHeightAtAnchor:n,spacerHeight:i},fl(i),Vs=!0,z.scrollTop=r,zs=z.scrollTop,Vs=!1,tl()},Cl=()=>{if(nr()){if(!Is.isFollowing()||Mt(z,1))return;il(!hs)}else{if(Ws&&Ws.initialSpacerHeight>0){let e=z.scrollHeight-Ws.spacerHeight,t=kt({initialSpacerHeight:Ws.initialSpacerHeight,contentHeightAtAnchor:Ws.contentHeightAtAnchor,currentContentHeight:e});t!==Ws.spacerHeight&&fl(t)}tl()}},Dl=e=>{let t=tr();t===`follow`?(rl(),il(!0)):t===`anchor-top`&&(Ys=!1,Xs=!0,ec=!1,Zs=e,xl(e))},Ol=()=>{tr()===`anchor-top`&&(Xs?Ys=!1:(Ys=!0,gl(),rl(),il(!0)))},kl=e=>{if(Js===null)return!0;let t=bl(Js),n=bl(e);if(!t||!n)return!0;let r=cl(n)-cl(t);return rr()+r>z.clientHeight-96},Ml=e=>{if(tr()!==`anchor-top`||!Xs||ec||ul())return;let t=Js===null;for(let n of e)if(!t)n.id===Js&&(t=!0);else if(At(n)){if(n.id===Zs||!kl(n.id))return;Zs=n.id,xl(n.id);return}},Nl=e=>{let t=/* @__PURE__ */ new Map;e.forEach(e=>{let n=lc.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!n&&e.role===`assistant`&&(be.emit(`assistant:message`,e),!qs&&(tr()!==`anchor-top`||cr())&&$c()&&(Us+=1,Xc(),tl(),Sr(Us===1?`1 new message below.`:`${Us} new messages below.`))),e.role===`assistant`&&n?.streaming&&e.streaming===!1&&be.emit(`assistant:complete`,e),e.variant===`approval`&&e.approval&&(n?e.approval.status!==`pending`&&be.emit(`approval:resolved`,{approval:e.approval,decision:e.approval.status}):be.emit(`approval:requested`,{approval:e.approval,message:e}))}),lc.clear(),t.forEach((e,t)=>{lc.set(t,e)})},Fl=(e,t)=>{let n=t===`user`?`user`:`assistant`,r=c.layout?.messages?.[n],i=r?.width??`content`,a=r?.maxWidth??(i===`full`?`var(--persona-message-${n}-max-width, 100%)`:void 0);e.classList.add(`persona-message-row`),e.classList.remove(`persona-message-row-user`,`persona-message-row-assistant`,`persona-message-row-system`,`persona-message-width-content`,`persona-message-width-full`),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${i}`),e.classList.toggle(`persona-justify-end`,t===`user`),e.setAttribute(`data-message-role`,t),e.setAttribute(`data-message-width`,i),a?e.style.setProperty(`--persona-message-row-max-width`,a):e.style.removeProperty(`--persona-message-row-max-width`)},Ll=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),Fl(n,t),n},zl=(e,t,n)=>{let r=/* @__PURE__ */ new Set;for(let e of t){let t=e.variant===`tool`?`tool`:e.variant===`reasoning`?`reasoning`:null;if(!t||gn(c,t)!==`row`)continue;let n=t===`tool`?c.features?.toolCallDisplay:c.features?.reasoningDisplay;n?.expandable!==!1&&(r.add(e.id),f.observe(e,t,t===`tool`?u:d,n))}let i=document.createElement(`div`),a=(()=>{let e=g.find(e=>e.renderLoadingIndicator);if(e?.renderLoadingIndicator)return e.renderLoadingIndicator;if(c.loadingIndicator?.render)return c.loadingIndicator.render})(),o=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),s=/* @__PURE__ */ new Set,l=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Set,h=g.some(e=>e.renderAskUserQuestion),_=[],v=[],y=c.enableComponentStreaming!==!1,b=c.approval!==!1,x=[],S=c.messageActions,C=S?.showRegenerate===!0&&S.enabled!==!1&&Oa.current?.isStreaming()!==!0?yr(t):null,w=S?.showEdit===!0&&S.enabled!==!1,T=S?.showQuote===!0&&S.enabled!==!1,E=null,D=c.features?.reasoningDisplay?.completedVisibility,O=e=>D===`removed`||D===`removed-when-short`&&Ne(e,c.features?.reasoningDisplay?.shortThinkThreshold),ee=c.features?.toolCallDisplay?.completedVisibility===`removed`,te=e=>e.variant===`reasoning`&&e.reasoning?.status===`complete`?O(e.reasoning):ee&&e.variant===`tool`&&e.toolCall?.status===`complete`;if(t.forEach(t=>{if(te(t))return;if(s.add(t.id),l.set(t.id,t.role),Ts===t.id&&Os){let e=Ll(t.id,t.role);e.setAttribute(`data-persona-message-edit-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),i.appendChild(e),E={messageId:t.id,element:Os.element};return}let r=h&&Je(t),o=b&&t.variant===`approval`&&!!t.approval,f=!r&&t.role===`assistant`&&!t.variant&&y&&au(t);!o&&Cs.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),Cs.delete(t.id)),!f&&bs.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),bs.delete(t.id));let S=Je(t)?`:${t.agentMetadata?.askUserQuestionAnswered?`a`:`u`}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:``,D={canRegenerate:C===t.id,canEdit:w&&br(t),canQuote:T&&!t.variant&&(t.content?.trim().length??0)>0},O=`${D.canRegenerate?`r`:``}${D.canEdit?`e`:``}${D.canQuote?`q`:``}`,ee=$a(t,As)+S+`:${O}`,ne=r||o||f?null:to(vs,t.id,ee);if(ne){i.appendChild(ne.cloneNode(!0)),Je(t)&&t.toolCall?.id&&t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),ja(t));return}let re=null,ie=g.find(e=>!!(t.variant===`reasoning`&&e.renderReasoning||t.variant===`tool`&&e.renderToolCall||!t.variant&&e.renderMessage)),ae=c.layout?.messages;if(Je(t)&&t.agentMetadata?.askUserQuestionAnswered===!0){ys.delete(t.id),e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`);return}if(Qe(t)&&Xe(c).enabled)return;if(Je(t)&&c.features?.askUserQuestion?.enabled!==!1){let e=g.find(e=>typeof e.renderAskUserQuestion==`function`);if(e&&Oa.current){let n=ys.get(t.id),r=n!==ee,a=null;if(r){let{payload:n,complete:r}=Ye(t),i=t.id,o=()=>Oa.current?.getMessages().find(e=>e.id===i);a=e.renderAskUserQuestion({message:t,payload:n,complete:r,resolve:e=>{let t=o();t&&Oa.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=o();e?.agentMetadata?.awaitingLocalTool&&(Oa.current?.markAskUserQuestionResolved(e),Oa.current?.resolveAskUserQuestion(e,`(dismissed)`))},config:c})}if(r&&a===null&&n==null){t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),ja(t));return}let o=Ll(t.id,t.role);o.setAttribute(`data-ask-plugin-stub`,`true`),o.setAttribute(`data-preserve-runtime`,`true`),i.appendChild(o),_.push({messageId:t.id,fingerprint:ee,bubble:a});return}t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),ja(t));return}if(o){let n=pe();if(!n){i.appendChild(Ll(t.id,t.role));return}let r=g.find(e=>typeof e.renderApproval==`function`)??k,a=Cs.get(t.id)!==ee,o=null;if(a&&r?.renderApproval){let e=t.id,i=(t,n)=>{let r=Oa.current?.getMessages().find(t=>t.id===e);r?.approval&&(r.approval.toolType===`webmcp`?Oa.current?.resolveWebMcpApproval(r.id,t):Oa.current?.resolveApproval(r.approval,t,n))};o=r.renderApproval({message:t,defaultRenderer:()=>n.createApprovalBubble(t,c,p),config:c,approve:e=>i(`approved`,e),deny:e=>i(`denied`,e)})}if(a&&o===null)e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),Cs.delete(t.id),re=n.createApprovalBubble(t,c,p);else{let e=Ll(t.id,t.role);e.setAttribute(`data-approval-plugin-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),i.appendChild(e),x.push({messageId:t.id,fingerprint:ee,bubble:o});return}}else if(ie){if(t.variant===`reasoning`&&t.reasoning&&ie.renderReasoning){if(!dt)return;re=ie.renderReasoning({message:t,defaultRenderer:()=>ac(t,c,d),config:c})}else if(t.variant===`tool`&&t.toolCall&&ie.renderToolCall){if(!pt)return;re=ie.renderToolCall({message:t,defaultRenderer:()=>hc(t,c,u),config:c})}else ie.renderMessage&&(re=ie.renderMessage({message:t,defaultRenderer:()=>{let e=ps(t,n,ae,c.messageActions,mn,{loadingIndicatorRenderer:a,widgetConfig:c,actionEligibility:D});return t.role!==`user`&&_e(e,t,c,Q),e},config:c}))}if(!re&&f){let r=ou(t);if(r){let a=bs.get(t.id),o=a!==ee,s=c.wrapComponentDirectiveInBubble!==!1&&Ee.getOptions(r.component)?.bubbleChrome!==!1,l=null;if(o){let i=ru(r,{config:c,message:t,transform:n});if(i&&r.component===`PersonaArtifactInline`){let n=i.hasAttribute(`data-artifact-inline`)?i:i.querySelector(`[data-artifact-inline]`),r=n?.getAttribute(`data-artifact-inline`)??``,a=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(r):r,o=r?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${a}"]`)??null:null;n&&o&&o!==n&&Pc()?.hasLiveInlineArtifactBlock(o)&&(n===i?i=o:n.replaceWith(o))}if(i){if(s){let e=document.createElement(`div`);if(e.className=[`persona-message-bubble`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-p-4`].join(` `),e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-mb-3 persona-text-sm persona-leading-relaxed`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(i),l=e}else{let e=document.createElement(`div`);if(e.className=`persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch`,e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),e.setAttribute(`data-persona-component-directive`,`true`),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(i),l=e}}}if(l||a!=null){let e=Ll(t.id,t.role);e.setAttribute(`data-component-directive-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),i.appendChild(e),v.push({messageId:t.id,fingerprint:ee,bubble:l});return}}}if(!re){if(t.variant===`reasoning`&&t.reasoning){if(!dt)return;re=ac(t,c,d)}else if(t.variant===`tool`&&t.toolCall){if(!pt)return;re=hc(t,c,u)}else if(t.variant===`approval`&&t.approval){if(c.approval===!1)return;let e=pe();if(!e)return;re=e.createApprovalBubble(t,c,p)}else{let e=c.layout?.messages;re=e?.renderUserMessage&&t.role===`user`?e.renderUserMessage({message:t,config:c,streaming:!!t.streaming}):e?.renderAssistantMessage&&t.role===`assistant`?e.renderAssistantMessage({message:t,config:c,streaming:!!t.streaming}):ps(t,n,e,c.messageActions,mn,{loadingIndicatorRenderer:a,widgetConfig:c,actionEligibility:D}),t.role!==`user`&&re&&_e(re,t,c,Q)}}let oe=Ll(t.id,t.role);oe.appendChild(re),no(vs,t.id,ee,oe),i.appendChild(oe)}),L.composerOverlay&&L.composerOverlay.querySelectorAll(`[data-persona-ask-sheet-for]`).forEach(e=>{let t=e.getAttribute(`data-persona-ask-sheet-for`);t&&!m.has(t)&&Ke(L.composerOverlay,t)}),c.features?.toolCallDisplay?.grouped){let e=[],n=[],a=c.features.toolCallDisplay.groupedMode===`summary`;t.forEach(t=>{if(t.variant===`tool`&&t.toolCall&&pt){if(ee&&t.toolCall.status===`complete`)return;n.push(t)}else(t.variant!==`reasoning`||dt&&(t.reasoning?.status!==`complete`||!O(t.reasoning)))&&((n.length>1||a&&n.length>0)&&e.push(n),n=[])}),(n.length>1||a&&n.length>0)&&e.push(n),e.forEach(e=>{let t=e.map(e=>Array.from(i.children).find(t=>t instanceof HTMLElement&&t.getAttribute(`data-wrapper-id`)===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let n=Ll(`tool-group-${e[0].id}`,`assistant`);if(n.setAttribute(`data-persona-tool-group-row`,`true`),c.features?.toolCallDisplay?.groupedMode===`collapsible`){let i=`tool-group-${e[0].id}`,a=e.some(e=>e.toolCall?.status!==`complete`),o={...e[0],id:i,toolCall:{id:i,name:`${e.length} tools`,status:a?`running`:`complete`,chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>e.toolCall?.success===!1)}};r.add(i),f.observe(o,`tool`,u,c.features.toolCallDisplay);let s=`${a?`Using`:`Used`} ${e.length} tools`,l=c.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:s,config:c}),d=bn(o,c,u.has(i),l??s);d.bubble.classList.add(`persona-tool-group`),d.body.dataset.personaToolGroupStack=`true`,t[0].before(n),n.appendChild(d.bubble),t.forEach((e,t)=>{e.style.setProperty(`--persona-message-row-max-width`,`100%`),e.style.setProperty(`--persona-activity-stagger`,`${t*40}ms`),e.classList.add(`persona-activity-group-child`),d.body.appendChild(e)});return}let s=document.createElement(`div`);s.className=`persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2`,s.setAttribute(`data-persona-tool-group`,`true`);let l=document.createElement(`div`);l.className=`persona-tool-group-summary persona-text-xs persona-text-persona-muted`,l.id=`tool-group-summary-${e[0].id}`;let d=`Called ${e.length} ${e.length===1?`tool`:`tools`}`,p=c.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:d,config:c});o(l,p)||(l.textContent=d);let m=document.createElement(`div`);m.className=`persona-tool-group-stack persona-flex persona-flex-col`,m.id=`tool-group-stack-${e[0].id}`,m.setAttribute(`data-persona-tool-group-stack`,`true`),s.appendChild(l),a||s.appendChild(m),n.appendChild(s),t[0].before(n),t.forEach((e,n)=>{if(a){e.remove();return}e.style.setProperty(`--persona-message-row-max-width`,`100%`);let r=document.createElement(`div`);r.className=`persona-tool-group-item persona-relative`,r.setAttribute(`data-persona-tool-group-item`,`true`),n<t.length-1&&r.setAttribute(`data-persona-tool-group-connector`,`true`),r.appendChild(e),m.appendChild(r)})})}f.prune(r),ro(vs,s);let ne=e=>e.variant===`tool`&&!pt||e.variant===`reasoning`&&!dt||te(e),re=t.some(e=>e.role===`assistant`&&e.streaming&&!ne(e)),ie=t.length-1;for(;ie>=0&&ne(t[ie]);)ie--;let ae=ie>=0?t[ie]:void 0,oe=ie<t.length-1,se=ae?.role===`assistant`&&!ae.streaming&&ae.variant!==`approval`&&!oe;if(hs&&t.some(e=>e.role===`user`)&&!re&&!se){let e={config:c,streaming:!0,location:`standalone`,defaultRenderer:rs},t=g.find(e=>e.renderLoadingIndicator),n=null;if(t?.renderLoadingIndicator&&(n=t.renderLoadingIndicator(e)),n===null&&c.loadingIndicator?.render&&(n=c.loadingIndicator.render(e)),n===null&&(n=rs()),n){let e=document.createElement(`div`),t=c.loadingIndicator?.showBubble!==!1,r=c.layout?.messages?.layout??`bubble`;e.className=t?ss(`assistant`,r).join(` `):[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-text`].join(` `),e.setAttribute(`data-typing-indicator`,`true`),t&&(e.style.color=`var(--persona-message-assistant-text, var(--persona-text))`,r!==`flat`&&(e.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,e.style.borderColor=`var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))`)),e.appendChild(n);let a=Ll(`typing-indicator`,`assistant`);a.appendChild(e),i.appendChild(a)}}if(!hs&&t.length>0){let e=t[t.length-1],n={config:c,lastMessage:e,messageCount:t.length},r=g.find(e=>e.renderIdleIndicator),a=null;if(r?.renderIdleIndicator&&(a=r.renderIdleIndicator(n)),a===null&&c.loadingIndicator?.renderIdle&&(a=c.loadingIndicator.renderIdle(n)),a){let e=document.createElement(`div`);e.className=c.loadingIndicator?.showBubble===!1?[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-primary`].join(` `):[`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(` `),e.setAttribute(`data-idle-indicator`,`true`),e.appendChild(a);let t=Ll(`idle-indicator`,`assistant`);t.appendChild(e),i.appendChild(t)}}if(Dn(i),Ya(e,i),On(e),E){let{messageId:t,element:n}=E,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(Fl(r,l.get(t)??`user`),r.replaceChildren(n))}if(_.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of _){let i=e.querySelector(`#wrapper-${t}`);i&&(Fl(i,l.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),ys.set(t,n)))}if(ys.size>0)for(let e of ys.keys())s.has(e)||ys.delete(e);if(v.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of v){let i=e.querySelector(`#wrapper-${t}`);i&&(Fl(i,l.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),bs.set(t,n)))}if(bs.size>0)for(let e of bs.keys())s.has(e)||bs.delete(e);if(x.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of x){let i=e.querySelector(`#wrapper-${t}`);i&&(Fl(i,l.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),Cs.set(t,n)))}if(Cs.size>0)for(let e of Cs.keys())s.has(e)||Cs.delete(e)},Bl=!1,Vl=()=>{Bl||(Bl=!0,Mn().catch(()=>{}),we().catch(()=>{Bl=!1}))},Ul=(e,t,n)=>{t.length>0&&Vl(),zl(e,t,n),pa()},Wl=null,Gl=()=>{if(Wl)return;let e=e=>{let t=e.composedPath();t.includes(F)||Cn&&t.includes(Cn)||wu(!1,`user`)};Wl=e,(t.ownerDocument??document).addEventListener(`pointerdown`,e,!0)},ql=()=>{Wl&&=((t.ownerDocument??document).removeEventListener(`pointerdown`,Wl,!0),null)};Z.push(()=>ql());let Jl=null,Xl=()=>{if(Jl)return;let e=e=>{e.key===`Escape`&&(e.isComposing||wu(!1,`user`))};Jl=e,(t.ownerDocument??document).addEventListener(`keydown`,e,!0)},Zl=()=>{Jl&&=((t.ownerDocument??document).removeEventListener(`keydown`,Jl,!0),null)};Z.push(()=>Zl());let Ql=!1,$l=/* @__PURE__ */ new Set,iu=()=>c.launcher?.composerBar?.peek?.streamAnimation||c.features?.streamAnimation,su=()=>{if(!N())return;let e=L.peekBanner,n=L.peekTextNode;if(!e||!n)return;if(P){e.classList.remove(`persona-pill-peek--visible`);return}let r=Q?.getMessages()??[],i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.role===`assistant`&&t.content){i=t;break}}if(!i){e.classList.remove(`persona-pill-peek--visible`);return}let a=i.content,o=!!i.streaming,s=iu(),c=Ft(s),l=c.type===`none`?null:Go(c.type,s?.plugins),u=l?.isAnimating?.(i)===!0,d=l!==null&&(o||u);d&&l&&!$l.has(l.name)&&(zt(l,t),$l.add(l.name));let f=d&&l?.containerClass?l.containerClass:null,p=n.dataset.personaPeekStreamClass??null;p&&p!==f&&(n.classList.remove(p),delete n.dataset.personaPeekStreamClass),f&&p!==f&&(n.classList.add(f),n.dataset.personaPeekStreamClass=f),d?(n.style.setProperty(`--persona-stream-step`,`${c.speed}ms`),n.style.setProperty(`--persona-stream-duration`,`${c.duration}ms`)):(n.style.removeProperty(`--persona-stream-step`),n.style.removeProperty(`--persona-stream-duration`));let m=d?Rt(a,c.buffer,l,i,o):a;if(d&&c.placeholder===`skeleton`&&o&&(!m||!m.trim())){let e=document.createElement(`div`),t=Bt();t.classList.add(`persona-pill-peek__skeleton`),e.appendChild(t),Ya(n,e)}else{let t=Math.max(0,m.length-100),r=m.length>100?m.slice(-100):m,a=ve(r);if(!d||!l){let e=m.length>100?`…${r}`:r;n.textContent!==e&&(n.textContent=e)}else{let o=a;(l.wrap===`char`||l.wrap===`word`)&&(o=Ut(a,l.wrap,`peek-${i.id}`,{skipTags:l.skipTags,startIndex:t}));let s=document.createElement(`div`);if(s.innerHTML=o,l.useCaret&&r.length>0){let e=It(),t=s.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];n?.parentNode?n.parentNode.insertBefore(e,n.nextSibling):s.appendChild(e)}Ya(n,s),l.onAfterRender?.({container:n,bubble:e,messageId:i.id,message:i,speed:c.speed,duration:c.duration})}}let h=hs||Ql;e.classList.toggle(`persona-pill-peek--visible`,h)};if(N()){let e=L.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),wu(!0,`user`)};e.addEventListener(`pointerdown`,t),Z.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{Ql||(Ql=!0,su())},n=()=>{Ql&&(Ql=!1,su())};I.addEventListener(`pointerenter`,t),I.addEventListener(`pointerleave`,n),Z.push(()=>{I.removeEventListener(`pointerenter`,t),I.removeEventListener(`pointerleave`,n)}),Cn&&(Cn.addEventListener(`pointerenter`,t),Cn.addEventListener(`pointerleave`,n),Z.push(()=>{Cn.removeEventListener(`pointerenter`,t),Cn.removeEventListener(`pointerleave`,n)}))}let pu=e=>{let t=c.launcher?.composerBar??{},n=t.expandedSize??`anchored`,r=t.bottomOffset??`16px`,i=t.collapsedMaxWidth,a=t.expandedMaxWidth??`880px`,o=t.expandedTopOffset??`5vh`,s=t.modalMaxWidth??`880px`,l=t.modalMaxHeight??`min(90vh, 800px)`,u=`calc(100vw - 32px)`,d=F.style;if(d.left=``,d.right=``,d.top=``,d.bottom=``,d.transform=``,d.width=``,d.maxWidth=``,d.height=``,d.maxHeight=``,Cn){let e=Cn.style;e.bottom=r,e.width=i??``}e&&n!==`fullscreen`&&(n===`modal`?(d.top=`50%`,d.left=`50%`,d.transform=`translate(-50%, -50%)`,d.bottom=`auto`,d.right=`auto`,d.width=s,d.maxWidth=u,d.maxHeight=l,d.height=l):(d.left=`50%`,d.transform=`translateX(-50%)`,d.bottom=`calc(${r} + var(--persona-pill-area-height, 80px))`,d.top=o,d.width=a,d.maxWidth=u))},Su=()=>{if(P&&Vl(),!at())return;if(N()){let e=(c.launcher?.composerBar??{}).expandedSize??`anchored`,t=P?`expanded`:`collapsed`;F.dataset.state=t,F.dataset.expandedSize=e,Cn&&(Cn.dataset.state=t,Cn.dataset.expandedSize=e),F.style.removeProperty(`display`),F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-95`,`persona-opacity-0`,`persona-scale-100`,`persona-opacity-100`),pu(P),R.style.display=P?`flex`:`none`,va(),P?(Gl(),Xl()):(ql(),Zl()),su();return}let e=po(c),n=t.ownerDocument.defaultView??window,r=c.launcher?.mobileBreakpoint??640,i=c.launcher?.mobileFullscreen??!0,a=n.innerWidth<=r,o=i&&a&&He,s=ho(c).reveal;P?(F.style.removeProperty(`display`),F.style.display=e?`flex`:``,F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-95`,`persona-opacity-0`),I.classList.add(`persona-scale-100`,`persona-opacity-100`),Sp?(Sp.setPanelOpen(!0),Sp.element.style.display=`none`):Cp&&(Cp.style.display=`none`)):(e?e&&(s===`overlay`||s===`push`)&&!o?(F.style.removeProperty(`display`),F.style.display=`flex`,F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(F.style.setProperty(`display`,`none`,`important`),F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(F.style.display=``,F.classList.add(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-100`,`persona-opacity-100`),I.classList.add(`persona-scale-95`,`persona-opacity-0`)),Sp?(Sp.setPanelOpen(!1),Sp.element.style.display=e?`none`:``):Cp&&(Cp.style.display=e?`none`:``))},wu=(e,n=`user`)=>{if(!at()||P===e)return;let r=P;P=e,Su();let i=(()=>{let e=c.launcher?.sidebarMode??!1,n=t.ownerDocument.defaultView??window,r=c.launcher?.mobileFullscreen??!0,i=c.launcher?.mobileBreakpoint??640,a=n.innerWidth<=i,o=po(c)&&r&&a,s=N()&&(c.launcher?.composerBar?.expandedSize??`fullscreen`)===`fullscreen`;return e||r&&a&&He||o||s})();if(P&&i){if(!Lo){let e=t.getRootNode(),n=e instanceof ShadowRoot?e.host:t.closest(`.persona-host`);n&&(Lo=so(n,c.launcher?.zIndex??1e5))}Bo||=uo(t.ownerDocument)}else P||(Lo?.(),Lo=null,Bo?.(),Bo=null);P&&(Dp(),dl()||(tr()===`follow`?il(!0):sl()));let a={open:P,source:n,timestamp:Date.now()};P&&!r?be.emit(`widget:opened`,a):!P&&r&&be.emit(`widget:closed`,a),be.emit(`widget:state`,{open:P,launcherEnabled:He,voiceActive:$.active,streaming:Q.isStreaming()})},Tu={inputDisabled:!1,sendDisabled:!1},Eu=()=>Tu.inputDisabled,Du=()=>Sn(c.voiceRecognition?.provider)&&!!Q&&(Q.isBargeInActive()||[`listening`,`processing`,`speaking`].includes(Q.getVoiceStatus())),Ou=()=>Tu.inputDisabled||Tu.sendDisabled,ku=()=>(Tu.inputDisabled?Tu.inputReason:void 0)??(Tu.sendDisabled?Tu.sendReason:void 0);function Au(){if(!H)return;if(J.getState().phase===`streaming`){H.disabled=!1;return}let e=q?!q.isReady():!1;H.disabled=Ou()||e}function ju(){if(!Wn)return;let e=J.getState(),t=c.sendButton?.visibility===`when-text`&&e.phase!==`streaming`&&e.text.trim().length===0&&e.attachments.length===0;Wn.toggleAttribute(`data-persona-send-hidden`,t)}function Mu(){let e=ku();if(N()){let t=kn??G;e?t.setAttribute(`title`,e):t.removeAttribute(`title`),G.toggleAttribute(du,!!e)}else if(e)U.setAttribute(`role`,`status`),U.setAttribute(`aria-live`,`polite`),U.setAttribute(du,``),U.removeAttribute(fu),U.textContent=e,i(U,c.statusIndicator??{},`idle`);else if(U.hasAttribute(du)&&(U.removeAttribute(`role`),U.removeAttribute(`aria-live`),U.removeAttribute(du),C)){let e=Q.getStatus();vn(U,hn(e),c.statusIndicator??{},e)}}function Nu(){let e=b(c.composer?.inputDisabled),t=b(c.composer?.sendDisabled);Tu={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},J.setInputDisabled(e.disabled),J.setSendDisabled(t.disabled);let n=J.getState().phase===`streaming`,r=e.disabled,i=n||r;V&&(V instanceof HTMLTextAreaElement?V.disabled=r:V.setAttribute(`contenteditable`,r?`false`:`true`),V.setAttribute(`aria-disabled`,r?`true`:`false`)),Jn&&(Jn.disabled=r),Xn&&(Xn.disabled=r);for(let e of Pr?.affordanceButtons??[])e.querySelectorAll(`button`).forEach(e=>{e.disabled=r});K&&(K.disabled=r||n&&!Du()),Xo.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute(`data-disabled`,i),e instanceof HTMLButtonElement||e.setAttribute(`aria-disabled`,i?`true`:`false`)}),e.buttons.forEach(e=>{e.disabled=i})}),Xu.forEach(e=>{e.toggleAttribute(`data-disabled`,i),e instanceof HTMLButtonElement?e.disabled=i:e.setAttribute(`aria-disabled`,i?`true`:`false`),e.querySelectorAll(`button`).forEach(e=>{e.disabled=i})}),G.dataset.personaComposerStreaming=n?`true`:`false`,G.dataset.personaComposerInputDisabled=r?`true`:`false`,G.dataset.personaComposerSendDisabled=Ou()?`true`:`false`,G.querySelectorAll(`[data-persona-composer-disable-when-streaming]`).forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=n)}),Au(),Mu()}let Pu=e=>{J.setStreaming(e),Gn(e?`stop`:`send`),Nu()},Fu=()=>{$.active||V&&V.focus()};be.on(`widget:opened`,()=>{c.autoFocusInput&&setTimeout(()=>Fu(),200)});let Iu=null,Lu=!1,Ru=!An.hidden,zu=null,Bu=!De,Vu=null;Z.push(()=>{Vu?.cancel(),Vu=null});let Hu=e=>{let n=Ms(e);if(n===Tr)return;Tr=n,t.setAttribute(`data-persona-conversation-state`,n);let r=Dr();Mr(),Bu&&(Vu?.cancel(),Vu=Ds(G,n===`active`?r:Dr(),n===`active`?`drop`:`rise`,wr().layout===`centered`?320:260)),Sl()},Uu=null,Wu,Gu=null,Ku=null,qu=!1,Ju=e=>{let t=wr(),n=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??`bottom`}|${t.align??``}|${t.iconPlacement}|${t.kicker??``}|${t.title}|${t.subtitle}`;(n!==Uu||t.icon!==Wu)&&(Uu=n,Wu=t.icon,_s({host:An,iconHolder:jn,kicker:Pn,title:Fn,subtitle:In,starterSuggestions:wn},t));let r=t.message===void 0?null:`${c.layout?.messages?.layout??`bubble`}|${t.message}`;r!==Gu&&(Gu=r,ws(Nn,t.message,c));let i=e??(Q?Q.getMessages():c.initialMessages);Hu(i);let a=Lu,o=!a&&Ns(t,i),s=o!==Ru;if(Ru=o,Ku){zu?.cancel(),zu=null,a!==qu&&(qu=a,a?Ss(z,An,null):xs(z,An,Ku)),gs(z,An,!a);return}if(s&&!o&&!a&&t.dismiss===`on-first-message`&&Bu){zu=Es(An,e=>{zu===e&&(zu=null),!Ru&&!Ku&&(gs(z,An,!1),Sl()),e?.cancel()});return}if(zu){if(!o&&!a)return;zu.cancel(),zu=null}let l=!An.hidden;gs(z,An,o),!o&&l&&Sl()},Yu=[],Xu=[],Zu=!1,Qu=null,$u,ed=()=>{Xu.length=0;let e=Yu.splice(0,Yu.length);for(let t of e)try{t()}catch(e){console.warn(`[persona] renderWelcome cleanup threw`,e)}};Z.push(ed);let td=(e,t)=>{let n=_o(e,t);if(!n)return c.debug===!0&&console.warn(`[persona] renderStarter received a suggestion with no label`),j(`span`);let r=c.suggestions?.starters,i=xo({item:{...n,behavior:n.behavior??r?.behavior??`send`},index:t,surface:`starter`,source:`config`,variant:r?.variant??`card`,streaming:C?Q.isStreaming():!1,config:c,plugins:g,chipsConfig:c.suggestionChipsConfig,session:Q,getTextarea:()=>V,eventTarget:An,submitPrompt:Cf});return Xu.push(i),i},nd=()=>{if(Zu)return;Zu=!0;let e=wr();Qu=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`,$u=e.icon;try{ed(),Ss(z,An,Ku),Ku=null,qu=!1;let t=Q?Q.getMessages():c.initialMessages,n=Ns(e,t),r=0,i=null;for(let t of g)if(t.renderWelcome&&(i=t.renderWelcome({config:e,variant:e.variant,visible:n,defaultRenderer:()=>An,sendMessage:e=>{if(!Q||Q.isStreaming())return;let t=e.trim();t&&Q.sendMessage(t)},requestRender:()=>nd(),renderStarter:e=>td(e,r++),storage:D(t.id),onCleanup:e=>{Yu.push(e)}}),i))break;i&&i!==An&&(Ku=i,xs(z,An,i))}finally{Zu=!1}Ju()},rd=()=>{let e=wr();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`!==Qu||e.icon!==$u)&&nd()},id=()=>{Ju(),mi||(V.placeholder=Li(J.getState().activeModeIds,c.composer?.modes)??c.copy?.inputPlaceholder??`How can I help...`,!(c.sendButton?.useIcon??!1)&&!Q?.isStreaming()&&(H.textContent=c.copy?.sendButtonLabel??`Send`)),V.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,V.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`},ad=!!c.setStoredConversationId,od=e=>Re(t=>{let n={...t};return delete n[e],n}),sd=e=>{let t=Te[e];return typeof t==`string`?t:null},cd=()=>{let e=Te.durableResume;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.executionId==`string`&&t.executionId.length>0&&typeof t.after==`string`&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};c.clientToken&&(c={...c,getStoredSessionId:()=>sd(`sessionId`),setStoredSessionId:e=>{Re(t=>({...t,sessionId:e}))},clearStoredSessionId:c.clearStoredSessionId??(()=>od(`sessionId`)),getStoredConversationId:c.getStoredConversationId??(()=>sd(`conversationId`)),setStoredConversationId:c.setStoredConversationId??(e=>{Re(t=>({...t,conversationId:e}))}),clearStoredConversationId:c.clearStoredConversationId??(()=>od(`conversationId`))});let ld=()=>c.clientToken??null,ud=e=>Kl(e,yt(),c.persistState===!1),dd=ld(),fd=dd?ud(dd):null,pd=()=>{let e=Te.pendingDisplayProjections;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.conversationId!=`string`||!Array.isArray(t.messageIds)?null:{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>typeof e==`string`)}},md={...fd?{visitorStore:fd}:{},historyBootstrapReady:c.features?.history?.enabled===!0&&!tu()?Promise.all([Ae,Me]).then(()=>{}):Ae,getStoredMessageCursor:()=>sd(`historyMessageCursor`),setStoredMessageCursor:e=>{e===null?od(`historyMessageCursor`):Re(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:pd,setPendingDisplayProjections:e=>{e?Re(t=>({...t,pendingDisplayProjections:e})):od(`pendingDisplayProjections`)},getStoredResumableHandle:cd,setStoredResumableHandle:e=>{e?Re(t=>({...t,durableResume:e})):od(`durableResume`)},shouldResumeDurableConversation:()=>Ce&&cd()!==null,...ad?{}:{getStoredConversationRevision:()=>sd(`conversationRevision`),setStoredConversationRevision:e=>{e===null?od(`conversationRevision`):Re(t=>({...t,conversationRevision:e}))}}};if(Ce){let e=c.onExecutionState,n=t.ownerDocument.defaultView,r=!1,i=()=>r=!0,a=()=>r=!1;n?.addEventListener(`pagehide`,i),n?.addEventListener(`pageshow`,a),Z.push(()=>{n?.removeEventListener(`pagehide`,i),n?.removeEventListener(`pageshow`,a)}),c={...c,reconnectStream:c.reconnectStream??(e=>Q.getClient().reconnectClientTokenStream(e)),onExecutionState:t=>{(t||!r)&&md.setStoredResumableHandle?.(t?{executionId:t.executionId,after:t.lastEventId}:null),e?.(t)}}}let hd=()=>{let e=ld();if(e&&fd?.matches(e,yt(),c.persistState===!1)||!e&&!fd)return;fd?.destroy(),fd=e?ud(e):null;let t={...md};fd?t.visitorStore=fd:delete t.visitorStore,md=t,Q.setHistoryInternals(md)},gd=null,_d=()=>{gd??=setInterval(()=>{let e=B.querySelectorAll(`[data-tool-elapsed]`);if(e.length===0){clearInterval(gd),gd=null;return}let t=Date.now();e.forEach(e=>{let n=Number(e.getAttribute(`data-tool-elapsed`));n&&(e.textContent=e.closest(`.persona-activity-row`)?_n(t-n):Ue(t-n))})},100)},vd=(e,t)=>{if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>vd(e,t[n]));let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.prototype.hasOwnProperty.call(r,e)&&vd(n[e],r[e]))},yd=e=>{let{content:t,rawContent:n,llmContent:r,...i}=e;return i},bd=e=>e.role===`assistant`&&e.streaming===!0&&!e.variant&&!e.toolCall&&!e.tools&&!e.approval&&!e.reasoning&&!e.contentParts&&!e.stopReason&&!au(e),xd=(e,t,n)=>{if(e.length!==t.length)return!1;let r=e[n.index],i=t[n.index];return!r||!i||r.id!==n.id||i.id!==n.id?!1:(!Object.is(r.content,i.content)||!Object.is(r.rawContent,i.rawContent)||!Object.is(r.llmContent,i.llmContent))&&bd(r)&&bd(i)&&vd(yd(r),yd(i))},Sd=null,Cd=null,wd=null,Td=null,Ed=null,Dd=e=>{if(!Ce)return kc(e);Ed=e,queueMicrotask(()=>{Ed===e&&(Ed=null,kc(e))})},Od=e=>{Sd=e;let t,n;Cd=null;for(let r=e.length-1;r>=0;--r){let i=e[r];if(!t&&i.role===`user`&&(t=i),!n&&i.role===`assistant`&&(n=i),!Cd&&bd(i)&&(Cd={index:r,id:i.id}),t&&n&&Cd)break}Ul(B,e,ut),Pc()?.updateInlineArtifactBlocks(B,xa.artifacts,{suppressTransition:hs}),_d(),Ju(e),ds(e),il(!hs),Nl(e),e.length===0&&(gl(),Ys=!0,Xs=!1,Zs=null,ec=!1),!Ks||qs?(Ks=!0,Js=t?.id??null,rc=n?.id??null):t&&t.id!==Js?(Js=t.id,Dl(t.id)):n&&n.id!==rc&&Ol(),n&&(rc=n.id),Ml(e);let r=$.lastUserMessageId;t&&t.id!==r&&($.lastUserMessageId=t.id,be.emit(`user:message`,t)),$.lastUserMessageWasVoice=!!t?.viaVoice,Dd(e),su()},kd=()=>{Td!==null&&(cancelAnimationFrame(Td),Td=null);let e=wd;wd=null,e&&Od(e)},Ad=()=>{Td!==null&&cancelAnimationFrame(Td),Td=null,wd=null},jd=e=>{let t=wd??Sd;hs&&t&&Cd&&xd(t,e,Cd)?(wd=e,Td===null&&(Td=requestAnimationFrame(()=>{Td=null;let e=wd;wd=null,e&&Od(e)}))):e.length===0?(Ad(),Od(e)):(kd(),Od(e))};Q=new Br(c,{onMessagesChanged(e){jd(e)},onStatusChanged(e){let t=c.statusIndicator??{};vn(U,(e=>e===`idle`?t.idleText??gt.idle:e===`connecting`?t.connectingText??gt.connecting:e===`connected`?t.connectedText??gt.connected:e===`error`?t.errorText??gt.error:e===`paused`?t.pausedText??gt.paused:e===`resuming`?t.resumingText??gt.resuming:gt[e])(e),t,e),fn()},onStreamingChanged(e){e||(Q?.getMessages().length===0?Ad():kd()),hs=e,Pu(e),fn(),Q&&Ul(B,Q.getMessages(),ut),e||(il(!0),hl(),ls=!0,Q&&us(Q.getMessages(),Xe(c))),tl(),Sr(e?`Responding…`:`Response complete.`),su()},onVoiceStatusChanged(e){if(be.emit(`voice:status`,{status:e,timestamp:Date.now()}),e!==`disconnected`&&!Sn(c.voiceRecognition?.provider))return;let t=Q.getVoiceNotice();switch(t&&ff(t,1e4),e){case`listening`:if(!dc){let e=Q.getVoiceDisclosure();e&&(dc=!0,N()?(fc=V.placeholder,V.placeholder=e,Sr(e)):ff(e,1e4))}sp(),ip();break;case`processing`:sp(),ap();break;case`speaking`:sp(),op();break;default:e===`idle`&&Q.isBargeInActive()?(sp(),ip(),K?.setAttribute(`aria-label`,`End voice session`)):($.active=!1,dc=!1,fc!==null&&(V.placeholder=fc,fc=null),sp(),vc(`system`),_c||yc())}},onArtifactsState(e){xa=e,e.artifacts.length===0&&(Ta=!1),Pc()?.updateInlineArtifactBlocks(B,e.artifacts,{suppressTransition:hs}),To(),kc()},onHistoryStateChanged(e){un(e)},onHistoryNotice(e){dn(e)},onReconnect(e){let{executionId:t,lastEventId:n}=e.handle;e.phase===`paused`?be.emit(`stream:paused`,{executionId:t,after:n}):e.phase===`resuming`?be.emit(`stream:resuming`,{executionId:t,after:n,attempt:e.attempt??1}):be.emit(`stream:resumed`,{executionId:t,after:n})}},md),Oa.current=Q,Z.push(()=>Q.cancel()),Z.push(()=>{Q.destroy(),fd?.destroy(),fd=null});let Md=null;if(Q.onReadAloudChange((e,t)=>{la=e,ua=t,pa();let n=e??Md;e&&(Md=e);let r=n?Q.getMessages().find(e=>e.id===n)??null:null;be.emit(`message:read-aloud`,{messageId:n,message:r,state:t,timestamp:Date.now()}),t===`idle`&&(Md=null)}),C=!0,Ks=!0,c.voiceRecognition?.enabled===!0&&Sn(c.voiceRecognition.provider))try{Q.setupVoice()}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Runtype voice setup failed:`,e)}let Nd=null,Pd=null,Fd=!1,Id=Q.getHistoryState(),Ld=()=>c.features?.history?.enabled===!0,Rd=e=>{e&&(gr.textContent=``,gr.textContent=e)},zd=()=>{S.forEach(e=>e()),S=[];let e=Nd,n=e?.railCollapseShortcut();e&&n&&S.push(x.register({id:`history-rail-collapse`,combo:n.combo,scope:c.features?.history?.rail?.collapseShortcutScope===`page`?`page`:`widget`,when:()=>on&&sn===`rail`&&e.railCollapsible()||e.railTriggerApplies(),run:()=>e.railOverlayMode()?e.toggleRailPinned():e.toggleRailCollapsed()}));for(let e of c.layout?.header?.trailingActions??[])e.shortcut&&S.push(x.register({id:`header-action-${e.id}`,combo:e.shortcut,run:()=>{let n=t.querySelector(`[data-persona-header-action="${e.id}"]`);n?n.click():c.layout?.header?.onAction?.(e.id)}}));for(let e of g)for(let t of e.shortcuts??[])S.push(x.register({...t,id:`${e.id}:${t.id}`}))};zd();let Bd=null,Vd=!1,Hd=()=>{if(!Rn)return;let e=c.layout?.header?.titleSource===`conversation`,t=e&&Bd?.trim()||null;Rn.textContent=t??c.launcher?.title??`Chat Assistant`;let n=Rn.closest(`.persona-combo-btn`);if(!n)return;let r=!e||Q.getActiveConversationId()!==null;n.setAttribute(`data-persona-menu-locked`,r?`false`:`true`),n.setAttribute(`aria-haspopup`,r?`true`:`false`),r||n.setAttribute(`aria-expanded`,`false`),n.style.cursor=r?`pointer`:`default`;let i=n.querySelector(`svg`);i&&(i.style.display=r?``:`none`)},Ud=e=>{e!==Bd&&(Bd=e,Hd())},Wd=e=>{Vd=e?.starred===!0,Ud(e&&e.title.trim()||null),Hd()};Hd(),R.addEventListener(`persona:title-menu-builtin`,e=>{let t=e.detail?.actionId,n=Q.getActiveConversationId();n&&(t===`delete`?Jd(e=>e.requestDeleteConversation(n)):t===`star`&&Q.canUpdateConversations()&&Jd(e=>e.updateHistoryConversation(n,{starred:!Vd})).catch(()=>{}))}),un=e=>{Id=e,Nd?.historySurface?.view.setNewConversationRequired(e.recovery===`new_conversation_required`),Pu(e.sendBlocked||hs),Nd?.syncEarlierMessagesPill()},dn=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(vs.clear(),gl(),rl()),Rd(e.message),Nd?.historySurface?.view.refresh()};let Gd={get actionManager(){return Ve},get activeConversationTitle(){return Bd},announceHistory:Rd,get applyRailChrome(){return ln},set applyRailChrome(e){ln=e},get artifactSplitRoot(){return La},get body(){return z},get config(){return c},get container(){return R},get conversationOpenPendingEl(){return Iu},set conversationOpenPendingEl(e){Iu=e},get conversationOpenTakeover(){return Lu},set conversationOpenTakeover(e){Lu=e},currentKeyPrefix:yt,destroyCallbacks:Z,eventBus:be,get footer(){return G},get header(){return Bn},get historyChromeSync(){return fn},set historyChromeSync(e){fn=e},historyFeatureEnabled:Ld,get historyInternals(){return md},set historyInternals(e){md=e},get historyPresentation(){return sn},set historyPresentation(e){sn=e},get historySessionState(){return Id},get historyVisible(){return on},set historyVisible(e){on=e},get isStreaming(){return hs},jumpToBottomInstant:sl,get lastAppliedMessages(){return Sd},set lastAppliedMessages(e){Sd=e},get launcherEnabled(){return He},get launcherSurfaceInstance(){return Sp},maybeFocusInput:Fu,messageCache:vs,get messagesWrapper(){return B},mount:t,get open(){return P},panel:I,panelElements:L,get persistentMetadata(){return Te},set persistentMetadata(e){Te=e},plugins:g,get reapplyHistoryHostChrome(){return cn},set reapplyHistoryHostChrome(e){cn=e},repinAnchoredMessage:Sl,resetAnchorState:gl,restoreScrollPosition:dl,resumeAutoScroll:rl,runStorageMutation:Oc,get session(){return Q},setActiveConversationSummary:Wd,storageAdapter:xe,get suppressScrollSend(){return qs},set suppressScrollSend(e){qs=e},syncScrollToBottomButton:tl,updateWelcome:Ju,getHistoryProviderFactory:nu,historyErrors:{HistoryClientError:qn,HistoryProviderError:vt},isDockedMountMode:po,renderLucideIcon:M,loadHistoryView:Yl,createHeaderIconButton:Do,attachTooltip:n},Kd=e=>(!Nd&&!Fd&&(Nd=e.createHistoryShell(Gd),Nd.railCollapseShortcut()&&zd()),Nd),qd=()=>{if(Nd)return Promise.resolve(Nd);let e=tu();return e?Promise.resolve(Kd(e)):(Pd??=eu().then(Kd,e=>{throw Pd=null,e}),Pd)},Jd=e=>{let t=tu(),n=Nd??(t?Kd(t):null);return n?e(n):qd().then(t=>{if(!t)throw Error(`[AgentWidget] The widget was destroyed`);return e(t)})},Yd=()=>{Nd?.syncHistoryPresentation()};Z.push(()=>{Fd=!0}),Ld()&&qd().catch(()=>{}).finally(je),c.clientToken&&(c.features?.history?.enabled===!0||c.sessionInit===`mount`)&&Q.initClientSession().then(()=>{let e=Nd;if(e?.historyAvailable())return Q.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Nd?.syncEarlierMessagesPill()}).catch(e=>{c.debug&&console.warn(`[AgentWidget] Pre-init client session failed:`,e)});let Xd=()=>Q.warmClientSession(),Zd=e=>{let t=c.sessionInit??`input`,n=Y?.input??V,r=e.target;n&&(e.type===`input`?(t===`input`||t===`focus`)&&r===n&&e.inputType&&n.value.trim():t===`focus`&&(e.type===`keyup`?r===n&&e.key===`Tab`:(Y?.form??kn)?.contains(r)))&&Xd()},Qd=[`input`,`pointerdown`,`keyup`];Qd.forEach(e=>t.addEventListener(e,Zd));let $d,ef,tf=()=>{let e=ef;ef=void 0;try{typeof e==`function`&&e()}catch{}},nf=()=>{let e=c.clientToken&&typeof c.sessionInit==`function`?c.sessionInit:void 0;if(e!==$d){tf(),$d=e;try{ef=e?.({warm:Xd,mount:t})}catch{}}};nf(),Z.push(()=>{Qd.forEach(e=>t.removeEventListener(e,Zd)),tf()}),(mt||c.onSSEEvent)&&Q.setSSEEventCallback((e,t)=>{c.onSSEEvent?.(e,t),rn(e,t)});let rf=()=>{let e=c.resume??(Ce?md.getStoredResumableHandle?.():null);e&&typeof c.reconnectStream==`function`&&Q.resumeFromHandle(e)};De?De.then(e=>{if(e){if(e.metadata&&(Te=vu(e.metadata),Ve.syncFromMetadata()),e.messages?.length){qs=!0;try{Q.hydrateMessages(e.messages)}finally{qs=!1}Vl()}e.artifacts?.length&&Q.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),zc(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Bu=!0,ke(),rf()}):(zc(Pe),rf());let af=()=>{N()&&(P||(c.launcher?.composerBar?.expandOnSubmit??!0)&&wu(!0,`auto`))},of=(e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[n,r]=await Promise.allSettled([e.finalize(),t.finalize()]),i=[];return n.status===`fulfilled`?i.push(n.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,n.reason),r.status===`fulfilled`?i.push(r.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,r.reason),Cu(i)}}:e:t,sf=()=>{let e=V.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>e.kind===`mention`)?e.contentSegments:void 0},cf=!1,lf=null,uf=()=>{V.value=``,V.style.height=`auto`,Fr(),kf()},df=null;function ff(e,t=4e3){Sr(e),!N()&&U&&(U.hasAttribute(du)||(U.setAttribute(fu,``),U.setAttribute(`role`,`status`),U.setAttribute(`aria-live`,`polite`),U.textContent=e,i(U,c.statusIndicator??{},`idle`),df&&clearTimeout(df),df=setTimeout(()=>{if(df=null,U?.hasAttribute(fu)&&(U.removeAttribute(fu),U.removeAttribute(`role`),U.removeAttribute(`aria-live`),C)){let e=Q.getStatus();vn(U,hn(e),c.statusIndicator??{},e)}},t)))}function pf(){let e=J.getState().pendingSubmission;e&&(ri(void 0),V&&(V.value=e.text,V.dispatchEvent(new Event(`input`,{bubbles:!0})),Fr()),e.options.selectedModelId&&(J.setSelectedModelId(e.options.selectedModelId),Gr?.repaint()),e.options.activeModeIds?.length&&Ur(e.options.activeModeIds),e.options.quote&&$r(e.options.quote),V?.focus())}let mf=e=>{typeof console<`u`&&console.error(`[AgentWidget] composer.onBeforeSend failed; the draft was preserved:`,e)},hf=(e={})=>{let t=(e.overrideText??V?.value??``).trim();return e.resolveInlineCommand&&t?(Pr?.takeInlineCommand(t)??Promise.resolve(null)).then(n=>gf(e,t,n)):gf(e,t,null)},gf=(e,t,n)=>{if(n?.kind===`action`){uf(),Pr?.clear(),Ir();return}let r=n?.kind===`server`?n.mentions:null,i=n?.kind===`prompt`?n.sendText:t,a=e.pending?.contentParts;if(!Yi({text:i,hasAttachments:(q?.hasAttachments()??!1)||(a?.length??0)>0,attachmentsReady:q?.isReady()??!0,hasMentions:Pr?.hasMentions()??!1,hasServerMentions:!!r,inputDisabled:Eu(),sendDisabled:Ou()}))return;let o=Q.isStreaming()?ti():`block`;if(o===`defer-one`&&!e.pending){if(J.getState().pendingSubmission){ff(`One message is already queued. Edit or remove it first.`);return}_f({intent:e,sendText:i,serverMentions:r});return}let s={text:i,mentionRefs:[...Pr?.getMentionRefs()??[],...r?.refs??[]],contentSegments:n?.kind===`prompt`?void 0:sf(),options:{...J.getState().selectedModelId&&{selectedModelId:J.getState().selectedModelId},...J.getState().activeModeIds.length>0&&{activeModeIds:[...J.getState().activeModeIds]},...J.getState().quote&&{quote:{...J.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(s.options={...e.pending.options},s.contentSegments=e.pending.contentSegments,s.mentionRefs=[...e.pending.mentionRefs],s.viaVoice=e.pending.viaVoice);let l=()=>{if(a?.length)return[...a];if(!q?.hasAttachments())return;let e=[...q.getContentParts()];return s.text&&e.push(it(s.text)),e};s.contentParts=l();let u=()=>{ks(),af();let t=Pr?.collectForSubmit()??null,n=of(t,r),i=l();e.consumeDraft!==!1&&uf();let a={selectedModelId:s.options.selectedModelId,activeModeIds:s.options.activeModeIds},u=o===`interrupt`;u&&Q.cancel(),Q.sendMessage(s.text,{contentParts:i,mentions:n??void 0,contentSegments:s.contentSegments,viaVoice:s.viaVoice,composerOptions:a,...s.options.quote&&{quote:s.options.quote},...u&&{interrupt:!0}}),q?.hasAttachments()&&q.clearAttachments(),t&&Pr?.clear(),Ir();let d=J.getState().activeModeIds,f=Ii(d,c.composer?.modes);f.length!==d.length&&Ur(f),J.getState().quote&&$r(void 0),Bc(),ta.release(),ra()},d=c.composer?.onBeforeSend;if(!d){u();return}let f=new AbortController;lf=f;let p=e=>{lf=null,e.status===`error`?mf(e.error):e.status===`proceed`&&u()},m=Qi(d,s,f.signal);if(!(m instanceof Promise))p(m);else return J.setPreparing(!0),m.then(p).finally(()=>J.setPreparing(!1))};function _f(e){let t=J.getState(),n=q?.hasAttachments()??!1,r=n?[...q.getContentParts()]:[];n&&e.sendText&&r.push(it(e.sendText)),ri(Ji({text:e.sendText,contentParts:r.length?r:void 0,mentionRefs:[...Pr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:sf(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),e.intent.consumeDraft!==!1&&uf(),n&&q.clearAttachments(),Pr?.clear(),Ir(),t.quote&&$r(void 0),Bc(),ta.release(),ra(),Sr(`Message queued. It sends when the response finishes.`)}function vf(){let e=J.getState().pendingSubmission;e&&(ri(void 0),wf(e.text,{consumeDraft:!1,pending:e}))}function yf(e){if(c.messageActions?.showEdit!==!0)return;let t=Q.getMessages().find(t=>t.id===e);t&&br(t)&&Ts!==e&&(ks(),Ts=e,Os=Vi({messageId:e,initialText:t.content,onSave:t=>bf(e,t),onCancel:()=>ks()}),vs.delete(e),Ul(B,Q.getMessages(),ut),Os.focus())}function bf(e,t){let n=Os;Ts=null,Os=null,n?.destroy(),vs.delete(e),Q.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?Sl():Ul(B,Q.getMessages(),ut)}function xf(e){if(Q.isStreaming())return;let t=vr(Q.getMessages(),e);t&&(ks(),Q.resubmitFrom(t,{reason:`retry`})&&Sl())}ma={regenerate:xf,edit:yf,quote:e=>{let t=Q.getMessages().find(t=>t.id===e)?.content?.trim();t&&($r({text:t,messageId:e}),V?.focus())}};let Sf=async e=>{if(!cf){cf=!0;try{await hf({resolveInlineCommand:!0,...e})}finally{cf=!1}}};function Cf(e){Ou()||(uf(),wf(e,{consumeDraft:!1}))}let wf=(e,t)=>{if(cf)return;cf=!0;let n=()=>{cf=!1};try{let r=hf({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},Tf=e=>{e.preventDefault(),Q.isStreaming()?(Q.cancel(),Jt?.reset(),Qt?.update()):cf||Sf()},Ef=()=>c.features?.composerHistory!==!1,Df={...Za},Of=!1,kf=()=>{Df={...Za}},Af=()=>Q.getMessages().filter(e=>e.role===`user`).map(e=>e.content??``).filter(e=>e.length>0),jf=e=>{if(!V)return;Of=!0,V.value=e,V.dispatchEvent(new Event(`input`,{bubbles:!0})),Of=!1;let t=V.value.length;V.setSelectionRange(t,t)},Mf=e=>{Of||(e.isComposing||Pr?.handleInput(e.inputType??void 0),kf())},Nf=()=>({submitKey:c.composer?.submitKey,insertNewlineOnTouchEnter:c.composer?.insertNewlineOnTouchEnter,coarsePointer:ce(V)}),Pf=e=>{if(V&&!Eu()&&(e.isComposing||!Pr?.handleKeydown(e))){if(Ef()&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.isComposing){let t=V.selectionStart===0&&V.selectionEnd===0,n=Qa({direction:e.key===`ArrowUp`?`up`:`down`,history:Af(),currentValue:V.value,atStart:t,state:Df});if(Df=n.state,n.handled){e.preventDefault(),n.value!==void 0&&jf(n.value);return}}if(de(e,Nf())){if(Q.isStreaming()){if(e.preventDefault(),ti()===`block`||cf||Ou())return;kf(),Sf()}else cf||Ou()?e.preventDefault():(kf(),e.preventDefault(),H.click())}}},Ff=e=>{e.key!==`Escape`||e.isComposing||e.composedPath().includes(R)&&(lf?(lf.abort(),lf=null,e.preventDefault(),e.stopImmediatePropagation()):Q.isStreaming()&&(Q.cancel(),Jt?.reset(),Qt?.update(),kf(),e.preventDefault(),e.stopImmediatePropagation()))},If=async e=>{if(c.attachments?.enabled!==!0||!q||Eu())return;let t=mu(e.clipboardData);t.length!==0&&(e.preventDefault(),await q.handleFiles(t))},Lf=null,Rf=!1,zf=null,Bf=null,Vf=()=>c.voiceRecognition?.completionBehavior===`review`;function Hf(e){K?.setAttribute(`data-state`,e),e===`recording`?Zf():Qf()}let Uf=`--persona-voice-level`,Wf=.5,Gf=null,Kf=-1,qf=0,Jf=()=>{let e=[],t=Kn??K?.parentElement??null;return t&&e.push(t),G&&e.push(G),e},Yf=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*100)/100;if(t!==Kf){Kf=t;for(let e of Jf())e.style.setProperty(Uf,String(t))}},Xf=()=>{Kf=-1,qf=0;for(let e of Jf())e.style.removeProperty(Uf)};function Zf(){if(Gf!==null)return;if(typeof requestAnimationFrame!=`function`){Yf(C?Q.getVoiceLevel()??Wf:Wf);return}let e=()=>{Gf=requestAnimationFrame(e);let t=C?Q.getVoiceLevel():null;t===null?Yf(Wf):(qf+=(t-qf)*.3,Yf(qf))};Gf=requestAnimationFrame(e)}function Qf(){Gf!==null&&(cancelAnimationFrame(Gf),Gf=null),Xf()}let $f=()=>typeof window>`u`?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ep=(e=`user`)=>{if(Rf||Q.isStreaming())return;let t=$f();if(!t)return;Lf=new t;let n=c.voiceRecognition??{},r=n.pauseDuration??2e3;Lf.continuous=n.provider?.browser?.continuous??!0,Lf.interimResults=!0,Lf.lang=n.provider?.browser?.language??`en-US`;let i=V.value;Lf.onresult=e=>{let t=``,n=``;for(let r=0;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n=a}let a=i+t+n;V.value=a,Fr(),zf&&clearTimeout(zf),(t||n)&&(zf=window.setTimeout(()=>{if(V.value.trim()&&Lf&&Rf){if(tp(),Vf())return;Sf({viaVoice:!0})}},r))},Lf.onerror=e=>{e.error!==`no-speech`&&tp()},Lf.onend=()=>{if(Rf){let e=V.value.trim();!Vf()&&e&&e!==i.trim()&&Sf({viaVoice:!0}),tp()}};try{if(Lf.start(),Rf=!0,$.active=!0,e!==`system`&&($.manuallyDeactivated=!1),vc(e),yc(),ra(),K){let e=c.voiceRecognition??{};Bf={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:e.iconName??`mic`,iconSize:parseFloat(e.iconSize??``)||24};let t=e.recordingBackgroundColor,n=e.recordingIconColor,r=e.recordingBorderColor;if(K.classList.add(`persona-voice-recording`),Hf(`recording`),K.style.backgroundColor=t??`var(--persona-voice-recording-bg, #ef4444)`,K.style.color=n??`var(--persona-voice-recording-indicator, #ffffff)`,n){let e=K.querySelector(`svg`);e&&e.setAttribute(`stroke`,n)}r&&(K.style.borderColor=r),K.setAttribute(`aria-label`,`Stop voice recognition`)}}catch{tp(`system`)}},tp=(e=`user`)=>{if(Rf){if(Rf=!1,zf&&=(clearTimeout(zf),null),Lf){try{Lf.stop()}catch{}Lf=null}if($.active=!1,vc(e),yc(),ra(),K){if(K.classList.remove(`persona-voice-recording`),Hf(`idle`),Bf){K.style.backgroundColor=Bf.backgroundColor,K.style.color=Bf.color,K.style.borderColor=Bf.borderColor;let e=K.querySelector(`svg`);e&&e.setAttribute(`stroke`,Bf.color||`currentColor`),Bf=null}K.setAttribute(`aria-label`,`Start voice recognition`)}}},np=null,rp=e=>{let t=t=>{np??=t.createMicStateStyles({mic:()=>K,config:()=>c,session:()=>Q,get original(){return Bf},set original(e){Bf=e},setMicState:Hf,renderIcon:M,iconFallbackPx:24}),e(np)},n=kr();n?t(n):Or().then(t,()=>{})},ip=()=>rp(e=>e.recording()),ap=()=>rp(e=>e.processing()),op=()=>rp(e=>e.speaking()),sp=()=>rp(e=>e.reset()),cp=()=>{if(!Eu()){if(Sn(c.voiceRecognition?.provider)){let e=Q.getVoiceStatus(),t=Q.getVoiceInterruptionMode();if(t===`none`&&(e===`processing`||e===`speaking`))return;if(t===`cancel`&&(e===`processing`||e===`speaking`)){Q.stopVoicePlayback();return}if(Q.isBargeInActive()){Q.stopVoicePlayback(),Q.deactivateBargeIn().then(()=>{$.active=!1,$.manuallyDeactivated=!0,yc(),vc(`user`),sp()});return}Q.toggleVoice().then(()=>{$.active=gc(),$.manuallyDeactivated=!$.active,yc(),vc(`user`),$.active?ip():sp()})}else if(Rf){let e=V.value.trim();$.manuallyDeactivated=!0,yc(),tp(`user`),e&&!Vf()&&Sf()}else $.manuallyDeactivated=!1,yc(),ep(`user`)}};si=cp;let lp=()=>Q.prewarmVoice(),up=()=>{let e=c.voiceRecognition;return e?.enabled===!0?e.prewarm??(c.clientToken?`hover`:!1):!1},dp=e=>{up()===`hover`&&K?.contains(e.target)&&lp()},fp=[`pointerover`,`pointerdown`,`focusin`];fp.forEach(e=>t.addEventListener(e,dp));let pp,mp=null,hp,gp=()=>{let e=hp;hp=void 0;try{typeof e==`function`&&e()}catch{}},_p=()=>{let e=up(),n=typeof e==`function`&&K?e:void 0,r=n?K:null;if((n!==pp||r!==mp)&&(gp(),pp=n,mp=r,n&&r))try{hp=n({warm:lp,micButton:r,mount:t})}catch{}};_p(),Z.push(()=>{fp.forEach(e=>t.removeEventListener(e,dp)),gp()}),K&&Z.push(()=>{Sn(c.voiceRecognition?.provider)?(Q.isVoiceActive()&&Q.toggleVoice(),sp()):tp(`system`)});let vp=be.on(`assistant:complete`,()=>{J.getState().pendingSubmission&&setTimeout(()=>{Q.isStreaming()||vf()},0)});Z.push(vp);let yp=be.on(`assistant:complete`,()=>{pc&&($.active||$.manuallyDeactivated||(pc!==`assistant`||$.lastUserMessageWasVoice)&&setTimeout(()=>{!$.active&&!$.manuallyDeactivated&&(Sn(c.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=Q.isVoiceActive(),vc(`auto`),Q.isVoiceActive()&&ip()}):ep(`auto`))},600))});Z.push(yp);let bp=be.on(`action:resubmit`,()=>{setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)});Z.push(bp);let xp=()=>{wu(!P,`user`)},Sp=null,Cp=null;if(He&&!N()){let{instance:e,element:t}=$s({config:c,plugins:g,onToggle:xp});Sp=e,e||(Cp=t)}Sp?t.appendChild(Sp.element):Cp&&t.appendChild(Cp),Su(),ds(),id(),nd(),Pu(Q.isStreaming()),dl()||(tr()===`follow`?il(!0):sl()),Sc(),Ge&&(!He||N()?setTimeout(()=>Fu(),0):P&&setTimeout(()=>Fu(),200));let wp=null,Tp=()=>{wp&&(wp.disconnect(),wp.observe(G),wp.observe(R),wp.observe(An))},Ep=Cr(),Dp=()=>{if(N()){Ar(),Su();return}let e=po(c),n=c.launcher?.sidebarMode??!1,r=t.ownerDocument.defaultView??window,i=c.launcher?.mobileFullscreen??!0,a=c.launcher?.mobileBreakpoint??640,o=r.innerWidth<=a,s=i&&o&&He;try{if(s){va(),ya=wo();return}let t=!1;rt&&(rt=!1,va(),t=!0);let r=wo();if(!t&&r!==ya&&(va(),t=!0),ya=r,t&&io(),!He&&!e){I.style.height=``,I.style.width=``;return}if(!n&&!e){let e=Fs(c);I.style.width=e.width,I.style.maxWidth=e.maxWidth}yo(),Io()}finally{Ar(),Mr();let e=Cr();if(e!==Ep&&(Ep=e,Ju(),ds()),Su(),P&&He){let e=(t.ownerDocument.defaultView??window).innerWidth<=(c.launcher?.mobileBreakpoint??640),n=c.launcher?.sidebarMode??!1,r=c.launcher?.mobileFullscreen??!0,i=po(c)&&r&&e,a=n||r&&e&&He||i;if(a&&!Bo){let e=t.getRootNode(),n=e instanceof ShadowRoot?e.host:t.closest(`.persona-host`);n&&!Lo&&(Lo=so(n,c.launcher?.zIndex??1e5)),Bo=uo(t.ownerDocument)}else a||(Lo?.(),Lo=null,Bo?.(),Bo=null)}}};Dp();let Op=t.ownerDocument.defaultView??window;if(Op.addEventListener(`resize`,Dp),Z.push(()=>Op.removeEventListener(`resize`,Dp)),typeof ResizeObserver<`u`){wp=new ResizeObserver(()=>{Mr()}),Tp(),Z.push(()=>{wp?.disconnect(),wp=null});let e=new ResizeObserver(()=>{Yd()});e.observe(R),Z.push(()=>e.disconnect())}Op.addEventListener(`resize`,Yd),Z.push(()=>Op.removeEventListener(`resize`,Yd)),zs=z.scrollTop;let kp=Dt(z),Ap=()=>{Mo();let e=z.scrollTop,t=Dt(z),n=t<kp;if(kp=t,!nr()){zs=e,tl();return}let{action:r,nextLastScrollTop:i}=Et({following:Is.isFollowing(),currentScrollTop:e,lastScrollTop:zs,nearBottom:Mt(z,24),userScrollThreshold:4,isAutoScrolling:Vs||Hs||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});zs=i,r===`resume`?ul()||rl():r===`pause`&&nl()};if(z.addEventListener(`scroll`,Ap,{passive:!0}),Z.push(()=>z.removeEventListener(`scroll`,Ap)),typeof ResizeObserver<`u`){let e=new ResizeObserver(()=>{Cl(),On(B)});e.observe(B),e.observe(z),Z.push(()=>e.disconnect())}let jp=()=>{nr()&&Is.isFollowing()&&ul()&&nl()},Mp=z.ownerDocument;Mp.addEventListener(`selectionchange`,jp),Z.push(()=>{Mp.removeEventListener(`selectionchange`,jp)});let Np=/* @__PURE__ */ new Set([`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`]),Pp=e=>{Np.has(e.key)&&(tc(),sr()&&nr()&&Is.isFollowing()&&nl())},Fp=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&(tc(),sr()&&nr()&&Is.isFollowing()&&nl())};z.addEventListener(`keydown`,Pp),z.addEventListener(`focusin`,Fp),Z.push(()=>{z.removeEventListener(`keydown`,Pp),z.removeEventListener(`focusin`,Fp)});let Ip=e=>{if(e.deltaY!==0&&tc(),!nr())return;let t=Ot({following:Is.isFollowing(),deltaY:e.deltaY,nearBottom:Mt(z,24),resumeWhenNearBottom:!0});t===`pause`?nl():t===`resume`&&!ul()&&rl()};z.addEventListener(`wheel`,Ip,{passive:!0}),z.addEventListener(`touchmove`,tc,{passive:!0}),z.addEventListener(`pointerdown`,tc,{passive:!0}),Z.push(()=>{z.removeEventListener(`touchmove`,tc),z.removeEventListener(`pointerdown`,tc)}),Z.push(()=>z.removeEventListener(`wheel`,Ip)),dr.addEventListener(`click`,()=>{gl(),z.scrollTop=z.scrollHeight,zs=z.scrollTop,rl(),il(!0),tl()}),Z.push(()=>dr.remove()),Z.push(()=>{Jc(),gl()});let Lp=()=>{W&&(Zo&&=(W.removeEventListener(`click`,Zo),null),at()?(W.style.display=``,Zo=()=>{wu(!1,`user`)},W.addEventListener(`click`,Zo)):W.style.display=`none`)};Lp(),(()=>{let{clearChatButton:e}=L;e&&e.addEventListener(`click`,()=>{let e=Nd;if(e?.historyAvailable()){e.startNewConversation({focusComposer:!0}).catch(e=>{c.debug&&console.warn(`[AgentWidget] New conversation failed:`,e)});return}Q.clearMessages(),c.layout?.topFade&&(z.scrollTop=0),z.removeAttribute(`data-persona-top-fade`),vs.clear(),rl(),Ke(L.composerOverlay);try{localStorage.removeItem(uu),c.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${uu}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(c.clearChatHistoryStorageKey&&c.clearChatHistoryStorageKey!==uu)try{localStorage.removeItem(c.clearChatHistoryStorageKey),c.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${c.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let t=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(t),xe?.clear&&Oc(()=>xe.clear(),`[AgentWidget] Failed to clear storage adapter:`),Te={},Ve.syncFromMetadata(),q?.clearAttachments(),Bc(),ri(void 0),$r(void 0),ks(),qt?.clear(),Jt?.reset(),Qt?.update()})})();let Rp=[[`keydown`,Pf],[`input`,Mf],[`input`,Fr],[`input`,Ir],[`keyup`,Ir],[`paste`,If],[`focus`,wi]],zp=e=>{if(e)for(let[t,n]of Rp)Y?.addListener(e,t,n)},Bp=e=>{if(e)for(let[t,n]of Rp)Y?.removeListener(e,t,n)},Vp=()=>{Y&&(Y.addListener(Y.form,`submit`,Tf),Y.addListener(Y.footer,`click`,Ir),zp(V),K&&Y.addListener(K,`click`,cp),_p())};Vp();let Hp=()=>{Pr?.onComposerSwap((e,t)=>{Bp(t),V=e,Y&&(Y.input=e),zp(e),vi(),Nu(),Fr()})};Hp();let Up=!1;function Wp(){if(!Up){Up=!0;try{let e=V?.value??``,t=G.ownerDocument??document,n=V?t.activeElement===V:!1;Qf(),Y?.destroy(),Y=null,Pr?.destroy(),Pr=null;let r=null,i=()=>(r=N()?Vo({config:c}):zo({config:c}),r.footer),a=hi(i)??i();xn.replaceComposer(a),G=xn.composer.footer;let o=r!==null&&a===r.footer;mi=!o,Gn=o?r.setSendButtonMode:()=>{},pi(G),yi(G),xi(),Ci(),ki(),Hp(),Zi(),$i(),ea(),Vp();let s=Xo.indexOf(qo);if(qo.destroy(),qo=So(En),s>=0&&(Xo[s]=qo),V&&(V.value=e),Fr(),Ir(),id(),ds(),Pu(Q.isStreaming()),c.statusIndicator?.mode===`transient`&&!N()){let e=Q.getStatus();vn(U,hn(e),c.statusIndicator,e)}$.active&&Hf(`recording`),va(),Tp(),Ar(),ra(),ju(),n&&V?.focus()}finally{Up=!1}}}let Gp=t.ownerDocument??document;Gp.addEventListener(`keydown`,Ff,!0);let Kp=()=>{Rc()},qp=()=>{Gp.visibilityState===`hidden`&&Rc()};typeof window<`u`&&(window.addEventListener(`pagehide`,Kp),Gp.addEventListener(`visibilitychange`,qp),Z.push(()=>{window.removeEventListener(`pagehide`,Kp),Gp.removeEventListener(`visibilitychange`,qp)}));let Jp=`persona-attachment-drop-active`,Yp=0,Xp=()=>{Yp=0,R.classList.remove(Jp)},Zp=()=>c.attachments?.enabled===!0&&q!==null&&!Eu(),Qp=e=>{hu(e.dataTransfer)&&Zp()&&(Yp++,Yp===1&&R.classList.add(Jp))},$p=e=>{hu(e.dataTransfer)&&Zp()&&(Yp--,Yp<=0&&Xp())},em=e=>{hu(e.dataTransfer)&&Zp()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},tm=e=>{if(!hu(e.dataTransfer)||!Zp())return;e.preventDefault(),e.stopPropagation(),Xp();let t=Array.from(e.dataTransfer.files??[]);t.length!==0&&q.handleFiles(t)};R.addEventListener(`dragenter`,Qp,!0),R.addEventListener(`dragleave`,$p,!0),t.addEventListener(`dragover`,em,!0),t.addEventListener(`drop`,tm,!0);let nm=t.ownerDocument,rm=e=>{Zp()&&e.preventDefault()},im=e=>{Zp()&&e.preventDefault()};nm.addEventListener(`dragover`,rm),nm.addEventListener(`drop`,im),Z.push(()=>{Y?.destroy(),Y=null,Qf(),ji?.destroy(),ji=null,Jr?.destroy(),Jr=null,Zr?.destroy(),Zr=null,ni?.destroy(),ni=null,Gr=null,qr=null,Rc(),Mc.destroy(),df&&clearTimeout(df),ks(),lf?.abort(),lf=null,q?.destroy(),q=null,J.destroy(),Gp.removeEventListener(`keydown`,Ff,!0),Pr?.destroy()}),Z.push(()=>{R.removeEventListener(`dragenter`,Qp,!0),R.removeEventListener(`dragleave`,$p,!0),t.removeEventListener(`dragover`,em,!0),t.removeEventListener(`drop`,tm,!0),nm.removeEventListener(`dragover`,rm),nm.removeEventListener(`drop`,im),Xp()}),Z.push(()=>{Q.cancel()}),Sp?Z.push(()=>{Sp?.destroy()}):Cp&&Z.push(()=>{Cp?.remove()});let am={update(a){let o=c.future?.v5Defaults===!0,s=c.toolCall,l=c.messageActions,u=c.layout?.messages,d=c.colorScheme,f=c.loadingIndicator,p=c.iterationDisplay,_=c.features?.showReasoning,v=c.features?.showToolCalls,b=c.features?.toolCallDisplay,x=c.features?.reasoningDisplay,S=c.features?.streamAnimation?.type,C=c.features?.history?.enabled===!0,w=c.features?.history?.provider,T=c.getIdentityProof,E=c.clientToken,D=c.contextMentions;c=Al({...c,features:h},a),h=c.features,c=pl(c),m(),Oo(),Ua(t,c),Hc(t,c),Uc(t,c),ln(),To(),c.colorScheme!==d&&Uo();let O=El.getForInstance(c.plugins);g.length=0,g.push(...O),zd(),He=c.launcher?.enabled??!0,We=c.launcher?.autoExpand??!1,dt=c.features?.showReasoning??!0,pt=c.features?.showToolCalls??!0,ht=c.features?.scrollToBottom??{};let k=tr();_t=c.features?.scrollBehavior??{},k!==tr()&&(gl(),rl()),sc(),Nr(),tl();let ee=mt;if(mt=c.features?.showEventStreamToggle??!1,mt&&!ee){if(qt||(an(),Q.setSSEEventCallback((e,t)=>{c.onSSEEvent?.(e,t),rn(e,t)})),!fi&&Bn){let t=c.features?.eventStream?.classNames,n=`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`+(t?.toggleButton?` `+t.toggleButton:``);fi=j(`button`,n),fi.style.width=`28px`,fi.style.height=`28px`,fi.style.color=Ao.actionIconColor,fi.type=`button`,fi.setAttribute(`aria-label`,`Event Stream`),fi.title=`Event Stream`;let r=e(Wt,`18px`,`currentColor`,1.5);r&&fi.appendChild(r);let i=L.clearChatButtonWrapper,a=L.closeButtonWrapper,o=i||a;o&&o.parentNode===Bn?Bn.insertBefore(fi,o):Bn.appendChild(fi),fi.addEventListener(`click`,()=>{$t?di():ui()})}}else!mt&&ee&&(di(),fi&&=(fi.remove(),null),qt?.clear(),Ct?.destroy(),qt=null,Ct=null,Jt?.reset(),Jt=null,Yt=null);if(c.launcher?.enabled===!1&&Sp&&(Sp.destroy(),Sp=null),c.launcher?.enabled===!1&&Cp&&(Cp.remove(),Cp=null),c.launcher?.enabled!==!1&&!Sp&&!Cp){let{instance:e,element:n}=$s({config:c,plugins:g,onToggle:xp});Sp=e,e||(Cp=n),t.appendChild(n)}Sp&&Sp.update(c),Hd(),zn&&c.launcher?.subtitle!==void 0&&(zn.textContent=c.launcher.subtitle);let te=c.layout?.header;if(te?.layout!==nt&&Bn){let e=te?Ro(c,te,{showClose:at(),onClose:()=>wu(!1,`user`)}):No({config:c,showClose:at(),onClose:()=>wu(!1,`user`)});xn.replaceHeader(e),Bn=xn.header.element,Ln=xn.header.iconHolder,Rn=xn.header.headerTitle,zn=xn.header.headerSubtitle,W=xn.header.closeButton,nt=te?.layout,Hd()}else if(te){if(Ln&&(Ln.style.display=te.showIcon===!1?`none`:``),Rn&&(Rn.style.display=te.showTitle===!1?`none`:``),zn&&(zn.style.display=te.showSubtitle===!1?`none`:``),W){let e=at()&&te.showCloseButton!==!1;W.style.display=e?``:`none`}if(L.clearChatButtonWrapper){let e=te.showClearChat;if(e!==void 0){L.clearChatButtonWrapper.style.display=e?``:`none`;let{closeButtonWrapper:t}=L;t&&!t.classList.contains(`persona-absolute`)&&(e?t.classList.remove(`persona-ml-auto`):t.classList.add(`persona-ml-auto`))}}}let re=c.layout?.showHeader!==!1;Bn&&(Bn.style.display=re?``:`none`);let ie=c.layout?.showFooter!==!1;G&&(G.style.display=ie?``:`none`),Ar(),tl(),He===tt?We!==$e&&wu(We,`auto`):He?wu(We,`auto`):(P=!0,Su()),$e=We,tt=He,Dp(),Lp();let oe=JSON.stringify(c.toolCall)!==JSON.stringify(s),ce=JSON.stringify(c.messageActions)!==JSON.stringify(l),le=JSON.stringify(c.layout?.messages)!==JSON.stringify(u),ue=c.loadingIndicator?.render!==f?.render||c.loadingIndicator?.renderIdle!==f?.renderIdle||c.loadingIndicator?.showBubble!==f?.showBubble,de=c.iterationDisplay!==p,fe=(c.features?.showReasoning??!0)!==(_??!0)||(c.features?.showToolCalls??!0)!==(v??!0)||JSON.stringify(c.features?.toolCallDisplay)!==JSON.stringify(b)||JSON.stringify(c.features?.reasoningDisplay)!==JSON.stringify(x);(c.future?.v5Defaults===!0!==o||oe||ce||le||ue||de||fe)&&Q&&(As++,Ul(B,Q.getMessages(),ut));let pe=c.features?.streamAnimation?.type;if(pe!==S&&pe&&pe!==`none`){let e=Go(pe,c.features?.streamAnimation?.plugins);e&&zt(e,t)}let A=c.launcher??{},me=A.headerIconHidden??!1,he=c.layout?.header?.showIcon,ge=me||he===!1,_e=A.headerIconName,ve=A.headerIconSize??`40px`;if(Ln){let e=Bn,t=e?.querySelector(`.persona-flex-col`);if(ge)Ln.style.display=`none`,e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(Ln.style.display=``,Ln.style.height=ve,Ln.style.width=ve,e&&t&&(e.contains(Ln)?Ln.nextSibling!==t&&(Ln.remove(),e.insertBefore(Ln,t)):e.insertBefore(Ln,t)),_e){let e=parseFloat(ve)||24,t=M(_e,e*.6,`currentColor`,1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,Ln.replaceChildren(t)):Ln.textContent=A.agentIconText??`💬`}else if(A.iconUrl){let e=Ln.querySelector(`img`);if(e)e.src=A.iconUrl,e.style.height=ve,e.style.width=ve;else{let e=document.createElement(`img`);e.src=A.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=ve,e.style.width=ve,Ln.replaceChildren(e)}}else{let e=Ln.querySelector(`svg`),t=Ln.querySelector(`img`);(e||t)&&Ln.replaceChildren(),Ln.textContent=A.agentIconText??`💬`}let n=Ln.querySelector(`img`);n&&(n.style.height=ve,n.style.width=ve)}}let ye=c.layout?.header?.showTitle,xe=c.layout?.header?.showSubtitle;if(Rn&&(Rn.style.display=ye===!1?`none`:``),zn&&(zn.style.display=xe===!1?`none`:``),W){let e=at()&&c.layout?.header?.showCloseButton!==!1;if(W.style.display=e?``:`none`,!N()){let e=A.closeButtonSize??``;W.style.height=e,W.style.width=e,W.style.minWidth=e,W.style.minHeight=e}let t=A.closeButtonPlacement??`inline`,{closeButtonWrapper:r}=L,i=t===`top-right`,a=r?.classList.contains(`persona-absolute`);if(r&&i!==a){if(r.remove(),i){r.className=`persona-absolute persona-top-4 persona-right-4 persona-z-50`;let e=Nd?.railColumn??R;e.style.position=`relative`,e.appendChild(r)}else{let e=A.clearChat?.placement??`inline`;r.className=(A.clearChat?.enabled??!0)&&e===`inline`?``:`persona-ml-auto`,Bn&&Bn.appendChild(r)}}if(W.style.color=A.closeButtonColor||Ao.actionIconColor,A.closeButtonBackgroundColor?(W.style.backgroundColor=A.closeButtonBackgroundColor,W.classList.remove(`hover:persona-bg-gray-100`)):(W.style.backgroundColor=``,W.classList.add(`hover:persona-bg-gray-100`)),A.closeButtonBorderWidth||A.closeButtonBorderColor){let e=A.closeButtonBorderWidth||`0px`,t=A.closeButtonBorderColor||`transparent`;W.style.border=`${e} solid ${t}`,W.classList.remove(`persona-border-none`)}else W.style.border=``,W.classList.add(`persona-border-none`);A.closeButtonBorderRadius?(W.style.borderRadius=A.closeButtonBorderRadius,W.classList.remove(`persona-rounded-full`)):(W.style.borderRadius=``,W.classList.add(`persona-rounded-full`)),A.closeButtonPaddingX?(W.style.paddingLeft=A.closeButtonPaddingX,W.style.paddingRight=A.closeButtonPaddingX):(W.style.paddingLeft=``,W.style.paddingRight=``),A.closeButtonPaddingY?(W.style.paddingTop=A.closeButtonPaddingY,W.style.paddingBottom=A.closeButtonPaddingY):(W.style.paddingTop=``,W.style.paddingBottom=``),Eo(W,A.closeButtonIconName??`x`,{iconSize:N()?Ls:void 0,iconText:A.closeButtonIconText??`×`});let o=A.closeButtonTooltipText??`Close chat`,s=A.closeButtonShowTooltip??!0;W.setAttribute(`aria-label`,o),r&&n({anchor:W,trigger:r,text:()=>W?.getAttribute(`aria-label`)??o,enabled:s})}let{clearChatButton:Se,clearChatButtonWrapper:Ce}=L;if(Se){let e=A.clearChat??{},t=e.enabled??!0,r=c.layout?.header?.showClearChat,i=r===void 0?t:r,a=e.placement??`inline`;if(Ce){Ce.style.display=i?``:`none`;let{closeButtonWrapper:e}=L;!N()&&e&&!e.classList.contains(`persona-absolute`)&&(i?e.classList.remove(`persona-ml-auto`):e.classList.add(`persona-ml-auto`));let t=a===`top-right`,n=Ce.classList.contains(`persona-absolute`);if(!N()&&t!==n&&i){if(Ce.remove(),t){Ce.className=`persona-absolute persona-top-4 persona-z-50`,Ce.style.right=`48px`;let e=Nd?.railColumn??R;e.style.position=`relative`,e.appendChild(Ce)}else{Ce.className=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,Ce.style.right=``;let e=L.closeButtonWrapper;Bn&&e&&e.parentElement===Bn?Bn.insertBefore(Ce,e):Bn&&Bn.appendChild(Ce)}let e=L.closeButtonWrapper;e&&!e.classList.contains(`persona-absolute`)&&(t?e.classList.add(`persona-ml-auto`):e.classList.remove(`persona-ml-auto`))}}if(i){if(!N()){let t=e.size??``;Se.style.height=t,Se.style.width=t,Se.style.minWidth=t,Se.style.minHeight=t}let t=e.iconColor??``;if(Se.style.color=t||Ao.actionIconColor,Eo(Se,e.iconName??`refresh-cw`,{iconSize:N()?Rs:void 0}),e.backgroundColor?(Se.style.backgroundColor=e.backgroundColor,Se.classList.remove(`hover:persona-bg-gray-100`)):(Se.style.backgroundColor=``,Se.classList.add(`hover:persona-bg-gray-100`)),e.borderWidth||e.borderColor){let t=e.borderWidth||`0px`,n=e.borderColor||`transparent`;Se.style.border=`${t} solid ${n}`,Se.classList.remove(`persona-border-none`)}else Se.style.border=``,Se.classList.add(`persona-border-none`);e.borderRadius?(Se.style.borderRadius=e.borderRadius,Se.classList.remove(`persona-rounded-full`)):(Se.style.borderRadius=``,Se.classList.add(`persona-rounded-full`)),e.paddingX?(Se.style.paddingLeft=e.paddingX,Se.style.paddingRight=e.paddingX):(Se.style.paddingLeft=``,Se.style.paddingRight=``),e.paddingY?(Se.style.paddingTop=e.paddingY,Se.style.paddingBottom=e.paddingY):(Se.style.paddingTop=``,Se.style.paddingBottom=``);let r=e.tooltipText??`Clear chat`,i=e.showTooltip??!0;Se.setAttribute(`aria-label`,r),Ce&&n({anchor:Se,trigger:Ce,text:()=>Se?.getAttribute(`aria-label`)??r,enabled:i})}}let we=c.actionParsers&&c.actionParsers.length?c.actionParsers:[Pl],Te=c.actionHandlers&&c.actionHandlers.length?c.actionHandlers:[Il.message,Il.messageAndClick];Ve=Rl({parsers:we,handlers:Te,getSessionMetadata:Le,updateSessionMetadata:Re,emit:be.emit,documentRef:typeof document<`u`?document:null}),ut=bu(c,Ve,ct),hd(),Q.updateConfig(c),nf(),(c.features?.history?.enabled===!0!==C||c.features?.history?.provider!==w||c.getIdentityProof!==T||c.clientToken!==E)&&(Nd?.closeHistory({restoreFocus:!1}),Nd?.installHistoryProvider()),Nd?.syncHistoryChromeImpl(),Yd(),Ld()&&!Nd&&qd().catch(()=>{}),Ul(B,Q.getMessages(),ut),ds(),id(),rd(),Pu(Q.isStreaming()),D!==c.contextMentions&&Wp();let Ee=c.voiceRecognition?.enabled===!0,De=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),Oe=Sn(c.voiceRecognition?.provider);if(Ee&&(De||Oe)){if(!K||!Kn){let e=se(c);if(e){K=e.button,Kn=e.wrapper;let t=Wn&&Wn.parentElement===Un?Wn:null;Un?Un.insertBefore(Kn,t):kn?.appendChild(Kn),Y&&(Y.micButton=K),Y?.addListener(K,`click`,cp),K.disabled=Eu()||Q.isStreaming()&&!Du()}}else{let e=c.voiceRecognition??{},t=c.sendButton??{},r=e.iconName??`mic`,i=e.iconSize,a=parseFloat(i??``)||24;K.classList.add(y),K.classList.toggle(ne,!i),K.style.width=i??``,K.style.height=i??``,K.style.minWidth=i??``,K.style.minHeight=i??``;let o=e.iconColor??t.textColor;K.innerHTML=``;let s=M(r,a,o||`currentColor`,1.5);s?K.appendChild(s):K.textContent=`🎤`;let l=e.backgroundColor??t.backgroundColor;l?K.style.backgroundColor=l:K.style.backgroundColor=``,o?K.style.color=o:K.style.color=`var(--persona-text, #111827)`,e.borderWidth?(K.style.borderWidth=e.borderWidth,K.style.borderStyle=`solid`):(K.style.borderWidth=``,K.style.borderStyle=``),e.borderColor?K.style.borderColor=e.borderColor:K.style.borderColor=``,e.paddingX?(K.style.paddingLeft=e.paddingX,K.style.paddingRight=e.paddingX):(K.style.paddingLeft=``,K.style.paddingRight=``),e.paddingY?(K.style.paddingTop=e.paddingY,K.style.paddingBottom=e.paddingY):(K.style.paddingTop=``,K.style.paddingBottom=``);let u=e.tooltipText??`Start voice recognition`,d=e.showTooltip??!1;K.setAttribute(`aria-label`,u),Kn&&n({anchor:K,trigger:Kn,text:()=>K?.getAttribute(`aria-label`)??u,enabled:d}),Kn.style.display=``,K.disabled=Eu()||Q.isStreaming()&&!Du()}}else K&&Kn&&(Kn.style.display=`none`,Sn(c.voiceRecognition?.provider)?Q.isVoiceActive()&&Q.toggleVoice():Rf&&tp());if(_p(),c.attachments?.enabled===!0){if(!Yn||!Jn){let e=c.attachments??{};Zn||(Zn=j(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),Zn.style.display=`none`,(V.parentElement??kn).insertBefore(Zn,V)),Xn||(Xn=document.createElement(`input`),Xn.type=`file`,Xn.accept=(e.allowedTypes??lt).join(`,`),Xn.multiple=(e.maxFiles??4)>1,Xn.style.display=`none`,Xn.setAttribute(`aria-label`,`Attach files`),(V.parentElement??kn).insertBefore(Xn,V)),Yn=j(`div`,`persona-send-button-wrapper`),Jn=j(`button`,`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${y} ${ne}`),Jn.type=`button`,Jn.setAttribute(`aria-label`,e.buttonTooltipText??`Attach file`);let t=e.buttonIconName??`paperclip`;Jn.style.fontSize=`18px`,Jn.style.lineHeight=`1`;let r=M(t,24,`currentColor`,1.5);r?Jn.appendChild(r):Jn.textContent=`📎`,Jn.addEventListener(`click`,e=>{e.preventDefault(),Xn?.click()}),Yn.appendChild(Jn);let i=e.buttonTooltipText??`Attach file`;n({anchor:Jn,trigger:Yn,text:()=>Jn?.getAttribute(`aria-label`)??i}),Hn?Hn.append(Yn):kn.appendChild(Yn),Y&&(Y.attachmentButton=Jn,Y.attachmentInput=Xn??void 0,Y.attachmentPreviews=Zn??void 0),!q&&Xn&&Zn&&(q=Kr.fromConfig(e,Rr),q.setPreviewsContainer(Zn),Y?.addListener(Xn,`change`,async()=>{q&&Xn?.files&&(await q.handleFileSelect(Xn.files),Xn.value=``)}))}else{Yn.style.display=``;let e=c.attachments??{};Xn&&(Xn.accept=(e.allowedTypes??lt).join(`,`),Xn.multiple=(e.maxFiles??4)>1),q&&q.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}if(R.querySelector(`.persona-attachment-drop-overlay`)?.remove(),R.appendChild(xu(c.attachments?.dropOverlay)),Jn){let e=c.attachments??{},t=e.buttonTooltipText??`Attach file`;Jn.setAttribute(`aria-label`,t),Jn.textContent=``;let r=M(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);r?Jn.appendChild(r):Jn.textContent=`📎`,Yn&&n({anchor:Jn,trigger:Yn,text:()=>Jn?.getAttribute(`aria-label`)??t})}}else Yn&&(Yn.style.display=`none`),q&&q.clearAttachments(),R.querySelector(`.persona-attachment-drop-overlay`)?.remove();let ke=c.sendButton??{},Ae=ke.useIcon??!1,je=ke.iconText??`↑`,Me=ke.iconName,Ne=ke.tooltipText??`Send message`,Pe=ke.showTooltip??!1,Fe=ke.size,Ie=parseFloat(Fe??``)||40,ze=ke.backgroundColor,Be=ke.textColor;if(Ae){if(H.style.width=Fe??``,H.style.height=Fe??``,H.style.minWidth=Fe??``,H.style.minHeight=Fe??``,H.style.fontSize=`18px`,H.style.lineHeight=`1`,Be?H.style.color=Be:H.style.color=`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`,!Q.isStreaming()){if(H.innerHTML=``,Me){let e=parseFloat(ke.iconSize??``)||Math.round(Ie*.5),t=Be?.trim()||`currentColor`,n=ke.iconStrokeWidth??2,r=M(Me,e,t,n),i=M(ke.stopIconName??`square`,e,t,n);r&&i?H.appendChild(ae(r,i)):r?H.appendChild(r):H.textContent=je}else H.textContent=je}H.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${y}`,ze?(H.style.backgroundColor=ze,H.classList.remove(`persona-bg-persona-primary`)):(H.style.backgroundColor=``,H.classList.add(`persona-bg-persona-primary`))}else H.textContent=c.copy?.sendButtonLabel??`Send`,H.style.width=``,H.style.height=``,H.style.minWidth=``,H.style.minHeight=``,H.style.fontSize=``,H.style.lineHeight=``,H.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`,ze?(H.style.backgroundColor=ze,H.classList.remove(`persona-bg-persona-accent`)):H.classList.add(`persona-bg-persona-accent`),Be?H.style.color=Be:H.classList.add(`persona-text-white`);ke.borderWidth?(H.style.borderWidth=ke.borderWidth,H.style.borderStyle=`solid`):(H.style.borderWidth=``,H.style.borderStyle=``),ke.borderColor?H.style.borderColor=ke.borderColor:H.style.borderColor=``,ke.paddingX?(H.style.paddingLeft=ke.paddingX,H.style.paddingRight=ke.paddingX):(H.style.paddingLeft=``,H.style.paddingRight=``),ke.paddingY?(H.style.paddingTop=ke.paddingY,H.style.paddingBottom=ke.paddingY):(H.style.paddingTop=``,H.style.paddingBottom=``),Q.isStreaming()||H.setAttribute(`aria-label`,Ne),ju(),Wn&&n({anchor:H,trigger:Wn,text:()=>H.getAttribute(`aria-label`)??Ne,enabled:Pe}),ia(),Fo();let Ue=Fi(J.getState().activeModeIds,c.composer?.modes);J.setActiveModeIds(Ue),Vr().length>0!=!!Jr&&$i(),Jr?.render(Ue,Vr());for(let e of[...Xr.keys()])Ai(e,c.composer?.modeGroups)||Xr.delete(e);Xr.forEach(e=>e.repaint()),Gr?.repaint(),ji?.resolve();let Ge=Ga(c,N());if(ko(),Ge){B.style.maxWidth=Ge,B.style.marginLeft=`auto`,B.style.marginRight=`auto`,B.style.width=`100%`,Nn.style.maxWidth=Ge,Nn.style.marginLeft=`auto`,Nn.style.marginRight=`auto`,Nn.style.width=`100%`;for(let e of[kn,En,Zn,U])e&&(e.style.maxWidth=Ge,e.style.marginLeft=`auto`,e.style.marginRight=`auto`,e.style.width=`100%`)}else{B.style.maxWidth=``,B.style.marginLeft=``,B.style.marginRight=``,B.style.width=``,Nn.style.maxWidth=``,Nn.style.marginLeft=``,Nn.style.marginRight=``,Nn.style.width=``;for(let e of[kn,En,Zn,U])e&&(e.style.maxWidth=``,e.style.marginLeft=``,e.style.marginRight=``,e.style.width=``)}let Ke=c.statusIndicator??{};if(r(U,kn,Ke),i(U,Ke,Q?.getStatus()??`idle`),Q){let e=Q.getStatus();vn(U,(e=>e===`idle`?Ke.idleText??gt.idle:e===`connecting`?Ke.connectingText??gt.connecting:e===`connected`?Ke.connectedText??gt.connected:e===`error`?Ke.errorText??gt.error:e===`paused`?Ke.pausedText??gt.paused:e===`resuming`?Ke.resumingText??gt.resuming:gt[e])(e),Ke,e)}U.classList.remove(`persona-text-left`,`persona-text-center`,`persona-text-right`);let qe=Ke.align===`left`?`persona-text-left`:Ke.align===`center`?`persona-text-center`:`persona-text-right`;U.classList.add(qe),vi(),Nu(),ra(),cn()},open(){at()&&wu(!0,`api`)},close(){at()&&wu(!1,`api`)},toggle(){at()&&wu(!P,`api`)},reconnect(){Q.reconnectNow()},clearChat(){Sa=!1,f.clear(),u.clear(),d.clear(),p.clear(),Q.clearMessages(),c.layout?.topFade&&(z.scrollTop=0),z.removeAttribute(`data-persona-top-fade`),vs.clear(),rl();try{localStorage.removeItem(uu),c.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${uu}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(c.clearChatHistoryStorageKey&&c.clearChatHistoryStorageKey!==uu)try{localStorage.removeItem(c.clearChatHistoryStorageKey),c.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${c.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let e=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(e),xe?.clear&&Oc(()=>xe.clear(),`[AgentWidget] Failed to clear storage adapter:`),Te={},Ve.syncFromMetadata(),q?.clearAttachments(),Bc(),ri(void 0),$r(void 0),ks(),qt?.clear(),Jt?.reset(),Qt?.update()},setMessage(e){return!V||Q.isStreaming()||Eu()?!1:(!P&&at()&&wu(!0,`system`),V.value=e,V.dispatchEvent(new Event(`input`,{bubbles:!0})),!0)},submitMessage(e){if(Q.isStreaming()||Ou())return!1;let t=e?.trim()||V.value.trim();return t?(!P&&at()&&wu(!0,`system`),V.value=``,V.style.height=`auto`,Fr(),wf(t,{consumeDraft:!1}),!0):!1},getComposerState(){return J.getState()},setQuote(e){let t=e?.text?.trim();t&&$r({...e,text:t})},clearQuote(){$r(void 0)},startVoiceRecognition(){return Q.isStreaming()?!1:Sn(c.voiceRecognition?.provider)?(Q.isVoiceActive()||Q.isBargeInActive()||(!P&&at()&&wu(!0,`system`),$.manuallyDeactivated=!1,yc(),Q.toggleVoice().then(()=>{$.active=gc(),yc(),vc(`user`),$.active&&ip()})),!0):Rf?!0:$f()?(!P&&at()&&wu(!0,`system`),$.manuallyDeactivated=!1,yc(),ep(`user`),!0):!1},stopVoiceRecognition(){return Sn(c.voiceRecognition?.provider)?!Q.isVoiceActive()&&!Q.isBargeInActive()?!1:((Q.isBargeInActive()?Q.deactivateBargeIn():Q.toggleVoice()).then(()=>{$.active=!1,$.manuallyDeactivated=!0,yc(),vc(`user`),sp()}),!0):Rf?($.manuallyDeactivated=!0,yc(),tp(`user`),!0):!1},injectMessage(e){return!P&&at()&&wu(!0,`system`),Q.injectMessage(e)},injectAssistantMessage(e){!P&&at()&&wu(!0,`system`);let t=Q.injectAssistantMessage(e);return ot&&(ot=!1,st&&=(clearTimeout(st),null),setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)),t},injectUserMessage(e){return!P&&at()&&wu(!0,`system`),Q.injectUserMessage(e)},injectSystemMessage(e){return!P&&at()&&wu(!0,`system`),Q.injectSystemMessage(e)},injectMessageBatch(e){return!P&&at()&&wu(!0,`system`),Q.injectMessageBatch(e)},injectComponentDirective(e){return!P&&at()&&wu(!0,`system`),Q.injectComponentDirective(e)},injectTestMessage(e){!P&&at()&&wu(!0,`system`),Q.injectTestEvent(e)},async connectStream(e,t){return Q.connectStream(e,t)},__pushEventStreamEvent(e){mt&&(an(),rn(e.type,e.payload))},showEventStream(){mt&&ui()},hideEventStream(){$t&&di()},isEventStreamVisible(){return $t},listConversations(e){return Q.listConversations(e)},getActiveConversationId(){return Q.getActiveConversationId()},openConversation(e,t){return Jd(n=>n.openHistoryConversation(e,{focusComposer:t?.focus===!0}))},startNewConversation(e){return Jd(t=>t.startNewConversation({focusComposer:e?.focus===!0}))},warmSession(){Xd()},deleteConversation(e){return Jd(t=>t.deleteHistoryConversation(e))},renameConversation(e,t){return Jd(n=>n.updateHistoryConversation(e,{title:t}))},setConversationStarred(e,t){return Jd(n=>n.updateHistoryConversation(e,{starred:t}))},clearConversationHistory(e){return Jd(t=>t.clearConversationHistory(e))},resetHistoryIdentity(){return Jd(e=>e.resetHistoryIdentity())},async getVisitorToken(){let e=fd;if(!e)return null;let t=await e.get();return e===fd?t:null},getHistoryIdentityStatus(){let e=Nd?.historyProvider;return e?e.getIdentityStatus():Ld()?{state:`unavailable`,reason:`ineligible_mode`}:{state:`unavailable`,reason:`history_disabled`}},showHistory(e){return Ld()?Jd(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...e?.focus===void 0?{}:{focus:e.focus}})):Promise.resolve()},hideHistory(e){Nd?.closeHistory(e?.restoreFocus===void 0?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible(){return on},showArtifacts(){Ic(c)&&(Sa=!1,Ta=!0,To(),X?.setMobileOpen(!0))},hideArtifacts(){Ic(c)&&(Sa=!0,To())},upsertArtifact(e){return Ic(c)?(et(c.features?.artifacts,{artifactType:e.artifactType,...e.artifactType===`markdown`&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})===`panel`&&(Sa=!1,Ta=!0),Q.upsertArtifact(e)):null},selectArtifact(e){Ic(c)&&Q.selectArtifact(e)},clearArtifacts(){Ic(c)&&Q.clearArtifacts()},getArtifacts(){return Q?.getArtifacts()??[]},getSelectedArtifactId(){return Q?.getSelectedArtifactId()??null},focusInput(){return He&&!P&&!N()||!V?!1:(V.focus(),!0)},async resolveApproval(e,t,n){let r=Q.getMessages().find(t=>t.variant===`approval`&&t.approval?.id===e);if(!r?.approval)throw Error(`Approval not found: ${e}`);if(r.approval.toolType===`webmcp`)Q.resolveWebMcpApproval(r.id,t);else return Q.resolveApproval(r.approval,t,n)},setFollowUpSuggestions(e){ms(e)},clearFollowUpSuggestions(){fs()},getMessages(){return Q.getMessages()},getStatus(){return Q.getStatus()},getPersistentMetadata(){return{...Te}},updatePersistentMetadata(e){Re(e)},on(e,t){return be.on(e,t)},off(e,t){be.off(e,t)},isOpen(){return at()&&P},isVoiceActive(){return $.active},toggleReadAloud(e){Q.toggleReadAloud(e)},stopReadAloud(){Q.stopSpeaking()},getReadAloudState(e){return Q.getReadAloudState(e)},onReadAloudChange(e){return Q.onReadAloudChange(e)},getState(){return{open:at()&&P,launcherEnabled:He,voiceActive:$.active,streaming:Q.isStreaming()}},showCSATFeedback(e){!P&&at()&&wu(!0,`system`);let t=B.querySelector(`.persona-feedback-container`);t&&t.remove();let n=cu({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitCSATFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});B.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},showNPSFeedback(e){!P&&at()&&wu(!0,`system`);let t=B.querySelector(`.persona-feedback-container`);t&&t.remove();let n=lu({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitNPSFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});B.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},async submitCSATFeedback(e,t){return Q.submitCSATFeedback(e,t)},async submitNPSFeedback(e,t){return Q.submitNPSFeedback(e,t)},destroy(){kd(),gd!=null&&(clearInterval(gd),gd=null),f.clear(),u.clear(),d.clear(),p.clear(),Z.forEach(e=>e()),F.remove(),Cn?.remove(),Sp?.destroy(),Cp?.remove(),Zo&&W.removeEventListener(`click`,Zo)}};if(((o?.debugTools??!1)||c.debug)&&typeof window<`u`){let e=window.AgentWidgetBrowser,t={controller:am,getMessages:am.getMessages,getStatus:am.getStatus,getMetadata:am.getPersistentMetadata,updateMetadata:am.updatePersistentMetadata,clearHistory:()=>am.clearChat(),setVoiceActive:e=>e?am.startVoiceRecognition():am.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Z.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<`u`){let e=t.getAttribute(`data-persona-instance`)||t.id||`persona-`+Math.random().toString(36).slice(2,8),n=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&am.focusInput()};if(window.addEventListener(`persona:focusInput`,n),Z.push(()=>{window.removeEventListener(`persona:focusInput`,n)}),mt){let t=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&am.showEventStream()},n=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&am.hideEventStream()};window.addEventListener(`persona:showEventStream`,t),window.addEventListener(`persona:hideEventStream`,n),Z.push(()=>{window.removeEventListener(`persona:showEventStream`,t),window.removeEventListener(`persona:hideEventStream`,n)})}let r=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&am.showHistory()},i=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&am.hideHistory()};window.addEventListener(`persona:showHistory`,r),window.addEventListener(`persona:hideHistory`,i),Z.push(()=>{window.removeEventListener(`persona:showHistory`,r),window.removeEventListener(`persona:hideHistory`,i)});let a=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&am.showArtifacts()},o=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&am.hideArtifacts()},s=t=>{let n=t.detail;n?.instanceId&&n.instanceId!==e||n?.artifact&&am.upsertArtifact(n.artifact)},c=t=>{let n=t.detail;n?.instanceId&&n.instanceId!==e||typeof n?.id==`string`&&am.selectArtifact(n.id)},l=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&am.clearArtifacts()};window.addEventListener(`persona:showArtifacts`,a),window.addEventListener(`persona:hideArtifacts`,o),window.addEventListener(`persona:upsertArtifact`,s),window.addEventListener(`persona:selectArtifact`,c),window.addEventListener(`persona:clearArtifacts`,l),Z.push(()=>{window.removeEventListener(`persona:showArtifacts`,a),window.removeEventListener(`persona:hideArtifacts`,o),window.removeEventListener(`persona:upsertArtifact`,s),window.removeEventListener(`persona:selectArtifact`,c),window.removeEventListener(`persona:clearArtifacts`,l)})}let om=gu(c.persistState);if(om&&at()){let e=_u(om.storage),n=`${om.keyPrefix}widget-open`,r=`${om.keyPrefix}widget-voice`,i=`${om.keyPrefix}widget-voice-mode`;if(e){let a=om.persist?.openState&&e.getItem(n)===`true`,o=om.persist?.voiceState&&e.getItem(r)===`true`,s=om.persist?.voiceState&&e.getItem(i)===`true`;if(a&&(Sp?.setPanelOpen(!0,`auto`),setTimeout(()=>{am.open(),setTimeout(()=>{if(o||s)am.startVoiceRecognition();else if(om.persist?.focusInput){let e=t.querySelector(`textarea`);e&&e.focus()}},100)},0)),om.persist?.openState&&(be.on(`widget:opened`,()=>{e.setItem(n,`true`)}),be.on(`widget:closed`,()=>{e.setItem(n,`false`)})),om.persist?.voiceState&&(be.on(`voice:state`,t=>{e.setItem(r,t.active?`true`:`false`)}),be.on(`user:message`,t=>{e.setItem(i,t.viaVoice?`true`:`false`)})),om.clearOnChatClear){let t=()=>{e.removeItem(n),e.removeItem(r),e.removeItem(i)},a=()=>t();window.addEventListener(`persona:clear-chat`,a),Z.push(()=>{window.removeEventListener(`persona:clear-chat`,a)})}}}if(Fe&&at()&&(Sp?.setPanelOpen(!0,`auto`),setTimeout(()=>{am.open()},0)),su(),!Ps){let e=Se(()=>{Q&&(As++,vs.clear(),Ul(B,Q.getMessages(),ut))});Z.push(e)}oe=()=>{Q&&(As++,vs.clear(),Ul(B,Q.getMessages(),ut))},Q.getMessages().length>0&&Vl(),he=()=>{Q&&(As++,vs.clear(),Ul(B,Q.getMessages(),ut))};let sm=ge(()=>{Q&&(As++,vs.clear(),Ul(B,Q.getMessages(),ut))});Z.push(sm);let cm=Fc(()=>{Q&&(As++,vs.clear(),Ul(B,Q.getMessages(),ut),Pc()?.updateInlineArtifactBlocks(B,xa.artifacts,{suppressTransition:!0}),To())});return Z.push(cm),am},Tu=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let i=/^(\d+(?:\.\d+)?)%$/i.exec(n);return i?Math.max(0,t*parseFloat(i[1])/100):420},Eu=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},Du=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},Ou=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement(`div`);r.style.cssText=`width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;`,n.appendChild(r);let i=r.offsetHeight>0;r.style.height=`100%`;let a=r.offsetHeight>0;r.remove(),i&&!a&&console.warn(`[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout.`+(t.maxHeight===!1?` The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.`:` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},ku=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className=`persona-host`,e.style.height=n?``:`100%`,e.style.display=n?``:`flex`,e.style.flexDirection=n?``:`column`,e.style.flex=n?``:`1 1 auto`,e.style.minHeight=n?``:`0`,e.style.minWidth=n?``:`0`},Au=e=>{e.style.position=``,e.style.top=``,e.style.bottom=``,e.style.left=``,e.style.right=``,e.style.zIndex=``,e.style.transform=``,e.style.pointerEvents=``},ju=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,Au(e)},Mu=e=>{e.style.transition=``},Nu=e=>{e.style.display=``,e.style.flexDirection=``,e.style.flex=``,e.style.minHeight=``,e.style.minWidth=``,e.style.width=``,e.style.height=``,e.style.alignItems=``,e.style.transition=``,e.style.transform=``,e.style.marginLeft=``},Pu=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},Fu=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},Iu=(e,t,n,r,i)=>{i?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Lu=(e,t,n,r,i,a)=>{let o=a?t:e;i===`left`?o.firstElementChild!==r&&o.replaceChildren(r,n):o.lastElementChild!==r&&o.replaceChildren(n,r)},Ru=e=>{let t=Va(e),n=t.components?.panel,r=(e,n)=>e==null||e===``?n:ha(t,e)??e;return{inset:r(n?.inset,ta),canvasBackground:r(n?.canvasBackground,na)}},zu=(e,t,n,r)=>{t?(e.style.boxSizing=`border-box`,e.style.padding=n,e.style.background=r):(e.style.padding=``,e.style.background=``,e.style.boxSizing=``)},Bu=(e,t,n,r,i,a,o,s)=>{let c=ho(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;Iu(e,t,n,r,l),Lu(e,t,n,r,c.side,l),e.dataset.personaHostLayout=`docked`,e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=o?`true`:`false`,e.style.width=`100%`,e.style.maxWidth=`100%`,e.style.minWidth=`0`,e.style.height=`100%`,e.style.minHeight=`0`,e.style.position=`relative`,n.style.display=`flex`,n.style.flexDirection=`column`,n.style.minHeight=`0`,n.style.position=`relative`,i.className=`persona-host`,i.style.height=`100%`,i.style.minHeight=`0`,i.style.minWidth=`0`,i.style.display=`flex`,i.style.flexDirection=`column`,i.style.flex=`1 1 auto`;let p=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,h=a?.launcher?.mobileBreakpoint??640,g=p!=null&&p.innerWidth<=h;if(m&&g&&o)e.dataset.personaDockMobileFullscreen=`true`,e.removeAttribute(`data-persona-dock-reveal`),Nu(t),Mu(r),ju(r),Pu(n),Fu(i,r),zu(r,!1,``,``),e.style.display=`flex`,e.style.flexDirection=`column`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.minWidth=`0`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.position=`fixed`,r.style.inset=`0`,r.style.width=`100%`,r.style.height=`100%`,r.style.maxWidth=`100%`,r.style.minWidth=`0`,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.zIndex=String(a?.launcher?.zIndex??1e5),r.style.transform=`none`,r.style.transition=`none`,r.style.pointerEvents=`auto`,r.style.flex=`none`,l&&(t.style.display=`flex`,t.style.flexDirection=`column`,t.style.width=`100%`,t.style.height=`100%`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.flex=`1 1 auto`,t.style.alignItems=`stretch`,t.style.transform=`none`,t.style.marginLeft=`0`,t.style.transition=`none`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.maxWidth=`100%`,n.style.minWidth=`0`);else if(e.removeAttribute(`data-persona-dock-mobile-fullscreen`),ju(r),Eu(r,c.maxHeight),zu(r,u&&o,d,f),c.reveal===`overlay`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`overlay`,Nu(t),Mu(r),Pu(n),Fu(i,r);let a=c.animate?`transform 180ms ease`:`none`,s=c.side===`right`?`translateX(100%)`:`translateX(-100%)`,l=o?`translateX(0)`:s;r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`none`,r.style.position=`absolute`,r.style.top=`0`,r.style.bottom=`0`,r.style.width=c.width,r.style.maxWidth=c.width,r.style.minWidth=c.width,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.transition=a,r.style.transform=l,r.style.pointerEvents=o?`auto`:`none`,r.style.zIndex=`2`,c.side===`right`?(r.style.right=`0`,r.style.left=``):(r.style.left=`0`,r.style.right=``)}else if(c.reveal===`push`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`push`,Mu(r),Au(r),Fu(i,r);let a=Tu(c.width,e.clientWidth),s=Math.max(0,e.clientWidth),l=c.animate?`margin-left 180ms ease`:`none`,u=c.side===`right`?o?-a:0:o?0:-a;t.style.display=`flex`,t.style.flexDirection=`row`,t.style.flex=`0 0 auto`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.alignItems=`stretch`,t.style.height=`100%`,t.style.width=`${s+a}px`,t.style.transition=l,t.style.marginLeft=`${u}px`,t.style.transform=``,n.style.flex=`0 0 auto`,n.style.flexGrow=`0`,n.style.flexShrink=`0`,n.style.width=`${s}px`,n.style.maxWidth=`${s}px`,n.style.minWidth=`${s}px`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 auto`,r.style.flexShrink=`0`,r.style.width=c.width,r.style.minWidth=c.width,r.style.maxWidth=c.width,r.style.position=`relative`,r.style.top=``,r.style.overflow=`hidden`,r.style.transition=`none`,r.style.pointerEvents=o?`auto`:`none`}else{e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=``,Nu(t),Au(r),Pu(n),Fu(i,r);let a=c.reveal===`emerge`;a?e.dataset.personaDockReveal=`emerge`:e.removeAttribute(`data-persona-dock-reveal`);let s=o?c.width:`0px`,l=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?`, padding 180ms ease`:``}`:`none`,f=!o;if(r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 ${s}`,r.style.width=s,r.style.maxWidth=s,r.style.minWidth=s,r.style.minHeight=`0`,Du(r,c.maxHeight),r.style.overflow=a||f?`hidden`:`visible`,r.style.transition=l,a){r.style.alignItems=c.side===`right`?`flex-start`:`flex-end`;let t=u?`calc(${Tu(c.width,e.clientWidth)}px - (2 * ${d}))`:c.width;i.style.width=t,i.style.minWidth=t,i.style.maxWidth=t,i.style.boxSizing=`border-box`}}},Vu=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return ku(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){ku(n,e)},destroy(){n.remove()}}},Hu=(e,t)=>{let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw Error(`Docked widget target must be attached to the DOM`);let i=e.tagName.toUpperCase();if(i===`BODY`||i===`HTML`)throw Error(`Docked widget target must be a concrete container element, not "body" or "html"`);let a=e.nextSibling,o=n.createElement(`div`),s=n.createElement(`div`),c=n.createElement(`div`),l=n.createElement(`aside`),u=n.createElement(`div`),d=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;s.dataset.personaDockRole=`push-track`,c.dataset.personaDockRole=`content`,l.dataset.personaDockRole=`panel`,u.dataset.personaDockRole=`host`,l.appendChild(u),r.insertBefore(o,e),c.appendChild(e);let f=null,p=()=>{f?.disconnect(),f=null},m=null,h=()=>{m=t?.launcher?.detachedPanel===!0?Ru(t):null};h();let g=()=>{Bu(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=Wa(()=>{h(),g()}))},y=()=>{p(),ho(t).reveal===`push`&&typeof ResizeObserver<`u`&&(f=new ResizeObserver(()=>{g()}),f.observe(o))},b=!1,x=()=>{g(),y(),d&&!b&&o.dataset.personaDockMobileFullscreen!==`true`&&(b=!0,Ou(o,ho(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),ho(t).reveal===`push`?(s.appendChild(c),s.appendChild(l),o.appendChild(s)):(o.appendChild(c),o.appendChild(l)),x(),v(),{mode:`docked`,host:u,shell:o,syncWidgetState(e){let t=!e.launcherEnabled||e.open;d!==t&&(d=t,x())},updateConfig(e){t=e,(t?.launcher?.enabled??!0)===!1&&(d=!0),h(),x(),v()},destroy(){S?.removeEventListener(`resize`,C),_?.(),_=null,p(),r.isConnected&&(a&&a.parentNode===r?r.insertBefore(e,a):r.appendChild(e)),o.remove()}}},Uu=(e,t)=>po(t)?Hu(e,t):Vu(e,t),Wu={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Gu=`persona-preview-shell-theme`,Ku={load:()=>null,save:()=>{},clear:()=>{}},qu=[`How do I get started?`,`Pricing & plans`,`Talk to support`];function Ju(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function Yu(e){return e===`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 Xu(e){let t=Yu(e);return`* { box-sizing: border-box; }
|
|
121
|
+
${k?`background: transparent !important;`:``}
|
|
122
|
+
`)}if(!o&&!n){let e=r?``:`padding-top: 1.25em !important;`,t=r?``:`z-index: ${i.launcher?.zIndex??1e5} !important;`;I.style.cssText+=`max-height: -moz-available !important; max-height: stretch !important;`+e+t}kr(),ye()},wo=()=>{t.style.setProperty(`--persona-content-max-width`,$a(i,P()))},Eo=!1;function Do(){i.layout?.topFade&&B.scrollTop>1?B.setAttribute(`data-persona-top-fade`,`true`):B.removeAttribute(`data-persona-top-fade`)}let Oo=()=>{Do();let e=eo(i,P());P()&&i.composer?.placement&&i.debug===!0&&!Eo&&(Eo=!0,console.warn(`[persona] composer.placement is ignored in composer-bar mount mode.`));let n=xr();t.setAttribute(`data-persona-composer-placement`,e),t.setAttribute(`data-persona-conversation-state`,Sr),t.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`),t.style.setProperty(`--persona-composer-anchor-gap`,n.composerGap??`24px`),Ar()},Mo=()=>{if(P())return;let e=xo(i),n=i.launcher?.sidebarMode??!1;if(e||n||(i.launcher?.fullHeight??!1)||!Be)return;let r=t.ownerDocument.defaultView??window,a=i.launcher?.mobileFullscreen??!0,o=i.launcher?.mobileBreakpoint??640;if(a&&r.innerWidth<=o)return;let s=Us(i);L.style.height=s.height,L.style.maxHeight=s.maxHeight};bo(),Za(t,i),Xc(t,i),Zc(t,i),wo(),Oo(),va=()=>{bo(),Mo(),Za(t,i),Xc(t,i),Zc(t,i),wo(),Oo(),ba?t.style.setProperty(`--persona-artifact-welded-outer-radius`,ba):t.style.removeProperty(`--persona-artifact-welded-outer-radius`),ln(),cn()};let Z=[];Z.push(()=>{ga=!0}),Z.push(()=>{m.forEach(e=>e()),p.destroy()}),Z.push(()=>{document.removeEventListener(`keydown`,La)}),Z.push(()=>{_r!==null&&clearTimeout(_r)});let Fo=null,Io=null;Z.push(()=>{Fo?.(),Fo=null,Io?.(),Io=null}),_a&&Z.push(()=>{_a?.disconnect(),_a=null}),Z.push(()=>{Ba?.(),Ba=null,qa(),za&&=(za.remove(),null),X?.element.style.removeProperty(`width`),X?.element.style.removeProperty(`maxWidth`),X?.destroy()}),ft&&Z.push(()=>{Ot=!0,Et=null,$t!==null&&(cancelAnimationFrame($t),$t=null),Xt?.destroy(),Xt=null,St?.destroy(),St=null,yt=null});let Ro=null,zo=()=>{Ro&&=(Ro(),null),i.colorScheme===`auto`&&(Ro=Qa(()=>{Za(t,i)}))};zo(),Z.push(()=>{Ro&&=(Ro(),null)}),Z.push(()=>{E=!0,T?.()}),Z.push(()=>{ie=!0});let Ho=!1;Z.push(()=>{Ho=!0});let Uo=(e,n)=>{let r=Ht(e,n);return r||!qt.includes(e)?r:(ho().then(r=>{if(Ho)return;Kt(r.wipe),Kt(r.glyphCycle);let i=Ht(e,n);i&&Wt(i,t)}).catch(()=>{}),null)},Wo=i.features?.streamAnimation;if(Wo?.type&&Wo.type!==`none`){let e=Uo(Wo.type,Wo.plugins);e&&Wt(e,t),Z.push(()=>zt(t))}let Go=Ao(En),Jo=Ao(wn),Xo=Ao(Tn),Zo=[Go,Jo,Xo];Z.push(()=>{Zo.forEach(e=>e.destroy())});let Qo=null,Q,$o=null,es=!1,ts=0,ns=null,rs=e=>e.reduce((e,t)=>t.role===`user`?e+1:e,0),is=e=>{for(let t=e.length-1;t>=0;t--)if(nt(e[t]))return e[t].id??null;return null},as=!1,os=()=>{as||i.debug!==!0||(as=!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".`))},ss=!1,cs=!1,ls=(e,t)=>{ss||i.debug!==!0||t.enabled&&!t.expose&&(es||cs&&(Q.isStreaming()||e.some(nt)||(ss=!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.`))))},us=e=>{if(!Q)return;let t=e??Q.getMessages(),n=e=>{e.render([],Q,H,t)},r=e=>{Zo.forEach(t=>{t!==e&&n(t)})};$o&&(rs(t)>ts||is(t)!==ns)&&($o=null);let a=et(i);ls(t,a);let o=a.enabled?tt(t):null,s=$o??o,c=$o?`host`:`agent`;if(s){let e=i.suggestions?.followUps,n=e?.placement??(e?`auto`:`composer`),a=(n===`auto`?P()?`composer`:`after-message`:n)===`after-message`?Xo:Go;r(a),a.render(s,Q,H,t,i.suggestionChipsConfig,{source:c,surface:`followUp`,variant:e?.variant??`chip`,behavior:e?.behavior??`send`,overflow:e?.overflow??`wrap`,maxItems:e?.maxItems??4,config:i,plugins:f,submitPrompt:Tf});return}if(t.some(e=>e.role===`user`)){Zo.forEach(n);return}let l=i.future?.v5Defaults===!0,u=br(),d=i.suggestions?.starters??(l?{}:void 0);if(d){let e=Vs(xr(),t),a=d.placement??`auto`,o=a===`auto`?e?`welcome`:`composer`:a;if(o===`welcome`&&!e){os(),Zo.forEach(n);return}let s=o===`welcome`?Jo:Go;r(s),s.render(d.items??i.suggestionChips,Q,H,t,i.suggestionChipsConfig,{surface:`starter`,variant:d.variant??(l&&!u?`chip`:`card`),behavior:d.behavior??`send`,overflow:d.overflow??`wrap`,maxItems:d.maxItems??(l&&!u?3:4),config:i,plugins:f,submitPrompt:Tf})}else r(Go),Go.render(i.suggestionChips,Q,H,t,i.suggestionChipsConfig,{surface:`starter`,variant:`chip`,behavior:`send`,overflow:`wrap`,maxItems:4,config:i,plugins:f,submitPrompt:Tf})},fs=()=>{$o&&($o=null,us())},ps=e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length){fs();return}let n=Q?Q.getMessages():[];$o=t,es=!0,ts=rs(n),ns=is(n),us(n)},ms=!1,gs=co(),_s=/* @__PURE__ */ new Map,vs=/* @__PURE__ */ new Map,ys=/* @__PURE__ */ new Map,bs=null,Ss=null;function Cs(){if(!bs)return;let e=bs;bs=null,Ss?.destroy(),Ss=null,gs.delete(e),z.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),Q&&Bl(V,Q.getMessages(),lt)}let Es=0,Ds=Re()!==null,Os=It(),js=0,Ns=null,Is=!1,Ls=!1,Rs=0,Hs=null,Ws=null,qs=!1,Js=!1,Ys=null,Xs=!0,Zs=!1,Qs=null,$s=!1,ec=()=>{$s=!0,ic()},tc=null,nc=null,rc=()=>{t.setAttribute(`data-persona-scrollbar`,cr()),cr()!==`on-scroll`&&(nc!==null&&clearTimeout(nc),nc=null,B.removeAttribute(`data-persona-scrollbar-visible`))},ic=()=>{cr()===`on-scroll`&&(B.setAttribute(`data-persona-scrollbar-visible`,``),nc!==null&&clearTimeout(nc),nc=setTimeout(()=>{nc=null,Lt(B,24)&&B.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};rc(),Z.push(()=>{nc!==null&&clearTimeout(nc)});let ac=/* @__PURE__ */ new Map,cc=!1,lc=null,$={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Vi();let pc=i.voiceRecognition?.autoResume??!1,mc=()=>Q.isVoiceActive()||Q.isBargeInActive(),hc=!1,gc=e=>{O.emit(`voice:state`,{active:$.active,source:e,timestamp:Date.now()})},vc=()=>{Ne(e=>({...e,voiceState:{active:$.active,timestamp:Date.now(),manuallyDeactivated:$.manuallyDeactivated}}))},yc=()=>{if(i.voiceRecognition?.enabled===!1)return;let e=Du(pe.voiceState),t=!!e.active,n=Number(e.timestamp??0);$.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-n<3e4&&setTimeout(()=>{$.active||($.manuallyDeactivated=!1,Cn(i.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=mc(),gc(`restore`),$.active?op():(vc(),mf(`Tap the mic to resume your voice call`,1e4))}):np(`restore`))},Cn(i.voiceRecognition?.provider)?0:1e3)},bc=e=>{hc=!e.persisted,$.active&&vc()};typeof window<`u`&&(window.addEventListener(`pagehide`,bc),Z.push(()=>window.removeEventListener(`pagehide`,bc)));let xc=()=>Q?Ou(Q.getMessages()).filter(e=>!e.__skipPersist):[],wc=null,Tc=(e,t)=>{typeof console<`u`&&console.error(e,t)},Ec=(e,t)=>{let n=()=>{try{let n=e();return!n||typeof n.then!=`function`?null:Promise.resolve(n).catch(e=>{Tc(t,e)})}catch(e){return Tc(t,e),null}},r=wc,i=r?r.then(()=>n()??void 0):n();if(!i)return;let a=i.finally(()=>{wc===a&&(wc=null)});wc=a};function Dc(e){if(!fe?.save)return;let t=e?Ou(e):Q?xc():[],n=k&&Q?.getResumableHandle();n&&(pe={...pe,durableResume:{executionId:n.executionId,after:n.lastEventId}});let r={messages:t,metadata:pe,artifacts:xa.artifacts,selectedArtifactId:xa.selectedId,...Ac?{draft:Ac}:{}};Ec(()=>fe.save(r),`[AgentWidget] Failed to persist state:`)}let Ac,jc=()=>!fe?.save||i.persistState===!1?!1:typeof i.persistState!=`object`||i.persistState.persist?.draft!==!1,Nc=Qi({write:()=>{if(!jc())return;let e=J.getState(),t=Xi({text:e.text,mentionRefs:e.mentionRefs,contentSegments:lf(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(Ac)&&(Ac=t,Dc())}});function Pc(){jc()&&Nc.schedule()}function Fc(){Nc.flush()}function Ic(e){if(!jc())return;let t=Zi(e,{mentionSourceIds:(i.contextMentions?.sources??[]).map(e=>e.id),modelIds:(i.composer?.models??[]).map(e=>e.id),modes:i.composer?.modes??[]});t&&(Ac=e,H&&!H.value&&(H.value=t.text,H.dispatchEvent(new Event(`input`,{bubbles:!0})),Ir()),t.selectedModelId&&(J.setSelectedModelId(t.selectedModelId),Gr?.repaint()),Ur(t.activeModeIds??[]),t.quote&&Zr(t.quote),Nc.cancel())}function Lc(){Nc.cancel(),Ac&&(Ac=void 0,jc()&&Dc())}let Rc=null,zc=()=>I.querySelector(`#persona-scroll-container`)||B,Bc=()=>{Rc!==null&&(cancelAnimationFrame(Rc),Rc=null),Is=!1},Gc=()=>{Ns!==null&&(cancelAnimationFrame(Ns),Ns=null),Ls=!1,Bc()},Kc=()=>ms&&el()&&(tr()!==`anchor-top`||or()),qc=()=>{let e=Zn()||`Jump to latest`,t=Kc();lr.toggleAttribute(`data-persona-scroll-to-bottom-streaming`,t),Rs>0?(mr.textContent=String(Rs),mr.style.display=``,lr.setAttribute(`aria-label`,`${e} (${Rs} new)`)):(mr.textContent=``,mr.style.display=`none`,lr.setAttribute(`aria-label`,t?`${e} (response streaming below)`:e))},Jc=()=>{Rs!==0&&(Rs=0,qc())},$c=()=>{let e=Hs?.spacerHeight??0;return e<=0?Lt(B,24):ml(e)-B.scrollTop-B.clientHeight<=24},el=()=>nr()?!Os.isFollowing():!$c(),tl=()=>!!Q&&Q.getMessages().length>0,nl=()=>{if(!er()||pn()){lr.parentNode&&lr.remove(),lr.style.display=`none`;return}lr.parentNode!==z&&z.appendChild(lr),Or();let e=Mt(B)>0&&el()&&tl();e?qc():Jc(),lr.style.display=e?``:`none`},rl=()=>{Os.pause()&&(Gc(),nl())},il=()=>{Os.resume(),Jc(),nl()},al=(e=!1)=>{nr()&&tl()&&Os.isFollowing()&&(e||ms)&&(Ns!==null&&(cancelAnimationFrame(Ns),Ns=null),Ls=!0,Ns=requestAnimationFrame(()=>{Ns=null,Ls=!1,Os.isFollowing()&&sl(zc(),e?220:140)}))},ol=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(Bc(),Math.abs(o)<1){Is=!0,e.scrollTop=a,js=e.scrollTop,Is=!1;return}let s=performance.now();Is=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){Bc();return}let d=t();d!==a&&(a=d,o=a-i);let f=u-s,p=Math.min(f/n,1),m=c(p);e.scrollTop=i+o*m,js=e.scrollTop,p<1?Rc=requestAnimationFrame(l):(e.scrollTop=a,js=e.scrollTop,Rc=null,Is=!1)};Rc=requestAnimationFrame(l)},sl=(e,t=500)=>{let n=Mt(e)-e.scrollTop;Math.abs(n)<1?js=e.scrollTop:Math.abs(n)>=80?(Bc(),Is=!0,e.scrollTop=Mt(e),js=e.scrollTop,Is=!1):ol(e,()=>Mt(e),t,()=>Os.isFollowing())},cl=()=>{if(!tl()){nl();return}let e=zc();Is=!0,e.scrollTop=Mt(e),js=e.scrollTop,Is=!1,nl()},ll=e=>{let t=0,n=e;for(;n&&n!==B;)t+=n.offsetTop,n=n.offsetParent;return t},ul=()=>{let e=B.getRootNode();return(typeof e.getSelection==`function`?e.getSelection():null)??B.ownerDocument.getSelection()},dl=()=>At(ul(),B),fl=()=>{if(ir()!==`last-user-turn`)return!1;let e=Q?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>e.role===`user`);if(!t)return!1;let n=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(t.id):t.id.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),r=B.querySelector(`[data-message-id="${n}"]`);if(!r)return!1;let i=Math.min(Math.max(0,ll(r)-rr()),Mt(B));return Is=!0,B.scrollTop=i,js=B.scrollTop,Is=!1,tr()===`follow`&&!Lt(B,24)&&Os.pause(),nl(),!0},pl=e=>{let t=Math.max(0,Math.round(e));hr.style.height=`${t}px`,hr.style.display=t>0?``:`none`,Hs&&(Hs.spacerHeight=Math.max(0,e))},ml=e=>{let t=parseFloat(getComputedStyle(B).paddingBottom)||0,n=0;for(let e of Array.from(B.children)){if(e===hr||e.offsetHeight===0)continue;let t=ll(e)+e.offsetHeight;t>n&&(n=t)}let r=B.scrollHeight-e;return n>0?Math.min(n+t,r):r},hl=()=>{if(!Hs||Hs.spacerHeight<=0)return;let e=ml(Hs.spacerHeight),t=Math.max(0,Math.round(B.scrollTop)+B.clientHeight-e+24);t<Hs.spacerHeight&&(pl(t),nl())},gl=()=>{Ws!==null&&(cancelAnimationFrame(Ws),Ws=null),Bc(),Hs=null,hr.style.height=`0px`,hr.style.display=`none`},_l=e=>typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),vl=e=>B.querySelector(`[data-message-id="${_l(e)}"]`),yl=e=>{Ws!==null&&cancelAnimationFrame(Ws),Ws=requestAnimationFrame(()=>{Ws=null;let t=_l(e),n=B.querySelector(`[data-message-id="${t}"]`);if(!n)return;let r=ll(n),i=Hs?.spacerHeight??0,a=ml(i),{targetScrollTop:o,spacerHeight:s}=Rt({anchorOffsetTop:r,topOffset:rr(),viewportHeight:B.clientHeight,contentHeight:a,slack:24});Hs={initialSpacerHeight:s,contentHeightAtAnchor:a,spacerHeight:s},pl(s),ol(B,()=>n.isConnected?Math.max(0,ll(n)-rr()):o,220)})},bl=()=>{if(tr()!==`anchor-top`||!Hs||!Qs)return;let e=vl(Qs);if(!e)return;Bc();let t=Hs.spacerHeight,n=ml(t),{targetScrollTop:r,spacerHeight:i}=Rt({anchorOffsetTop:ll(e),topOffset:rr(),viewportHeight:B.clientHeight,contentHeight:n,slack:24});Hs={initialSpacerHeight:i,contentHeightAtAnchor:n,spacerHeight:i},pl(i),Is=!0,B.scrollTop=r,js=B.scrollTop,Is=!1,nl()},Sl=()=>{if(nr()){if(!Os.isFollowing()||Lt(B,1))return;al(!ms)}else{if(Hs&&Hs.initialSpacerHeight>0){let e=B.scrollHeight-Hs.spacerHeight,t=Pt({initialSpacerHeight:Hs.initialSpacerHeight,contentHeightAtAnchor:Hs.contentHeightAtAnchor,currentContentHeight:e});t!==Hs.spacerHeight&&pl(t)}nl()}},Cl=e=>{let t=tr();t===`follow`?(il(),al(!0)):t===`anchor-top`&&(Xs=!1,Zs=!0,$s=!1,Qs=e,yl(e))},wl=()=>{tr()===`anchor-top`&&(Zs?Xs=!1:(Xs=!0,gl(),il(),al(!0)))},Tl=e=>{if(Ys===null)return!0;let t=vl(Ys),n=vl(e);if(!t||!n)return!0;let r=ll(n)-ll(t);return rr()+r>B.clientHeight-96},Ol=e=>{if(tr()!==`anchor-top`||!Zs||$s||dl())return;let t=Ys===null;for(let n of e)if(!t)n.id===Ys&&(t=!0);else if(Ft(n)){if(n.id===Qs||!Tl(n.id))return;Qs=n.id,yl(n.id);return}},kl=e=>{let t=/* @__PURE__ */ new Map;e.forEach(e=>{let n=ac.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!n&&e.role===`assistant`&&(O.emit(`assistant:message`,e),!Js&&(tr()!==`anchor-top`||or())&&el()&&(Rs+=1,qc(),nl(),yr(Rs===1?`1 new message below.`:`${Rs} new messages below.`))),e.role===`assistant`&&n?.streaming&&e.streaming===!1&&O.emit(`assistant:complete`,e),e.variant===`approval`&&e.approval&&(n?e.approval.status!==`pending`&&O.emit(`approval:resolved`,{approval:e.approval,decision:e.approval.status}):O.emit(`approval:requested`,{approval:e.approval,message:e}))}),ac.clear(),t.forEach((e,t)=>{ac.set(t,e)})},Al=(e,t)=>{let n=t===`user`?`user`:`assistant`,r=i.layout?.messages?.[n],a=r?.width??`content`,o=r?.maxWidth??(a===`full`?`var(--persona-message-${n}-max-width, 100%)`:void 0);e.classList.add(`persona-message-row`),e.classList.remove(`persona-message-row-user`,`persona-message-row-assistant`,`persona-message-row-system`,`persona-message-width-content`,`persona-message-width-full`),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${a}`),e.classList.toggle(`persona-justify-end`,t===`user`),e.setAttribute(`data-message-role`,t),e.setAttribute(`data-message-width`,a),o?e.style.setProperty(`--persona-message-row-max-width`,o):e.style.removeProperty(`--persona-message-row-max-width`)},jl=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),Al(n,t),n},Fl=(e,t,n)=>{let r=/* @__PURE__ */ new Set;for(let e of t){let t=e.variant===`tool`?`tool`:e.variant===`reasoning`?`reasoning`:null;if(!t||yn(i,t)!==`row`)continue;let n=t===`tool`?i.features?.toolCallDisplay:i.features?.reasoningDisplay;n?.expandable!==!1&&(r.add(e.id),c.observe(e,t,t===`tool`?o:s,n))}let u=document.createElement(`div`),d=(()=>{let e=f.find(e=>e.renderLoadingIndicator);if(e?.renderLoadingIndicator)return e.renderLoadingIndicator;if(i.loadingIndicator?.render)return i.loadingIndicator.render})(),p=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),m=/* @__PURE__ */ new Set,h=/* @__PURE__ */ new Map,g=/* @__PURE__ */ new Set,_=f.some(e=>e.renderAskUserQuestion),y=[],b=[],S=i.enableComponentStreaming!==!1,C=i.approval!==!1,w=[],T=i.messageActions,E=T?.showRegenerate===!0&&T.enabled!==!1&&ka.current?.isStreaming()!==!0?Er(t):null,D=T?.showEdit===!0&&T.enabled!==!1,ee=T?.showQuote===!0&&T.enabled!==!1,te=null,ne=i.features?.reasoningDisplay?.completedVisibility,ie=e=>ne===`removed`||ne===`removed-when-short`&&a(e,i.features?.reasoningDisplay?.shortThinkThreshold),ae=i.features?.toolCallDisplay?.completedVisibility===`removed`,oe=e=>e.variant===`reasoning`&&e.reasoning?.status===`complete`?ie(e.reasoning):ae&&e.variant===`tool`&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;if(t.forEach(t=>{if(oe(t))return;if(m.add(t.id),h.set(t.id,t.role),bs===t.id&&Ss){let e=jl(t.id,t.role);e.setAttribute(`data-persona-message-edit-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(e),te={messageId:t.id,element:Ss.element};return}let r=_&&Qe(t),a=C&&t.variant===`approval`&&!!t.approval,c=!r&&t.role===`assistant`&&!t.variant&&S&&mu(t);!a&&ys.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),ys.delete(t.id)),!c&&vs.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),vs.delete(t.id));let p=Qe(t)?`:${t.agentMetadata?.askUserQuestionAnswered?`a`:`u`}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:``,T={canRegenerate:E===t.id,canEdit:D&&Dr(t),canQuote:ee&&!t.variant&&(t.content?.trim().length??0)>0},ne=`${T.canRegenerate?`r`:``}${T.canEdit?`e`:``}${T.canQuote?`q`:``}`,ie=so(t,Es)+p+`:${ne}`,ae=r||a||c?null:lo(gs,t.id,ie);if(ae){u.appendChild(ae.cloneNode(!0)),Qe(t)&&t.toolCall?.id&&t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(g.add(t.toolCall.id),Ma(t));return}let O=null,ce=f.find(e=>!!(t.variant===`reasoning`&&e.renderReasoning||t.variant===`tool`&&e.renderToolCall||!t.variant&&e.renderMessage)),le=i.layout?.messages;if(Qe(t)&&t.agentMetadata?.askUserQuestionAnswered===!0){_s.delete(t.id),e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`);return}if(nt(t)&&et(i).enabled)return;if(Qe(t)&&i.features?.askUserQuestion?.enabled!==!1){let e=f.find(e=>typeof e.renderAskUserQuestion==`function`);if(e&&ka.current){let n=_s.get(t.id),r=n!==ie,a=null;if(r){let{payload:n,complete:r}=$e(t),o=t.id,s=()=>ka.current?.getMessages().find(e=>e.id===o);a=e.renderAskUserQuestion({message:t,payload:n,complete:r,resolve:e=>{let t=s();t&&ka.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(ka.current?.markAskUserQuestionResolved(e),ka.current?.resolveAskUserQuestion(e,`(dismissed)`))},config:i})}if(r&&a===null&&n==null){t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(g.add(t.toolCall.id),Ma(t));return}let o=jl(t.id,t.role);o.setAttribute(`data-ask-plugin-stub`,`true`),o.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(o),y.push({messageId:t.id,fingerprint:ie,bubble:a});return}t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(g.add(t.toolCall.id),Ma(t));return}if(a){let n=re();if(!n){u.appendChild(jl(t.id,t.role));return}let r=f.find(e=>typeof e.renderApproval==`function`)??x,a=ys.get(t.id)!==ie,o=null;if(a&&r?.renderApproval){let e=t.id,a=(t,n)=>{let r=ka.current?.getMessages().find(t=>t.id===e);r?.approval&&(v(r.approval)?ka.current?.resolveWebMcpApproval(r.id,t):ka.current?.resolveApproval(r.approval,t,n))};o=r.renderApproval({message:t,defaultRenderer:()=>n.createApprovalBubble(t,i,l),config:i,approve:e=>a(`approved`,e),deny:e=>a(`denied`,e)})}if(a&&o===null)e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),ys.delete(t.id),O=n.createApprovalBubble(t,i,l);else{let e=jl(t.id,t.role);e.setAttribute(`data-approval-plugin-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(e),w.push({messageId:t.id,fingerprint:ie,bubble:o});return}}else if(ce){if(t.variant===`reasoning`&&t.reasoning&&ce.renderReasoning){if(!ut)return;O=ce.renderReasoning({message:t,defaultRenderer:()=>fc(t,i,s),config:i})}else if(t.variant===`tool`&&t.toolCall&&ce.renderToolCall){if(!dt)return;O=ce.renderToolCall({message:t,defaultRenderer:()=>Cc(t,i,o),config:i})}else ce.renderMessage&&(O=ce.renderMessage({message:t,defaultRenderer:()=>{let e=xs(t,n,le,i.messageActions,mn,{loadingIndicatorRenderer:d,widgetConfig:i,actionEligibility:T});return t.role!==`user`&&se(e,t,i,Q),e},config:i}))}if(!O&&c){let r=hu(t);if(r){let a=vs.get(t.id),o=a!==ie,s=i.wrapComponentDirectiveInBubble!==!1&&Ge.getOptions(r.component)?.bubbleChrome!==!1,c=null;if(o){let a=fu(r,{config:i,message:t,transform:n});if(a&&r.component===`PersonaArtifactInline`){let n=a.hasAttribute(`data-artifact-inline`)?a:a.querySelector(`[data-artifact-inline]`),r=n?.getAttribute(`data-artifact-inline`)??``,i=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(r):r,o=r?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${i}"]`)??null:null;n&&o&&o!==n&&Hc()?.hasLiveInlineArtifactBlock(o)&&(n===a?a=o:n.replaceWith(o))}if(a){if(s){let e=document.createElement(`div`);if(e.className=[`persona-message-bubble`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-p-4`].join(` `),e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-mb-3 persona-text-sm persona-leading-relaxed`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}else{let e=document.createElement(`div`);if(e.className=`persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch`,e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),e.setAttribute(`data-persona-component-directive`,`true`),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}}}if(c||a!=null){let e=jl(t.id,t.role);e.setAttribute(`data-component-directive-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(e),b.push({messageId:t.id,fingerprint:ie,bubble:c});return}}}if(!O){if(t.variant===`reasoning`&&t.reasoning){if(!ut)return;O=fc(t,i,s)}else if(t.variant===`tool`&&t.toolCall){if(!dt)return;O=Cc(t,i,o)}else if(t.variant===`approval`&&t.approval){if(i.approval===!1)return;let e=re();if(!e)return;O=e.createApprovalBubble(t,i,l)}else{let e=i.layout?.messages;O=e?.renderUserMessage&&t.role===`user`?e.renderUserMessage({message:t,config:i,streaming:!!t.streaming}):e?.renderAssistantMessage&&t.role===`assistant`?e.renderAssistantMessage({message:t,config:i,streaming:!!t.streaming}):xs(t,n,e,i.messageActions,mn,{loadingIndicatorRenderer:d,widgetConfig:i,actionEligibility:T}),t.role!==`user`&&O&&se(O,t,i,Q)}}let ue=jl(t.id,t.role);ue.appendChild(O),uo(gs,t.id,ie,ue),u.appendChild(ue)}),R.composerOverlay&&R.composerOverlay.querySelectorAll(`[data-persona-ask-sheet-for]`).forEach(e=>{let t=e.getAttribute(`data-persona-ask-sheet-for`);t&&!g.has(t)&&Xe(R.composerOverlay,t)}),i.features?.toolCallDisplay?.grouped){let e=[],n=[],a=i.features.toolCallDisplay.groupedMode===`summary`;t.forEach(t=>{if(t.variant===`tool`&&t.toolCall&&dt){if(ae&&t.toolCall.status===`complete`&&!t.toolCall.interrupted)return;n.push(t)}else(t.variant!==`reasoning`||ut&&(t.reasoning?.status!==`complete`||!ie(t.reasoning)))&&((n.length>1||a&&n.length>0)&&e.push(n),n=[])}),(n.length>1||a&&n.length>0)&&e.push(n),e.forEach(e=>{let t=e.map(e=>Array.from(u.children).find(t=>t instanceof HTMLElement&&t.getAttribute(`data-wrapper-id`)===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let n=jl(`tool-group-${e[0].id}`,`assistant`);if(n.setAttribute(`data-persona-tool-group-row`,`true`),i.features?.toolCallDisplay?.groupedMode===`collapsible`){let a=`tool-group-${e[0].id}`,s=e.some(e=>e.toolCall?.status!==`complete`),l={...e[0],id:a,toolCall:{id:a,name:`${e.length} tools`,status:s?`running`:`complete`,chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>e.toolCall?.success===!1),interrupted:!s&&e.some(e=>e.toolCall?.interrupted)}};r.add(a),c.observe(l,`tool`,o,i.features.toolCallDisplay);let u=l.toolCall?.interrupted?`${e.length} tools · Interrupted`:`${s?`Using`:`Used`} ${e.length} tools`,d=i.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:u,config:i}),f=Sn(l,i,o.has(a),d??u);f.bubble.classList.add(`persona-tool-group`),f.body.dataset.personaToolGroupStack=`true`,t[0].before(n),n.appendChild(f.bubble),t.forEach((e,t)=>{e.style.setProperty(`--persona-message-row-max-width`,`100%`),e.style.setProperty(`--persona-activity-stagger`,`${t*40}ms`),e.classList.add(`persona-activity-group-child`),f.body.appendChild(e)});return}let s=document.createElement(`div`);s.className=`persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2`,s.setAttribute(`data-persona-tool-group`,`true`);let l=document.createElement(`div`);l.className=`persona-tool-group-summary persona-text-xs persona-text-persona-muted`,l.id=`tool-group-summary-${e[0].id}`;let d=`${e.length} ${e.length===1?`tool`:`tools`}`,f=e.some(e=>e.toolCall?.interrupted)?`${d} · Interrupted`:`Called ${d}`,m=i.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:f,config:i});p(l,m)||(l.textContent=f);let h=document.createElement(`div`);h.className=`persona-tool-group-stack persona-flex persona-flex-col`,h.id=`tool-group-stack-${e[0].id}`,h.setAttribute(`data-persona-tool-group-stack`,`true`),s.appendChild(l),a||s.appendChild(h),n.appendChild(s),t[0].before(n),t.forEach((e,n)=>{if(a){e.remove();return}e.style.setProperty(`--persona-message-row-max-width`,`100%`);let r=document.createElement(`div`);r.className=`persona-tool-group-item persona-relative`,r.setAttribute(`data-persona-tool-group-item`,`true`),n<t.length-1&&r.setAttribute(`data-persona-tool-group-connector`,`true`),r.appendChild(e),h.appendChild(r)})})}c.prune(r),fo(gs,m);let O=e=>e.variant===`tool`&&!dt||e.variant===`reasoning`&&!ut||oe(e),ce=t.some(e=>e.role===`assistant`&&e.streaming&&!O(e)),le=t.length-1;for(;le>=0&&O(t[le]);)le--;let ue=le>=0?t[le]:void 0,de=le<t.length-1,fe=ue?.role===`assistant`&&!ue.streaming&&ue.variant!==`approval`&&!de;if(ms&&t.some(e=>e.role===`user`)&&!ce&&!fe){let e={config:i,streaming:!0,location:`standalone`,defaultRenderer:ds},t=f.find(e=>e.renderLoadingIndicator),n=null;if(t?.renderLoadingIndicator&&(n=t.renderLoadingIndicator(e)),n===null&&i.loadingIndicator?.render&&(n=i.loadingIndicator.render(e)),n===null&&(n=ds()),n){let e=document.createElement(`div`),t=i.loadingIndicator?.showBubble!==!1,r=i.layout?.messages?.layout??`bubble`;e.className=t?hs(`assistant`,r).join(` `):[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-text`].join(` `),e.setAttribute(`data-typing-indicator`,`true`),t&&(e.style.color=`var(--persona-message-assistant-text, var(--persona-text))`,r!==`flat`&&(e.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,e.style.borderColor=`var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))`)),e.appendChild(n);let a=jl(`typing-indicator`,`assistant`);a.appendChild(e),u.appendChild(a)}}if(!ms&&t.length>0){let e=t[t.length-1],n={config:i,lastMessage:e,messageCount:t.length},r=f.find(e=>e.renderIdleIndicator),a=null;if(r?.renderIdleIndicator&&(a=r.renderIdleIndicator(n)),a===null&&i.loadingIndicator?.renderIdle&&(a=i.loadingIndicator.renderIdle(n)),a){let e=document.createElement(`div`);e.className=i.loadingIndicator?.showBubble===!1?[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-primary`].join(` `):[`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(` `),e.setAttribute(`data-idle-indicator`,`true`),e.appendChild(a);let t=jl(`idle-indicator`,`assistant`);t.appendChild(e),u.appendChild(t)}}if(An(u),ro(e,u),Mn(e),te){let{messageId:t,element:n}=te,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(Al(r,h.get(t)??`user`),r.replaceChildren(n))}if(y.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of y){let i=e.querySelector(`#wrapper-${t}`);i&&(Al(i,h.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),_s.set(t,n)))}if(_s.size>0)for(let e of _s.keys())m.has(e)||_s.delete(e);if(b.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of b){let i=e.querySelector(`#wrapper-${t}`);i&&(Al(i,h.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),vs.set(t,n)))}if(vs.size>0)for(let e of vs.keys())m.has(e)||vs.delete(e);if(w.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of w){let i=e.querySelector(`#wrapper-${t}`);i&&(Al(i,h.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),ys.set(t,n)))}if(ys.size>0)for(let e of ys.keys())m.has(e)||ys.delete(e)},Il=!1,Ll=()=>{Il||(Il=!0,In().catch(()=>{}),Ue().catch(()=>{Il=!1}))},Bl=(e,t,n)=>{t.length>0&&Ll(),Fl(e,t,n),ma()},Vl=null,Ul=()=>{if(Vl)return;let e=e=>{let t=e.composedPath();t.includes(I)||vn&&t.includes(vn)||ou(!1,`user`)};Vl=e,(t.ownerDocument??document).addEventListener(`pointerdown`,e,!0)},Gl=()=>{Vl&&=((t.ownerDocument??document).removeEventListener(`pointerdown`,Vl,!0),null)};Z.push(()=>Gl());let ql=null,Jl=()=>{if(ql)return;let e=e=>{e.key===`Escape`&&(e.isComposing||ou(!1,`user`))};ql=e,(t.ownerDocument??document).addEventListener(`keydown`,e,!0)},Yl=()=>{ql&&=((t.ownerDocument??document).removeEventListener(`keydown`,ql,!0),null)};Z.push(()=>Yl());let Ql=!1,$l=/* @__PURE__ */ new Set,eu=()=>i.launcher?.composerBar?.peek?.streamAnimation||i.features?.streamAnimation,nu=()=>{if(!P())return;let e=R.peekBanner,n=R.peekTextNode;if(!e||!n)return;if(F){e.classList.remove(`persona-pill-peek--visible`);return}let r=Q?.getMessages()??[],i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.role===`assistant`&&t.content){i=t;break}}if(!i){e.classList.remove(`persona-pill-peek--visible`);return}let a=i.content,o=!!i.streaming,s=eu(),c=Bt(s),l=c.type===`none`?null:Uo(c.type,s?.plugins),u=l?.isAnimating?.(i)===!0,d=l!==null&&(o||u);d&&l&&!$l.has(l.name)&&(Wt(l,t),$l.add(l.name));let f=d&&l?.containerClass?l.containerClass:null,p=n.dataset.personaPeekStreamClass??null;p&&p!==f&&(n.classList.remove(p),delete n.dataset.personaPeekStreamClass),f&&p!==f&&(n.classList.add(f),n.dataset.personaPeekStreamClass=f),d?(n.style.setProperty(`--persona-stream-step`,`${c.speed}ms`),n.style.setProperty(`--persona-stream-duration`,`${c.duration}ms`)):(n.style.removeProperty(`--persona-stream-step`),n.style.removeProperty(`--persona-stream-duration`));let m=d?Ut(a,c.buffer,l,i,o):a;if(d&&c.placeholder===`skeleton`&&o&&(!m||!m.trim())){let e=document.createElement(`div`),t=Gt();t.classList.add(`persona-pill-peek__skeleton`),e.appendChild(t),ro(n,e)}else{let t=Math.max(0,m.length-100),r=m.length>100?m.slice(-100):m,a=Le(r);if(!d||!l){let e=m.length>100?`…${r}`:r;n.textContent!==e&&(n.textContent=e)}else{let o=a;(l.wrap===`char`||l.wrap===`word`)&&(o=Jt(a,l.wrap,`peek-${i.id}`,{skipTags:l.skipTags,startIndex:t}));let s=document.createElement(`div`);if(s.innerHTML=o,l.useCaret&&r.length>0){let e=Vt(),t=s.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];n?.parentNode?n.parentNode.insertBefore(e,n.nextSibling):s.appendChild(e)}ro(n,s),l.onAfterRender?.({container:n,bubble:e,messageId:i.id,message:i,speed:c.speed,duration:c.duration})}}let h=ms||Ql;e.classList.toggle(`persona-pill-peek--visible`,h)};if(P()){let e=R.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),ou(!0,`user`)};e.addEventListener(`pointerdown`,t),Z.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{Ql||(Ql=!0,nu())},n=()=>{Ql&&(Ql=!1,nu())};L.addEventListener(`pointerenter`,t),L.addEventListener(`pointerleave`,n),Z.push(()=>{L.removeEventListener(`pointerenter`,t),L.removeEventListener(`pointerleave`,n)}),vn&&(vn.addEventListener(`pointerenter`,t),vn.addEventListener(`pointerleave`,n),Z.push(()=>{vn.removeEventListener(`pointerenter`,t),vn.removeEventListener(`pointerleave`,n)}))}let ru=e=>{let t=i.launcher?.composerBar??{},n=t.expandedSize??`anchored`,r=t.bottomOffset??`16px`,a=t.collapsedMaxWidth,o=t.expandedMaxWidth??`880px`,s=t.expandedTopOffset??`5vh`,c=t.modalMaxWidth??`880px`,l=t.modalMaxHeight??`min(90vh, 800px)`,u=`calc(100vw - 32px)`,d=I.style;if(d.left=``,d.right=``,d.top=``,d.bottom=``,d.transform=``,d.width=``,d.maxWidth=``,d.height=``,d.maxHeight=``,vn){let e=vn.style;e.bottom=r,e.width=a??``}e&&n!==`fullscreen`&&(n===`modal`?(d.top=`50%`,d.left=`50%`,d.transform=`translate(-50%, -50%)`,d.bottom=`auto`,d.right=`auto`,d.width=c,d.maxWidth=u,d.maxHeight=l,d.height=l):(d.left=`50%`,d.transform=`translateX(-50%)`,d.bottom=`calc(${r} + var(--persona-pill-area-height, 80px))`,d.top=s,d.width=o,d.maxWidth=u))},au=()=>{if(F&&Ll(),!it())return;if(P()){let e=(i.launcher?.composerBar??{}).expandedSize??`anchored`,t=F?`expanded`:`collapsed`;I.dataset.state=t,I.dataset.expandedSize=e,vn&&(vn.dataset.state=t,vn.dataset.expandedSize=e),I.style.removeProperty(`display`),I.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),L.classList.remove(`persona-scale-95`,`persona-opacity-0`,`persona-scale-100`,`persona-opacity-100`),ru(F),z.style.display=F?`flex`:`none`,va(),F?(Ul(),Jl()):(Gl(),Yl()),nu();return}let e=xo(i),n=t.ownerDocument.defaultView??window,r=i.launcher?.mobileBreakpoint??640,a=i.launcher?.mobileFullscreen??!0,o=n.innerWidth<=r,s=a&&o&&Be,c=Co(i).reveal;F?(I.style.removeProperty(`display`),I.style.display=e?`flex`:``,I.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),L.classList.remove(`persona-scale-95`,`persona-opacity-0`),L.classList.add(`persona-scale-100`,`persona-opacity-100`),wp?(wp.setPanelOpen(!0),wp.element.style.display=`none`):Tp&&(Tp.style.display=`none`)):(e?e&&(c===`overlay`||c===`push`)&&!s?(I.style.removeProperty(`display`),I.style.display=`flex`,I.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),L.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(I.style.setProperty(`display`,`none`,`important`),I.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),L.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(I.style.display=``,I.classList.add(`persona-pointer-events-none`,`persona-opacity-0`),L.classList.remove(`persona-scale-100`,`persona-opacity-100`),L.classList.add(`persona-scale-95`,`persona-opacity-0`)),wp?(wp.setPanelOpen(!1),wp.element.style.display=e?`none`:``):Tp&&(Tp.style.display=e?`none`:``))},ou=(e,n=`user`)=>{if(!it()||F===e)return;let r=F;F=e,au();let a=(()=>{let e=i.launcher?.sidebarMode??!1,n=t.ownerDocument.defaultView??window,r=i.launcher?.mobileFullscreen??!0,a=i.launcher?.mobileBreakpoint??640,o=n.innerWidth<=a,s=xo(i)&&r&&o,c=P()&&(i.launcher?.composerBar?.expandedSize??`fullscreen`)===`fullscreen`;return e||r&&o&&Be||s||c})();if(F&&a){if(!Fo){let e=t.getRootNode(),n=e instanceof ShadowRoot?e.host:t.closest(`.persona-host`);n&&(Fo=go(n,i.launcher?.zIndex??1e5))}Io||=yo(t.ownerDocument)}else F||(Fo?.(),Fo=null,Io?.(),Io=null);F&&(kp(),fl()||(tr()===`follow`?al(!0):cl()));let o={open:F,source:n,timestamp:Date.now()};F&&!r?O.emit(`widget:opened`,o):!F&&r&&O.emit(`widget:closed`,o),O.emit(`widget:state`,{open:F,launcherEnabled:Be,voiceActive:$.active,streaming:Q.isStreaming()})},su={inputDisabled:!1,sendDisabled:!1},cu=()=>su.inputDisabled,pu=()=>Cn(i.voiceRecognition?.provider)&&!!Q&&(Q.isBargeInActive()||[`listening`,`processing`,`speaking`].includes(Q.getVoiceStatus())),gu=()=>su.inputDisabled||su.sendDisabled,Su=()=>(su.inputDisabled?su.inputReason:void 0)??(su.sendDisabled?su.sendReason:void 0);function ju(){if(!U)return;if(J.getState().phase===`streaming`){U.disabled=!1;return}let e=Mr?!Mr.isReady():!1;U.disabled=gu()||e}function Nu(){if(!Wn)return;let e=J.getState(),t=i.sendButton?.visibility===`when-text`&&e.phase!==`streaming`&&e.text.trim().length===0&&e.attachments.length===0;Wn.toggleAttribute(`data-persona-send-hidden`,t)}function Pu(){let e=Su();if(P()){let t=Dn??K;e?t.setAttribute(`title`,e):t.removeAttribute(`title`),K.toggleAttribute(bu,!!e)}else if(e)W.setAttribute(`role`,`status`),W.setAttribute(`aria-live`,`polite`),W.setAttribute(bu,``),W.removeAttribute(xu),W.textContent=e,w(W,i.statusIndicator??{},`idle`);else if(W.hasAttribute(bu)&&(W.removeAttribute(`role`),W.removeAttribute(`aria-live`),W.removeAttribute(bu),g)){let e=Q.getStatus();gn(W,hn(e),i.statusIndicator??{},e)}}function Fu(){let e=de(i.composer?.inputDisabled),t=de(i.composer?.sendDisabled);su={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},J.setInputDisabled(e.disabled),J.setSendDisabled(t.disabled);let n=J.getState().phase===`streaming`,r=e.disabled,a=n||r;H&&(H instanceof HTMLTextAreaElement?H.disabled=r:H.setAttribute(`contenteditable`,r?`false`:`true`),H.setAttribute(`aria-disabled`,r?`true`:`false`)),qn&&(qn.disabled=r),Yn&&(Yn.disabled=r);for(let e of Nr?.affordanceButtons??[])e.querySelectorAll(`button`).forEach(e=>{e.disabled=r});q&&(q.disabled=r||n&&!pu()),Zo.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement||e.setAttribute(`aria-disabled`,a?`true`:`false`)}),e.buttons.forEach(e=>{e.disabled=a})}),Qu.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute(`aria-disabled`,a?`true`:`false`),e.querySelectorAll(`button`).forEach(e=>{e.disabled=a})}),K.dataset.personaComposerStreaming=n?`true`:`false`,K.dataset.personaComposerInputDisabled=r?`true`:`false`,K.dataset.personaComposerSendDisabled=gu()?`true`:`false`,K.querySelectorAll(`[data-persona-composer-disable-when-streaming]`).forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=n)}),ju(),Pu()}let Iu=e=>{J.setStreaming(e),Gn(e?`stop`:`send`),Fu()},Lu=()=>{$.active||H&&H.focus()};O.on(`widget:opened`,()=>{i.autoFocusInput&&setTimeout(()=>Lu(),200)});let Ru=null,zu=!1,Bu=!On.hidden,Vu=null,Hu=!_e,Uu=null;Z.push(()=>{Uu?.cancel(),Uu=null});let Wu=e=>{let n=Bs(e);if(n===Sr)return;Sr=n,t.setAttribute(`data-persona-conversation-state`,n);let r=wr();Ar(),Hu&&(Uu?.cancel(),Uu=Fs(K,n===`active`?r:wr(),n===`active`?`drop`:`rise`,xr().layout===`centered`?320:260)),bl()},Gu=null,Ku,qu=null,Ju=null,Yu=!1,Xu=e=>{let t=xr(),n=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??`bottom`}|${t.align??``}|${t.iconPlacement}|${t.kicker??``}|${t.title}|${t.subtitle}`;(n!==Gu||t.icon!==Ku)&&(Gu=n,Ku=t.icon,Ts({host:On,iconHolder:kn,kicker:Nn,title:Pn,subtitle:Fn,starterSuggestions:wn},t));let r=t.message===void 0?null:`${i.layout?.messages?.layout??`bubble`}|${t.message}`;r!==qu&&(qu=r,Ms(jn,t.message,i));let a=e??(Q?Q.getMessages():i.initialMessages);Wu(a);let o=zu,s=!o&&Vs(t,a),c=s!==Bu;if(Bu=s,Ju){Vu?.cancel(),Vu=null,o!==Yu&&(Yu=o,o?As(B,On,null):ks(B,On,Ju)),ws(B,On,!o);return}if(c&&!s&&!o&&t.dismiss===`on-first-message`&&Hu){Vu=Ps(On,e=>{Vu===e&&(Vu=null),!Bu&&!Ju&&(ws(B,On,!1),bl()),e?.cancel()});return}if(Vu){if(!s&&!o)return;Vu.cancel(),Vu=null}let l=!On.hidden;ws(B,On,s),!s&&l&&bl()},Zu=[],Qu=[],$u=!1,ed=null,td,nd=()=>{Qu.length=0;let e=Zu.splice(0,Zu.length);for(let t of e)try{t()}catch(e){console.warn(`[persona] renderWelcome cleanup threw`,e)}};Z.push(nd);let rd=(e,t)=>{let n=To(e,t);if(!n)return i.debug===!0&&console.warn(`[persona] renderStarter received a suggestion with no label`),M(`span`);let r=i.suggestions?.starters,a=ko({item:{...n,behavior:n.behavior??r?.behavior??`send`},index:t,surface:`starter`,source:`config`,variant:r?.variant??`card`,streaming:g?Q.isStreaming():!1,config:i,plugins:f,chipsConfig:i.suggestionChipsConfig,session:Q,getTextarea:()=>H,eventTarget:On,submitPrompt:Tf});return Qu.push(a),a},id=()=>{if($u)return;$u=!0;let e=xr();ed=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`,td=e.icon;try{nd(),As(B,On,Ju),Ju=null,Yu=!1;let t=Q?Q.getMessages():i.initialMessages,n=Vs(e,t),r=0,a=null;for(let t of f)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:n,defaultRenderer:()=>On,sendMessage:e=>{if(!Q||Q.isStreaming())return;let t=e.trim();t&&Q.sendMessage(t)},requestRender:()=>id(),renderStarter:e=>rd(e,r++),storage:_(t.id),onCleanup:e=>{Zu.push(e)}}),a))break;a&&a!==On&&(Ju=a,ks(B,On,a))}finally{$u=!1}Xu()},ad=()=>{let e=xr();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`!==ed||e.icon!==td)&&id()},od=()=>{Xu(),hi||(H.placeholder=Gi(J.getState().activeModeIds,i.composer?.modes)??i.copy?.inputPlaceholder??`How can I help...`,!(i.sendButton?.useIcon??!1)&&!Q?.isStreaming()&&(U.textContent=i.copy?.sendButtonLabel??`Send`)),H.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,H.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`},sd=!!i.setStoredConversationId,cd=e=>Ne(t=>{let n={...t};return delete n[e],n}),ld=e=>{let t=pe[e];return typeof t==`string`?t:null},ud=()=>{let e=pe.durableResume;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.executionId==`string`&&t.executionId.length>0&&typeof t.after==`string`&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};i.clientToken&&(i={...i,getStoredSessionId:()=>ld(`sessionId`),setStoredSessionId:e=>{Ne(t=>({...t,sessionId:e}))},clearStoredSessionId:i.clearStoredSessionId??(()=>cd(`sessionId`)),getStoredConversationId:i.getStoredConversationId??(()=>ld(`conversationId`)),setStoredConversationId:i.setStoredConversationId??(e=>{Ne(t=>({...t,conversationId:e}))}),clearStoredConversationId:i.clearStoredConversationId??(()=>cd(`conversationId`))});let dd=()=>i.clientToken??null,fd=e=>tu(e,_t(),i.persistState===!1),pd=dd(),md=pd?fd(pd):null,hd=()=>{let e=pe.pendingDisplayProjections;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.conversationId!=`string`||!Array.isArray(t.messageIds)?null:{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>typeof e==`string`)}},gd={...md?{visitorStore:md}:{},historyBootstrapReady:i.features?.history?.enabled===!0&&!uu()?Promise.all([ye,Se]).then(()=>{}):ye,getStoredMessageCursor:()=>ld(`historyMessageCursor`),setStoredMessageCursor:e=>{e===null?cd(`historyMessageCursor`):Ne(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:hd,setPendingDisplayProjections:e=>{e?Ne(t=>({...t,pendingDisplayProjections:e})):cd(`pendingDisplayProjections`)},getStoredResumableHandle:ud,setStoredResumableHandle:e=>{e?Ne(t=>({...t,durableResume:e})):cd(`durableResume`)},shouldResumeDurableConversation:()=>k&&ud()!==null,...sd?{}:{getStoredConversationRevision:()=>ld(`conversationRevision`),setStoredConversationRevision:e=>{e===null?cd(`conversationRevision`):Ne(t=>({...t,conversationRevision:e}))}}};if(k){let e=i.onExecutionState,n=t.ownerDocument.defaultView,r=!1,a=()=>r=!0,o=()=>r=!1;n?.addEventListener(`pagehide`,a),n?.addEventListener(`pageshow`,o),Z.push(()=>{n?.removeEventListener(`pagehide`,a),n?.removeEventListener(`pageshow`,o)}),i={...i,reconnectStream:i.reconnectStream??(e=>Q.getClient().reconnectClientTokenStream(e)),onExecutionState:t=>{(t||!r)&&gd.setStoredResumableHandle?.(t?{executionId:t.executionId,after:t.lastEventId}:null),e?.(t)}}}let _d=()=>{let e=dd();if(e&&md?.matches(e,_t(),i.persistState===!1)||!e&&!md)return;md?.destroy(),md=e?fd(e):null;let t={...gd};md?t.visitorStore=md:delete t.visitorStore,gd=t,Q.setHistoryInternals(gd)},vd=null,yd=()=>{vd??=setInterval(()=>{let e=V.querySelectorAll(`[data-tool-elapsed]`);if(e.length===0){clearInterval(vd),vd=null;return}let t=Date.now();e.forEach(e=>{let n=Number(e.getAttribute(`data-tool-elapsed`));n&&(e.textContent=e.closest(`.persona-activity-row`)?bn(t-n):h(t-n))})},100)},bd=(e,t)=>{if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>bd(e,t[n]));let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.prototype.hasOwnProperty.call(r,e)&&bd(n[e],r[e]))},xd=e=>{let{content:t,rawContent:n,llmContent:r,...i}=e;return i},Sd=e=>e.role===`assistant`&&e.streaming===!0&&!e.variant&&!e.toolCall&&!e.tools&&!e.approval&&!e.reasoning&&!e.contentParts&&!e.stopReason&&!mu(e),Cd=(e,t,n)=>{if(e.length!==t.length)return!1;let r=e[n.index],i=t[n.index];return!r||!i||r.id!==n.id||i.id!==n.id?!1:(!Object.is(r.content,i.content)||!Object.is(r.rawContent,i.rawContent)||!Object.is(r.llmContent,i.llmContent))&&Sd(r)&&Sd(i)&&bd(xd(r),xd(i))},wd=null,Td=null,Ed=null,Dd=null,Od=null,kd=e=>{if(!k)return Dc(e);Od=e,queueMicrotask(()=>{Od===e&&(Od=null,Dc(e))})},Ad=e=>{wd=e;let t,n;Td=null;for(let r=e.length-1;r>=0;--r){let i=e[r];if(!t&&i.role===`user`&&(t=i),!n&&i.role===`assistant`&&(n=i),!Td&&Sd(i)&&(Td={index:r,id:i.id}),t&&n&&Td)break}Bl(V,e,lt),Hc()?.updateInlineArtifactBlocks(V,xa.artifacts,{suppressTransition:ms}),yd(),Xu(e),us(e),al(!ms),kl(e),e.length===0&&(gl(),Xs=!0,Zs=!1,Qs=null,$s=!1),!qs||Js?(qs=!0,Ys=t?.id??null,tc=n?.id??null):t&&t.id!==Ys?(Ys=t.id,Cl(t.id)):n&&n.id!==tc&&wl(),n&&(tc=n.id),Ol(e);let r=$.lastUserMessageId;t&&t.id!==r&&($.lastUserMessageId=t.id,O.emit(`user:message`,t)),$.lastUserMessageWasVoice=!!t?.viaVoice,kd(e),nu()},jd=()=>{Dd!==null&&(cancelAnimationFrame(Dd),Dd=null);let e=Ed;Ed=null,e&&Ad(e)},Md=()=>{Dd!==null&&cancelAnimationFrame(Dd),Dd=null,Ed=null},Nd=e=>{let t=Ed??wd;ms&&t&&Td&&Cd(t,e,Td)?(Ed=e,Dd===null&&(Dd=requestAnimationFrame(()=>{Dd=null;let e=Ed;Ed=null,e&&Ad(e)}))):e.length===0?(Md(),Ad(e)):(jd(),Ad(e))};Q=new Jr(i,{onMessagesChanged(e){Nd(e)},onStatusChanged(e){let t=i.statusIndicator??{};gn(W,(e=>e===`idle`?t.idleText??xt.idle:e===`connecting`?t.connectingText??xt.connecting:e===`connected`?t.connectedText??xt.connected:e===`error`?t.errorText??xt.error:e===`paused`?t.pausedText??xt.paused:e===`resuming`?t.resumingText??xt.resuming:xt[e])(e),t,e),fn()},onStreamingChanged(e){e||(Q?.getMessages().length===0?Md():jd()),ms=e,Iu(e),fn(),Q&&Bl(V,Q.getMessages(),lt),e||(al(!0),hl(),cs=!0,Q&&ls(Q.getMessages(),et(i))),nl(),yr(e?`Responding…`:`Response complete.`),nu()},onVoiceStatusChanged(e){if(O.emit(`voice:status`,{status:e,timestamp:Date.now()}),e!==`disconnected`&&!Cn(i.voiceRecognition?.provider))return;let t=Q.getVoiceNotice();switch(t&&mf(t,1e4),e){case`listening`:if(!cc){let e=Q.getVoiceDisclosure();e&&(cc=!0,P()?(lc=H.placeholder,H.placeholder=e,yr(e)):mf(e,1e4))}lp(),op();break;case`processing`:lp(),sp();break;case`speaking`:lp(),cp();break;default:e===`idle`&&Q.isBargeInActive()?(lp(),op(),q?.setAttribute(`aria-label`,`End voice session`)):($.active=!1,cc=!1,lc!==null&&(H.placeholder=lc,lc=null),lp(),gc(`system`),hc||vc())}},onArtifactsState(e){xa=e,e.artifacts.length===0&&(Ea=!1),Hc()?.updateInlineArtifactBlocks(V,e.artifacts,{suppressTransition:ms}),vo(),Dc()},onHistoryStateChanged(e){un(e)},onHistoryNotice(e){dn(e)},onReconnect(e){let{executionId:t,lastEventId:n}=e.handle;e.phase===`paused`?O.emit(`stream:paused`,{executionId:t,after:n}):e.phase===`resuming`?O.emit(`stream:resuming`,{executionId:t,after:n,attempt:e.attempt??1}):O.emit(`stream:resumed`,{executionId:t,after:n})}},gd),ka.current=Q,Z.push(()=>Q.cancel()),Z.push(()=>{Q.destroy(),md?.destroy(),md=null});let Pd=null;if(Q.onReadAloudChange((e,t)=>{ua=e,da=t,ma();let n=e??Pd;e&&(Pd=e);let r=n?Q.getMessages().find(e=>e.id===n)??null:null;O.emit(`message:read-aloud`,{messageId:n,message:r,state:t,timestamp:Date.now()}),t===`idle`&&(Pd=null)}),g=!0,qs=!0,i.voiceRecognition?.enabled===!0&&Cn(i.voiceRecognition.provider))try{Q.setupVoice()}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Runtype voice setup failed:`,e)}let Fd=null,Id=null,Ld=!1,Rd=Q.getHistoryState(),zd=()=>i.features?.history?.enabled===!0,Bd=e=>{e&&(gr.textContent=``,gr.textContent=e)},Vd=()=>{m.forEach(e=>e()),m=[];let e=Fd,n=e?.railCollapseShortcut();e&&n&&m.push(p.register({id:`history-rail-collapse`,combo:n.combo,scope:i.features?.history?.rail?.collapseShortcutScope===`page`?`page`:`widget`,when:()=>on&&sn===`rail`&&e.railCollapsible()||e.railTriggerApplies(),run:()=>e.railOverlayMode()?e.toggleRailPinned():e.toggleRailCollapsed()}));for(let e of i.layout?.header?.trailingActions??[])e.shortcut&&m.push(p.register({id:`header-action-${e.id}`,combo:e.shortcut,run:()=>{let n=t.querySelector(`[data-persona-header-action="${e.id}"]`);n?n.click():i.layout?.header?.onAction?.(e.id)}}));for(let e of f)for(let t of e.shortcuts??[])m.push(p.register({...t,id:`${e.id}:${t.id}`}))};Vd();let Hd=null,Ud=!1,Wd=()=>{if(!Rn)return;let e=i.layout?.header?.titleSource===`conversation`,t=e&&Hd?.trim()||null;Rn.textContent=t??i.launcher?.title??`Chat Assistant`;let n=Rn.closest(`.persona-combo-btn`);if(!n)return;let r=!e||Q.getActiveConversationId()!==null;n.setAttribute(`data-persona-menu-locked`,r?`false`:`true`),n.setAttribute(`aria-haspopup`,r?`true`:`false`),r||n.setAttribute(`aria-expanded`,`false`),n.style.cursor=r?`pointer`:`default`;let a=n.querySelector(`svg`);a&&(a.style.display=r?``:`none`)},Gd=e=>{e!==Hd&&(Hd=e,Wd())},Kd=e=>{Ud=e?.starred===!0,Gd(e&&e.title.trim()||null),Wd()};Wd(),z.addEventListener(`persona:title-menu-builtin`,e=>{let t=e.detail?.actionId,n=Q.getActiveConversationId();n&&(t===`delete`?Xd(e=>e.requestDeleteConversation(n)):t===`star`&&Q.canUpdateConversations()&&Xd(e=>e.updateHistoryConversation(n,{starred:!Ud})).catch(()=>{}))}),un=e=>{Rd=e,Fd?.historySurface?.view.setNewConversationRequired(e.recovery===`new_conversation_required`),Iu(e.sendBlocked||ms),Fd?.syncEarlierMessagesPill()},dn=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(gs.clear(),gl(),il()),Bd(e.message),Fd?.historySurface?.view.refresh()};let qd={get actionManager(){return ze},get activeConversationTitle(){return Hd},announceHistory:Bd,get applyRailChrome(){return ln},set applyRailChrome(e){ln=e},get artifactSplitRoot(){return Ra},get body(){return B},get config(){return i},get container(){return z},get conversationOpenPendingEl(){return Ru},set conversationOpenPendingEl(e){Ru=e},get conversationOpenTakeover(){return zu},set conversationOpenTakeover(e){zu=e},currentKeyPrefix:_t,destroyCallbacks:Z,eventBus:O,get footer(){return K},get header(){return Bn},get historyChromeSync(){return fn},set historyChromeSync(e){fn=e},historyFeatureEnabled:zd,get historyInternals(){return gd},set historyInternals(e){gd=e},get historyPresentation(){return sn},set historyPresentation(e){sn=e},get historySessionState(){return Rd},get historyVisible(){return on},set historyVisible(e){on=e},get isStreaming(){return ms},jumpToBottomInstant:cl,get lastAppliedMessages(){return wd},set lastAppliedMessages(e){wd=e},get launcherEnabled(){return Be},get launcherSurfaceInstance(){return wp},maybeFocusInput:Lu,messageCache:gs,get messagesWrapper(){return V},mount:t,get open(){return F},panel:L,panelElements:R,get persistentMetadata(){return pe},set persistentMetadata(e){pe=e},plugins:f,get reapplyHistoryHostChrome(){return cn},set reapplyHistoryHostChrome(e){cn=e},repinAnchoredMessage:bl,resetAnchorState:gl,restoreScrollPosition:fl,resumeAutoScroll:il,runStorageMutation:Ec,get session(){return Q},setActiveConversationSummary:Kd,storageAdapter:fe,get suppressScrollSend(){return Js},set suppressScrollSend(e){Js=e},syncScrollToBottomButton:nl,updateWelcome:Xu,getHistoryProviderFactory:du,historyErrors:{HistoryClientError:Qn,HistoryProviderError:Ct},isDockedMountMode:xo,renderLucideIcon:N,loadHistoryView:iu,createHeaderIconButton:Po,attachTooltip:S},Jd=e=>(!Fd&&!Ld&&(Fd=e.createHistoryShell(qd),Fd.railCollapseShortcut()&&Vd()),Fd),Yd=()=>{if(Fd)return Promise.resolve(Fd);let e=uu();return e?Promise.resolve(Jd(e)):(Id??=lu().then(Jd,e=>{throw Id=null,e}),Id)},Xd=e=>{let t=uu(),n=Fd??(t?Jd(t):null);return n?e(n):Yd().then(t=>{if(!t)throw Error(`[AgentWidget] The widget was destroyed`);return e(t)})},Zd=()=>{Fd?.syncHistoryPresentation()};Z.push(()=>{Ld=!0}),zd()&&Yd().catch(()=>{}).finally(A),i.clientToken&&(i.features?.history?.enabled===!0||i.sessionInit===`mount`)&&Q.initClientSession().then(()=>{let e=Fd;if(e?.historyAvailable())return Q.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Fd?.syncEarlierMessagesPill()}).catch(e=>{i.debug&&console.warn(`[AgentWidget] Pre-init client session failed:`,e)});let Qd=()=>Q.warmClientSession(),$d=e=>{let t=i.sessionInit??`input`,n=Y?.input??H,r=e.target;n&&(e.type===`input`?(t===`input`||t===`focus`)&&r===n&&e.inputType&&n.value.trim():t===`focus`&&(e.type===`keyup`?r===n&&e.key===`Tab`:(Y?.form??Dn)?.contains(r)))&&Qd()},ef=[`input`,`pointerdown`,`keyup`];ef.forEach(e=>t.addEventListener(e,$d));let tf,nf,rf=()=>{let e=nf;nf=void 0;try{typeof e==`function`&&e()}catch{}},af=()=>{let e=i.clientToken&&typeof i.sessionInit==`function`?i.sessionInit:void 0;if(e!==tf){rf(),tf=e;try{nf=e?.({warm:Qd,mount:t})}catch{}}};af(),Z.push(()=>{ef.forEach(e=>t.removeEventListener(e,$d)),rf()}),(ft||i.onSSEEvent)&&Q.setSSEEventCallback((e,t)=>{i.onSSEEvent?.(e,t),rn(e,t)});let of=()=>{let e=i.resume??(k?gd.getStoredResumableHandle?.():null);e&&typeof i.reconnectStream==`function`&&Q.resumeFromHandle(e)};_e?_e.then(e=>{if(e){if(e.metadata&&(pe=Du(e.metadata),ze.syncFromMetadata()),e.messages?.length){Js=!0;try{Q.hydrateMessages(e.messages)}finally{Js=!1}Ll()}e.artifacts?.length&&Q.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),Ic(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Hu=!0,ve(),of()}):(Ic(Te),of());let sf=()=>{P()&&(F||(i.launcher?.composerBar?.expandOnSubmit??!0)&&ou(!0,`auto`))},cf=(e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[n,r]=await Promise.allSettled([e.finalize(),t.finalize()]),i=[];return n.status===`fulfilled`?i.push(n.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,n.reason),r.status===`fulfilled`?i.push(r.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,r.reason),Mu(i)}}:e:t,lf=()=>{let e=H.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>e.kind===`mention`)?e.contentSegments:void 0},uf=!1,df=null,ff=()=>{H.value=``,H.style.height=`auto`,Ir(),jf()},pf=null;function mf(e,t=4e3){yr(e),!P()&&W&&(W.hasAttribute(bu)||(W.setAttribute(xu,``),W.setAttribute(`role`,`status`),W.setAttribute(`aria-live`,`polite`),W.textContent=e,w(W,i.statusIndicator??{},`idle`),pf&&clearTimeout(pf),pf=setTimeout(()=>{if(pf=null,W?.hasAttribute(xu)&&(W.removeAttribute(xu),W.removeAttribute(`role`),W.removeAttribute(`aria-live`),g)){let e=Q.getStatus();gn(W,hn(e),i.statusIndicator??{},e)}},t)))}function hf(){let e=J.getState().pendingSubmission;e&&(ni(void 0),H&&(H.value=e.text,H.dispatchEvent(new Event(`input`,{bubbles:!0})),Ir()),e.options.selectedModelId&&(J.setSelectedModelId(e.options.selectedModelId),Gr?.repaint()),e.options.activeModeIds?.length&&Ur(e.options.activeModeIds),e.options.quote&&Zr(e.options.quote),H?.focus())}let gf=e=>{typeof console<`u`&&console.error(`[AgentWidget] composer.onBeforeSend failed; the draft was preserved:`,e)},_f=(e={})=>{let t=(e.overrideText??H?.value??``).trim();return e.resolveInlineCommand&&t?(Nr?.takeInlineCommand(t)??Promise.resolve(null)).then(n=>vf(e,t,n)):vf(e,t,null)},vf=(e,t,n)=>{if(n?.kind===`action`){ff(),Nr?.clear(),Lr();return}let r=n?.kind===`server`?n.mentions:null,a=n?.kind===`prompt`?n.sendText:t,o=e.pending?.contentParts;if(!ra({text:a,hasAttachments:(Mr?.hasAttachments()??!1)||(o?.length??0)>0,attachmentsReady:Mr?.isReady()??!0,hasMentions:Nr?.hasMentions()??!1,hasServerMentions:!!r,inputDisabled:cu(),sendDisabled:gu()}))return;let s=Q.isStreaming()?$r():`block`;if(s===`defer-one`&&!e.pending){if(J.getState().pendingSubmission){mf(`One message is already queued. Edit or remove it first.`);return}yf({intent:e,sendText:a,serverMentions:r});return}let c={text:a,mentionRefs:[...Nr?.getMentionRefs()??[],...r?.refs??[]],contentSegments:n?.kind===`prompt`?void 0:lf(),options:{...J.getState().selectedModelId&&{selectedModelId:J.getState().selectedModelId},...J.getState().activeModeIds.length>0&&{activeModeIds:[...J.getState().activeModeIds]},...J.getState().quote&&{quote:{...J.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(c.options={...e.pending.options},c.contentSegments=e.pending.contentSegments,c.mentionRefs=[...e.pending.mentionRefs],c.viaVoice=e.pending.viaVoice);let l=()=>{if(o?.length)return[...o];if(!Mr?.hasAttachments())return;let e=[...Mr.getContentParts()];return c.text&&e.push(st(c.text)),e};c.contentParts=l();let u=()=>{Cs(),sf();let t=Nr?.collectForSubmit()??null,n=cf(t,r),a=l();e.consumeDraft!==!1&&ff();let o={selectedModelId:c.options.selectedModelId,activeModeIds:c.options.activeModeIds},u=s===`interrupt`;u&&Q.cancel(),Q.sendMessage(c.text,{contentParts:a,mentions:n??void 0,contentSegments:c.contentSegments,viaVoice:c.viaVoice,composerOptions:o,...c.options.quote&&{quote:c.options.quote},...u&&{interrupt:!0}}),Mr?.hasAttachments()&&Mr.clearAttachments(),t&&Nr?.clear(),Lr();let d=J.getState().activeModeIds,f=Wi(d,i.composer?.modes);f.length!==d.length&&Ur(f),J.getState().quote&&Zr(void 0),Lc(),Li.release(),Vi()},d=i.composer?.onBeforeSend;if(!d){u();return}let f=new AbortController;df=f;let p=e=>{df=null,e.status===`error`?gf(e.error):e.status===`proceed`&&u()},m=oa(d,c,f.signal);if(!(m instanceof Promise))p(m);else return J.setPreparing(!0),m.then(p).finally(()=>J.setPreparing(!1))};function yf(e){let t=J.getState(),n=Mr?.hasAttachments()??!1,r=n?[...Mr.getContentParts()]:[];n&&e.sendText&&r.push(st(e.sendText)),ni(na({text:e.sendText,contentParts:r.length?r:void 0,mentionRefs:[...Nr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:lf(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),e.intent.consumeDraft!==!1&&ff(),n&&Mr.clearAttachments(),Nr?.clear(),Lr(),t.quote&&Zr(void 0),Lc(),Li.release(),Vi(),yr(`Message queued. It sends when the response finishes.`)}function bf(){let e=J.getState().pendingSubmission;e&&(ni(void 0),Ef(e.text,{consumeDraft:!1,pending:e}))}function xf(e){if(i.messageActions?.showEdit!==!0)return;let t=Q.getMessages().find(t=>t.id===e);t&&Dr(t)&&bs!==e&&(Cs(),bs=e,Ss=Yi({messageId:e,initialText:t.content,onSave:t=>Sf(e,t),onCancel:()=>Cs()}),gs.delete(e),Bl(V,Q.getMessages(),lt),Ss.focus())}function Sf(e,t){let n=Ss;bs=null,Ss=null,n?.destroy(),gs.delete(e),Q.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?bl():Bl(V,Q.getMessages(),lt)}function Cf(e){if(Q.isStreaming())return;let t=Tr(Q.getMessages(),e);t&&(Cs(),Q.resubmitFrom(t,{reason:`retry`})&&bl())}ha={regenerate:Cf,edit:xf,quote:e=>{let t=Q.getMessages().find(t=>t.id===e)?.content?.trim();t&&(Zr({text:t,messageId:e}),H?.focus())}};let wf=async e=>{if(!uf){uf=!0;try{await _f({resolveInlineCommand:!0,...e})}finally{uf=!1}}};function Tf(e){gu()||(ff(),Ef(e,{consumeDraft:!1}))}let Ef=(e,t)=>{if(uf)return;uf=!0;let n=()=>{uf=!1};try{let r=_f({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},Df=e=>{e.preventDefault(),Q.isStreaming()?(Q.cancel(),wt?.reset(),Xt?.update()):uf||wf()},Of=()=>i.features?.composerHistory!==!1,kf={...ao},Af=!1,jf=()=>{kf={...ao}},Mf=()=>Q.getMessages().filter(e=>e.role===`user`).map(e=>e.content??``).filter(e=>e.length>0),Nf=e=>{if(!H)return;Af=!0,H.value=e,H.dispatchEvent(new Event(`input`,{bubbles:!0})),Af=!1;let t=H.value.length;H.setSelectionRange(t,t)},Pf=e=>{Af||(e.isComposing||Nr?.handleInput(e.inputType??void 0),jf())},Ff=()=>({submitKey:i.composer?.submitKey,insertNewlineOnTouchEnter:i.composer?.insertNewlineOnTouchEnter,coarsePointer:De(H)}),If=e=>{if(H&&!cu()&&(e.isComposing||!Nr?.handleKeydown(e))){if(Of()&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.isComposing){let t=H.selectionStart===0&&H.selectionEnd===0,n=oo({direction:e.key===`ArrowUp`?`up`:`down`,history:Mf(),currentValue:H.value,atStart:t,state:kf});if(kf=n.state,n.handled){e.preventDefault(),n.value!==void 0&&Nf(n.value);return}}if(Ae(e,Ff())){if(Q.isStreaming()){if(e.preventDefault(),$r()===`block`||uf||gu())return;jf(),wf()}else uf||gu()?e.preventDefault():(jf(),e.preventDefault(),U.click())}}},Lf=e=>{e.key!==`Escape`||e.isComposing||e.composedPath().includes(z)&&(df?(df.abort(),df=null,e.preventDefault(),e.stopImmediatePropagation()):Q.isStreaming()&&(Q.cancel(),wt?.reset(),Xt?.update(),jf(),e.preventDefault(),e.stopImmediatePropagation()))},Rf=async e=>{if(i.attachments?.enabled!==!0||!Mr||cu())return;let t=Cu(e.clipboardData);t.length!==0&&(e.preventDefault(),await Mr.handleFiles(t))},zf=null,Bf=!1,Vf=null,Hf=null,Uf=()=>i.voiceRecognition?.completionBehavior===`review`;function Wf(e){q?.setAttribute(`data-state`,e),e===`recording`?$f():ep()}let Gf=`--persona-voice-level`,Kf=.5,qf=null,Jf=-1,Yf=0,Xf=()=>{let e=[],t=Kn??q?.parentElement??null;return t&&e.push(t),K&&e.push(K),e},Zf=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*100)/100;if(t!==Jf){Jf=t;for(let e of Xf())e.style.setProperty(Gf,String(t))}},Qf=()=>{Jf=-1,Yf=0;for(let e of Xf())e.style.removeProperty(Gf)};function $f(){if(qf!==null)return;if(typeof requestAnimationFrame!=`function`){Zf(g?Q.getVoiceLevel()??Kf:Kf);return}let e=()=>{qf=requestAnimationFrame(e);let t=g?Q.getVoiceLevel():null;t===null?Zf(Kf):(Yf+=(t-Yf)*.3,Zf(Yf))};qf=requestAnimationFrame(e)}function ep(){qf!==null&&(cancelAnimationFrame(qf),qf=null),Qf()}let tp=()=>typeof window>`u`?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,np=(e=`user`)=>{if(Bf||Q.isStreaming())return;let t=tp();if(!t)return;zf=new t;let n=i.voiceRecognition??{},r=n.pauseDuration??2e3;zf.continuous=n.provider?.browser?.continuous??!0,zf.interimResults=!0,zf.lang=n.provider?.browser?.language??`en-US`;let a=H.value;zf.onresult=e=>{let t=``,n=``;for(let r=0;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n=a}let i=a+t+n;H.value=i,Ir(),Vf&&clearTimeout(Vf),(t||n)&&(Vf=window.setTimeout(()=>{if(H.value.trim()&&zf&&Bf){if(rp(),Uf())return;wf({viaVoice:!0})}},r))},zf.onerror=e=>{e.error!==`no-speech`&&rp()},zf.onend=()=>{if(Bf){let e=H.value.trim();!Uf()&&e&&e!==a.trim()&&wf({viaVoice:!0}),rp()}};try{if(zf.start(),Bf=!0,$.active=!0,e!==`system`&&($.manuallyDeactivated=!1),gc(e),vc(),Vi(),q){let e=i.voiceRecognition??{};Hf={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:e.iconName??`mic`,iconSize:parseFloat(e.iconSize??``)||24};let t=e.recordingBackgroundColor,n=e.recordingIconColor,r=e.recordingBorderColor;if(q.classList.add(`persona-voice-recording`),Wf(`recording`),q.style.backgroundColor=t??`var(--persona-voice-recording-bg, #ef4444)`,q.style.color=n??`var(--persona-voice-recording-indicator, #ffffff)`,n){let e=q.querySelector(`svg`);e&&e.setAttribute(`stroke`,n)}r&&(q.style.borderColor=r),q.setAttribute(`aria-label`,`Stop voice recognition`)}}catch{rp(`system`)}},rp=(e=`user`)=>{if(Bf){if(Bf=!1,Vf&&=(clearTimeout(Vf),null),zf){try{zf.stop()}catch{}zf=null}if($.active=!1,gc(e),vc(),Vi(),q){if(q.classList.remove(`persona-voice-recording`),Wf(`idle`),Hf){q.style.backgroundColor=Hf.backgroundColor,q.style.color=Hf.color,q.style.borderColor=Hf.borderColor;let e=q.querySelector(`svg`);e&&e.setAttribute(`stroke`,Hf.color||`currentColor`),Hf=null}q.setAttribute(`aria-label`,`Start voice recognition`)}}},ip=null,ap=e=>{let t=t=>{ip??=t.createMicStateStyles({mic:()=>q,config:()=>i,session:()=>Q,get original(){return Hf},set original(e){Hf=e},setMicState:Wf,renderIcon:N,iconFallbackPx:24}),e(ip)},n=Fr();n?t(n):Pr().then(t,()=>{})},op=()=>ap(e=>e.recording()),sp=()=>ap(e=>e.processing()),cp=()=>ap(e=>e.speaking()),lp=()=>ap(e=>e.reset()),up=()=>{if(!cu()){if(Cn(i.voiceRecognition?.provider)){let e=Q.getVoiceStatus(),t=Q.getVoiceInterruptionMode();if(t===`none`&&(e===`processing`||e===`speaking`))return;if(t===`cancel`&&(e===`processing`||e===`speaking`)){Q.stopVoicePlayback();return}if(Q.isBargeInActive()){Q.stopVoicePlayback(),Q.deactivateBargeIn().then(()=>{$.active=!1,$.manuallyDeactivated=!0,vc(),gc(`user`),lp()});return}Q.toggleVoice().then(()=>{$.active=mc(),$.manuallyDeactivated=!$.active,vc(),gc(`user`),$.active?op():lp()})}else if(Bf){let e=H.value.trim();$.manuallyDeactivated=!0,vc(),rp(`user`),e&&!Uf()&&wf()}else $.manuallyDeactivated=!1,vc(),np(`user`)}};si=up;let dp=()=>Q.prewarmVoice(),fp=()=>{let e=i.voiceRecognition;return e?.enabled===!0?e.prewarm??(i.clientToken?`hover`:!1):!1},pp=e=>{fp()===`hover`&&q?.contains(e.target)&&dp()},mp=[`pointerover`,`pointerdown`,`focusin`];mp.forEach(e=>t.addEventListener(e,pp));let hp,gp=null,_p,vp=()=>{let e=_p;_p=void 0;try{typeof e==`function`&&e()}catch{}},yp=()=>{let e=fp(),n=typeof e==`function`&&q?e:void 0,r=n?q:null;if((n!==hp||r!==gp)&&(vp(),hp=n,gp=r,n&&r))try{_p=n({warm:dp,micButton:r,mount:t})}catch{}};yp(),Z.push(()=>{mp.forEach(e=>t.removeEventListener(e,pp)),vp()}),q&&Z.push(()=>{Cn(i.voiceRecognition?.provider)?(Q.isVoiceActive()&&Q.toggleVoice(),lp()):rp(`system`)});let bp=O.on(`assistant:complete`,()=>{J.getState().pendingSubmission&&setTimeout(()=>{Q.isStreaming()||bf()},0)});Z.push(bp);let xp=O.on(`assistant:complete`,()=>{pc&&($.active||$.manuallyDeactivated||(pc!==`assistant`||$.lastUserMessageWasVoice)&&setTimeout(()=>{!$.active&&!$.manuallyDeactivated&&(Cn(i.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=Q.isVoiceActive(),gc(`auto`),Q.isVoiceActive()&&op()}):np(`auto`))},600))});Z.push(xp);let Sp=O.on(`action:resubmit`,()=>{setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)});Z.push(Sp);let Cp=()=>{ou(!F,`user`)},wp=null,Tp=null;if(Be&&!P()){let{instance:e,element:t}=sc({config:i,plugins:f,onToggle:Cp});wp=e,e||(Tp=t)}wp?t.appendChild(wp.element):Tp&&t.appendChild(Tp),au(),us(),od(),id(),Iu(Q.isStreaming()),fl()||(tr()===`follow`?al(!0):cl()),yc(),We&&(!Be||P()?setTimeout(()=>Lu(),0):F&&setTimeout(()=>Lu(),200));let Ep=null,Dp=()=>{Ep&&(Ep.disconnect(),Ep.observe(K),Ep.observe(z),Ep.observe(On))},Op=br(),kp=()=>{if(P()){Or(),au();return}let e=xo(i),n=i.launcher?.sidebarMode??!1,r=t.ownerDocument.defaultView??window,a=i.launcher?.mobileFullscreen??!0,o=i.launcher?.mobileBreakpoint??640,s=r.innerWidth<=o,c=a&&s&&Be;try{if(c){va(),ya=_o();return}let t=!1;Ye&&(Ye=!1,va(),t=!0);let r=_o();if(!t&&r!==ya&&(va(),t=!0),ya=r,t&&Ha(),!Be&&!e){L.style.height=``,L.style.width=``;return}if(!n&&!e){let e=Us(i);L.style.width=e.width,L.style.maxWidth=e.maxWidth}po(),Mo()}finally{Or(),Ar();let e=br();if(e!==Op&&(Op=e,Xu(),us()),au(),F&&Be){let e=(t.ownerDocument.defaultView??window).innerWidth<=(i.launcher?.mobileBreakpoint??640),n=i.launcher?.sidebarMode??!1,r=i.launcher?.mobileFullscreen??!0,a=xo(i)&&r&&e,o=n||r&&e&&Be||a;if(o&&!Io){let e=t.getRootNode(),n=e instanceof ShadowRoot?e.host:t.closest(`.persona-host`);n&&!Fo&&(Fo=go(n,i.launcher?.zIndex??1e5)),Io=yo(t.ownerDocument)}else o||(Fo?.(),Fo=null,Io?.(),Io=null)}}};kp();let Ap=t.ownerDocument.defaultView??window;if(Ap.addEventListener(`resize`,kp),Z.push(()=>Ap.removeEventListener(`resize`,kp)),typeof ResizeObserver<`u`){Ep=new ResizeObserver(()=>{Ar()}),Dp(),Z.push(()=>{Ep?.disconnect(),Ep=null});let e=new ResizeObserver(()=>{Zd()});e.observe(z),Z.push(()=>e.disconnect())}Ap.addEventListener(`resize`,Zd),Z.push(()=>Ap.removeEventListener(`resize`,Zd)),js=B.scrollTop;let jp=Mt(B),Mp=()=>{Do();let e=B.scrollTop,t=Mt(B),n=t<jp;if(jp=t,!nr()){js=e,nl();return}let{action:r,nextLastScrollTop:i}=jt({following:Os.isFollowing(),currentScrollTop:e,lastScrollTop:js,nearBottom:Lt(B,24),userScrollThreshold:4,isAutoScrolling:Is||Ls||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});js=i,r===`resume`?dl()||il():r===`pause`&&rl()};if(B.addEventListener(`scroll`,Mp,{passive:!0}),Z.push(()=>B.removeEventListener(`scroll`,Mp)),typeof ResizeObserver<`u`){let e=new ResizeObserver(()=>{Sl(),Mn(V)});e.observe(V),e.observe(B),Z.push(()=>e.disconnect())}let Np=()=>{nr()&&Os.isFollowing()&&dl()&&rl()},Pp=B.ownerDocument;Pp.addEventListener(`selectionchange`,Np),Z.push(()=>{Pp.removeEventListener(`selectionchange`,Np)});let Fp=/* @__PURE__ */ new Set([`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`]),Ip=e=>{Fp.has(e.key)&&(ec(),ar()&&nr()&&Os.isFollowing()&&rl())},Lp=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&(ec(),ar()&&nr()&&Os.isFollowing()&&rl())};B.addEventListener(`keydown`,Ip),B.addEventListener(`focusin`,Lp),Z.push(()=>{B.removeEventListener(`keydown`,Ip),B.removeEventListener(`focusin`,Lp)});let Rp=e=>{if(e.deltaY!==0&&ec(),!nr())return;let t=Nt({following:Os.isFollowing(),deltaY:e.deltaY,nearBottom:Lt(B,24),resumeWhenNearBottom:!0});t===`pause`?rl():t===`resume`&&!dl()&&il()};B.addEventListener(`wheel`,Rp,{passive:!0}),B.addEventListener(`touchmove`,ec,{passive:!0}),B.addEventListener(`pointerdown`,ec,{passive:!0}),Z.push(()=>{B.removeEventListener(`touchmove`,ec),B.removeEventListener(`pointerdown`,ec)}),Z.push(()=>B.removeEventListener(`wheel`,Rp)),lr.addEventListener(`click`,()=>{gl(),B.scrollTop=B.scrollHeight,js=B.scrollTop,il(),al(!0),nl()}),Z.push(()=>lr.remove()),Z.push(()=>{Gc(),gl()});let zp=()=>{G&&(Qo&&=(G.removeEventListener(`click`,Qo),null),it()?(G.style.display=``,Qo=()=>{ou(!1,`user`)},G.addEventListener(`click`,Qo)):G.style.display=`none`)};zp(),(()=>{let{clearChatButton:e}=R;e&&e.addEventListener(`click`,()=>{let e=Fd;if(e?.historyAvailable()){e.startNewConversation({focusComposer:!0}).catch(e=>{i.debug&&console.warn(`[AgentWidget] New conversation failed:`,e)});return}Q.clearMessages(),i.layout?.topFade&&(B.scrollTop=0),B.removeAttribute(`data-persona-top-fade`),gs.clear(),il(),Xe(R.composerOverlay);try{localStorage.removeItem(yu),i.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${yu}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(i.clearChatHistoryStorageKey&&i.clearChatHistoryStorageKey!==yu)try{localStorage.removeItem(i.clearChatHistoryStorageKey),i.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${i.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let t=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(t),fe?.clear&&Ec(()=>fe.clear(),`[AgentWidget] Failed to clear storage adapter:`),pe={},ze.syncFromMetadata(),Mr?.clearAttachments(),Lc(),ni(void 0),Zr(void 0),Cs(),St?.clear(),wt?.reset(),Xt?.update()})})();let Bp=[[`keydown`,If],[`input`,Pf],[`input`,Ir],[`input`,Lr],[`keyup`,Lr],[`paste`,Rf],[`focus`,wi]],Vp=e=>{if(e)for(let[t,n]of Bp)Y?.addListener(e,t,n)},Hp=e=>{if(e)for(let[t,n]of Bp)Y?.removeListener(e,t,n)},Up=()=>{Y&&(Y.addListener(Y.form,`submit`,Df),Y.addListener(Y.footer,`click`,Lr),Vp(H),q&&Y.addListener(q,`click`,up),yp())};Up();let Wp=()=>{Nr?.onComposerSwap((e,t)=>{Hp(t),H=e,Y&&(Y.input=e),Vp(e),yi(),Fu(),Ir()})};Wp();let Gp=!1;function Kp(){if(!Gp){Gp=!0;try{let e=H?.value??``,t=K.ownerDocument??document,n=H?t.activeElement===H:!1;ep(),Y?.destroy(),Y=null,Nr?.destroy(),Nr=null;let r=null,a=()=>(r=P()?Yo({config:i}):qo({config:i}),r.footer),o=gi(a)??a();_n.replaceComposer(o),K=_n.composer.footer;let s=r!==null&&o===r.footer;hi=!s,Gn=s?r.setSendButtonMode:()=>{},mi(K),bi(K),Si(),Ci(),Ti(),Wp(),ki(),ji(),Mi(),Up();let c=Zo.indexOf(Go);if(Go.destroy(),Go=Ao(En),c>=0&&(Zo[c]=Go),H&&(H.value=e),Ir(),Lr(),od(),us(),Iu(Q.isStreaming()),i.statusIndicator?.mode===`transient`&&!P()){let e=Q.getStatus();gn(W,hn(e),i.statusIndicator,e)}$.active&&Wf(`recording`),va(),Dp(),Or(),Vi(),Nu(),n&&H?.focus()}finally{Gp=!1}}}let qp=t.ownerDocument??document;qp.addEventListener(`keydown`,Lf,!0);let Jp=()=>{Fc()},Yp=()=>{qp.visibilityState===`hidden`&&Fc()};typeof window<`u`&&(window.addEventListener(`pagehide`,Jp),qp.addEventListener(`visibilitychange`,Yp),Z.push(()=>{window.removeEventListener(`pagehide`,Jp),qp.removeEventListener(`visibilitychange`,Yp)}));let Xp=`persona-attachment-drop-active`,Zp=0,Qp=()=>{Zp=0,z.classList.remove(Xp)},$p=()=>i.attachments?.enabled===!0&&Mr!==null&&!cu(),em=e=>{wu(e.dataTransfer)&&$p()&&(Zp++,Zp===1&&z.classList.add(Xp))},tm=e=>{wu(e.dataTransfer)&&$p()&&(Zp--,Zp<=0&&Qp())},nm=e=>{wu(e.dataTransfer)&&$p()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},rm=e=>{if(!wu(e.dataTransfer)||!$p())return;e.preventDefault(),e.stopPropagation(),Qp();let t=Array.from(e.dataTransfer.files??[]);t.length!==0&&Mr.handleFiles(t)};z.addEventListener(`dragenter`,em,!0),z.addEventListener(`dragleave`,tm,!0),t.addEventListener(`dragover`,nm,!0),t.addEventListener(`drop`,rm,!0);let im=t.ownerDocument,am=e=>{$p()&&e.preventDefault()},om=e=>{$p()&&e.preventDefault()};im.addEventListener(`dragover`,am),im.addEventListener(`drop`,om),Z.push(()=>{Y?.destroy(),Y=null,ep(),Ei?.destroy(),Ei=null,qr?.destroy(),qr=null,Xr?.destroy(),Xr=null,ti?.destroy(),ti=null,Gr=null,Kr=null,Fc(),Nc.destroy(),pf&&clearTimeout(pf),Cs(),df?.abort(),df=null,Mr?.destroy(),Mr=null,J.destroy(),qp.removeEventListener(`keydown`,Lf,!0),Nr?.destroy()}),Z.push(()=>{z.removeEventListener(`dragenter`,em,!0),z.removeEventListener(`dragleave`,tm,!0),t.removeEventListener(`dragover`,nm,!0),t.removeEventListener(`drop`,rm,!0),im.removeEventListener(`dragover`,am),im.removeEventListener(`drop`,om),Qp()}),Z.push(()=>{Q.cancel()}),wp?Z.push(()=>{wp?.destroy()}):Tp&&Z.push(()=>{Tp?.remove()});let sm={update(e){let n=i.future?.v5Defaults===!0,r=i.toolCall,a=i.messageActions,o=i.layout?.messages,s=i.colorScheme,c=i.loadingIndicator,l=i.iterationDisplay,p=i.features?.showReasoning,m=i.features?.showToolCalls,h=i.features?.toolCallDisplay,g=i.features?.reasoningDisplay,_=i.features?.streamAnimation?.type,v=i.features?.history?.enabled===!0,y=i.features?.history?.provider,x=i.getIdentityProof,T=i.clientToken,E=i.contextMentions;i=Rl({...i,features:d},e),d=i.features,i=xl(i),u(),bo(),Za(t,i),Xc(t,i),Zc(t,i),ln(),vo(),i.colorScheme!==s&&zo();let D=Pl.getForInstance(i.plugins);f.length=0,f.push(...D),Vd(),Be=i.launcher?.enabled??!0,He=i.launcher?.autoExpand??!1,ut=i.features?.showReasoning??!0,dt=i.features?.showToolCalls??!0,mt=i.features?.scrollToBottom??{};let ee=tr();ht=i.features?.scrollBehavior??{},ee!==tr()&&(gl(),il()),rc(),jr(),nl();let te=ft;if(ft=i.features?.showEventStreamToggle??!1,ft&&!te){if(St||(an(),Q.setSSEEventCallback((e,t)=>{i.onSSEEvent?.(e,t),rn(e,t)})),!fi&&Bn){let e=i.features?.eventStream?.classNames,t=`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`+(e?.toggleButton?` `+e.toggleButton:``);fi=M(`button`,t),fi.style.width=`28px`,fi.style.height=`28px`,fi.style.color=Lo.actionIconColor,fi.type=`button`,fi.setAttribute(`aria-label`,`Event Stream`),fi.title=`Event Stream`;let n=b(Yt,`18px`,`currentColor`,1.5);n&&fi.appendChild(n);let r=R.clearChatButtonWrapper,a=R.closeButtonWrapper,o=r||a;o&&o.parentNode===Bn?Bn.insertBefore(fi,o):Bn.appendChild(fi),fi.addEventListener(`click`,()=>{Qt?di():ui()})}}else!ft&&te&&(di(),fi&&=(fi.remove(),null),St?.clear(),yt?.destroy(),St=null,yt=null,wt?.reset(),wt=null,Et=null);if(i.launcher?.enabled===!1&&wp&&(wp.destroy(),wp=null),i.launcher?.enabled===!1&&Tp&&(Tp.remove(),Tp=null),i.launcher?.enabled!==!1&&!wp&&!Tp){let{instance:e,element:n}=sc({config:i,plugins:f,onToggle:Cp});wp=e,e||(Tp=n),t.appendChild(n)}wp&&wp.update(i),Wd(),zn&&i.launcher?.subtitle!==void 0&&(zn.textContent=i.launcher.subtitle);let ne=i.layout?.header;if(ne?.layout!==Je&&Bn){let e=ne?Ko(i,ne,{showClose:it(),onClose:()=>ou(!1,`user`)}):Bo({config:i,showClose:it(),onClose:()=>ou(!1,`user`)});_n.replaceHeader(e),Bn=_n.header.element,Ln=_n.header.iconHolder,Rn=_n.header.headerTitle,zn=_n.header.headerSubtitle,G=_n.header.closeButton,Je=ne?.layout,Wd()}else if(ne){if(Ln&&(Ln.style.display=ne.showIcon===!1?`none`:``),Rn&&(Rn.style.display=ne.showTitle===!1?`none`:``),zn&&(zn.style.display=ne.showSubtitle===!1?`none`:``),G){let e=it()&&ne.showCloseButton!==!1;G.style.display=e?``:`none`}if(R.clearChatButtonWrapper){let e=ne.showClearChat;if(e!==void 0){R.clearChatButtonWrapper.style.display=e?``:`none`;let{closeButtonWrapper:t}=R;t&&!t.classList.contains(`persona-absolute`)&&(e?t.classList.remove(`persona-ml-auto`):t.classList.add(`persona-ml-auto`))}}}let re=i.layout?.showHeader!==!1;Bn&&(Bn.style.display=re?``:`none`);let ie=i.layout?.showFooter!==!1;K&&(K.style.display=ie?``:`none`),Or(),nl(),Be===qe?He!==Ke&&ou(He,`auto`):Be?ou(He,`auto`):(F=!0,au()),Ke=He,qe=Be,kp(),zp();let ae=JSON.stringify(i.toolCall)!==JSON.stringify(r),oe=JSON.stringify(i.messageActions)!==JSON.stringify(a),se=JSON.stringify(i.layout?.messages)!==JSON.stringify(o),ce=i.loadingIndicator?.render!==c?.render||i.loadingIndicator?.renderIdle!==c?.renderIdle||i.loadingIndicator?.showBubble!==c?.showBubble,le=i.iterationDisplay!==l,de=(i.features?.showReasoning??!0)!==(p??!0)||(i.features?.showToolCalls??!0)!==(m??!0)||JSON.stringify(i.features?.toolCallDisplay)!==JSON.stringify(h)||JSON.stringify(i.features?.reasoningDisplay)!==JSON.stringify(g);(i.future?.v5Defaults===!0!==n||ae||oe||se||ce||le||de)&&Q&&(Es++,Bl(V,Q.getMessages(),lt));let fe=i.features?.streamAnimation?.type;if(fe!==_&&fe&&fe!==`none`){let e=Uo(fe,i.features?.streamAnimation?.plugins);e&&Wt(e,t)}let k=i.launcher??{},pe=k.headerIconHidden??!1,me=i.layout?.header?.showIcon,he=pe||me===!1,ge=k.headerIconName,_e=k.headerIconSize??`40px`;if(Ln){let e=Bn,t=e?.querySelector(`.persona-flex-col`);if(he)Ln.style.display=`none`,e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(Ln.style.display=``,Ln.style.height=_e,Ln.style.width=_e,e&&t&&(e.contains(Ln)?Ln.nextSibling!==t&&(Ln.remove(),e.insertBefore(Ln,t)):e.insertBefore(Ln,t)),ge){let e=parseFloat(_e)||24,t=N(ge,e*.6,`currentColor`,1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,Ln.replaceChildren(t)):Ln.textContent=k.agentIconText??`💬`}else if(k.iconUrl){let e=Ln.querySelector(`img`);if(e)e.src=k.iconUrl,e.style.height=_e,e.style.width=_e;else{let e=document.createElement(`img`);e.src=k.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=_e,e.style.width=_e,Ln.replaceChildren(e)}}else{let e=Ln.querySelector(`svg`),t=Ln.querySelector(`img`);(e||t)&&Ln.replaceChildren(),Ln.textContent=k.agentIconText??`💬`}let n=Ln.querySelector(`img`);n&&(n.style.height=_e,n.style.width=_e)}}let ve=i.layout?.header?.showTitle,ye=i.layout?.header?.showSubtitle;if(Rn&&(Rn.style.display=ve===!1?`none`:``),zn&&(zn.style.display=ye===!1?`none`:``),G){let e=it()&&i.layout?.header?.showCloseButton!==!1;if(G.style.display=e?``:`none`,!P()){let e=k.closeButtonSize??``;G.style.height=e,G.style.width=e,G.style.minWidth=e,G.style.minHeight=e}let t=k.closeButtonPlacement??`inline`,{closeButtonWrapper:n}=R,r=t===`top-right`,a=n?.classList.contains(`persona-absolute`);if(n&&r!==a){if(n.remove(),r){n.className=`persona-absolute persona-top-4 persona-right-4 persona-z-50`;let e=Fd?.railColumn??z;e.style.position=`relative`,e.appendChild(n)}else{let e=k.clearChat?.placement??`inline`;n.className=(k.clearChat?.enabled??!0)&&e===`inline`?``:`persona-ml-auto`,Bn&&Bn.appendChild(n)}}if(G.style.color=k.closeButtonColor||Lo.actionIconColor,k.closeButtonBackgroundColor?(G.style.backgroundColor=k.closeButtonBackgroundColor,G.classList.remove(`hover:persona-bg-gray-100`)):(G.style.backgroundColor=``,G.classList.add(`hover:persona-bg-gray-100`)),k.closeButtonBorderWidth||k.closeButtonBorderColor){let e=k.closeButtonBorderWidth||`0px`,t=k.closeButtonBorderColor||`transparent`;G.style.border=`${e} solid ${t}`,G.classList.remove(`persona-border-none`)}else G.style.border=``,G.classList.add(`persona-border-none`);k.closeButtonBorderRadius?(G.style.borderRadius=k.closeButtonBorderRadius,G.classList.remove(`persona-rounded-full`)):(G.style.borderRadius=``,G.classList.add(`persona-rounded-full`)),k.closeButtonPaddingX?(G.style.paddingLeft=k.closeButtonPaddingX,G.style.paddingRight=k.closeButtonPaddingX):(G.style.paddingLeft=``,G.style.paddingRight=``),k.closeButtonPaddingY?(G.style.paddingTop=k.closeButtonPaddingY,G.style.paddingBottom=k.closeButtonPaddingY):(G.style.paddingTop=``,G.style.paddingBottom=``),No(G,k.closeButtonIconName??`x`,{iconSize:P()?Gs:void 0,iconText:k.closeButtonIconText??`×`});let o=k.closeButtonTooltipText??`Close chat`,s=k.closeButtonShowTooltip??!0;G.setAttribute(`aria-label`,o),n&&S({anchor:G,trigger:n,text:()=>G?.getAttribute(`aria-label`)??o,enabled:s})}let{clearChatButton:A,clearChatButtonWrapper:be}=R;if(A){let e=k.clearChat??{},t=e.enabled??!0,n=i.layout?.header?.showClearChat,r=n===void 0?t:n,a=e.placement??`inline`;if(be){be.style.display=r?``:`none`;let{closeButtonWrapper:e}=R;!P()&&e&&!e.classList.contains(`persona-absolute`)&&(r?e.classList.remove(`persona-ml-auto`):e.classList.add(`persona-ml-auto`));let t=a===`top-right`,n=be.classList.contains(`persona-absolute`);if(!P()&&t!==n&&r){if(be.remove(),t){be.className=`persona-absolute persona-top-4 persona-z-50`,be.style.right=`48px`;let e=Fd?.railColumn??z;e.style.position=`relative`,e.appendChild(be)}else{be.className=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,be.style.right=``;let e=R.closeButtonWrapper;Bn&&e&&e.parentElement===Bn?Bn.insertBefore(be,e):Bn&&Bn.appendChild(be)}let e=R.closeButtonWrapper;e&&!e.classList.contains(`persona-absolute`)&&(t?e.classList.add(`persona-ml-auto`):e.classList.remove(`persona-ml-auto`))}}if(r){if(!P()){let t=e.size??``;A.style.height=t,A.style.width=t,A.style.minWidth=t,A.style.minHeight=t}let t=e.iconColor??``;if(A.style.color=t||Lo.actionIconColor,No(A,e.iconName??`refresh-cw`,{iconSize:P()?Ks:void 0}),e.backgroundColor?(A.style.backgroundColor=e.backgroundColor,A.classList.remove(`hover:persona-bg-gray-100`)):(A.style.backgroundColor=``,A.classList.add(`hover:persona-bg-gray-100`)),e.borderWidth||e.borderColor){let t=e.borderWidth||`0px`,n=e.borderColor||`transparent`;A.style.border=`${t} solid ${n}`,A.classList.remove(`persona-border-none`)}else A.style.border=``,A.classList.add(`persona-border-none`);e.borderRadius?(A.style.borderRadius=e.borderRadius,A.classList.remove(`persona-rounded-full`)):(A.style.borderRadius=``,A.classList.add(`persona-rounded-full`)),e.paddingX?(A.style.paddingLeft=e.paddingX,A.style.paddingRight=e.paddingX):(A.style.paddingLeft=``,A.style.paddingRight=``),e.paddingY?(A.style.paddingTop=e.paddingY,A.style.paddingBottom=e.paddingY):(A.style.paddingTop=``,A.style.paddingBottom=``);let n=e.tooltipText??`Clear chat`,r=e.showTooltip??!0;A.setAttribute(`aria-label`,n),be&&S({anchor:A,trigger:be,text:()=>A?.getAttribute(`aria-label`)??n,enabled:r})}}let Se=i.actionParsers&&i.actionParsers.length?i.actionParsers:[Hl],Ce=i.actionHandlers&&i.actionHandlers.length?i.actionHandlers:[Wl.message,Wl.messageAndClick];ze=Kl({parsers:Se,handlers:Ce,getSessionMetadata:j,updateSessionMetadata:Ne,emit:O.emit,documentRef:typeof document<`u`?document:null}),lt=ku(i,ze,ct),_d(),Q.updateConfig(i),af(),(i.features?.history?.enabled===!0!==v||i.features?.history?.provider!==y||i.getIdentityProof!==x||i.clientToken!==T)&&(Fd?.closeHistory({restoreFocus:!1}),Fd?.installHistoryProvider()),Fd?.syncHistoryChromeImpl(),Zd(),zd()&&!Fd&&Yd().catch(()=>{}),Bl(V,Q.getMessages(),lt),us(),od(),ad(),Iu(Q.isStreaming()),E!==i.contextMentions&&Kp();let Te=i.voiceRecognition?.enabled===!0,De=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),Oe=Cn(i.voiceRecognition?.provider);if(Te&&(De||Oe)){if(!q||!Kn){let e=Ee(i);if(e){q=e.button,Kn=e.wrapper;let t=Wn&&Wn.parentElement===Un?Wn:null;Un?Un.insertBefore(Kn,t):Dn?.appendChild(Kn),Y&&(Y.micButton=q),Y?.addListener(q,`click`,up),q.disabled=cu()||Q.isStreaming()&&!pu()}}else{let e=i.voiceRecognition??{},t=i.sendButton??{},n=e.iconName??`mic`,r=e.iconSize,a=parseFloat(r??``)||24;q.classList.add(ue),q.classList.toggle(xe,!r),q.style.width=r??``,q.style.height=r??``,q.style.minWidth=r??``,q.style.minHeight=r??``;let o=e.iconColor??t.textColor;q.innerHTML=``;let s=N(n,a,o||`currentColor`,1.5);s?q.appendChild(s):q.textContent=`🎤`;let c=e.backgroundColor??t.backgroundColor;c?q.style.backgroundColor=c:q.style.backgroundColor=``,o?q.style.color=o:q.style.color=`var(--persona-text, #111827)`,e.borderWidth?(q.style.borderWidth=e.borderWidth,q.style.borderStyle=`solid`):(q.style.borderWidth=``,q.style.borderStyle=``),e.borderColor?q.style.borderColor=e.borderColor:q.style.borderColor=``,e.paddingX?(q.style.paddingLeft=e.paddingX,q.style.paddingRight=e.paddingX):(q.style.paddingLeft=``,q.style.paddingRight=``),e.paddingY?(q.style.paddingTop=e.paddingY,q.style.paddingBottom=e.paddingY):(q.style.paddingTop=``,q.style.paddingBottom=``);let l=e.tooltipText??`Start voice recognition`,u=e.showTooltip??!1;q.setAttribute(`aria-label`,l),Kn&&S({anchor:q,trigger:Kn,text:()=>q?.getAttribute(`aria-label`)??l,enabled:u}),Kn.style.display=``,q.disabled=cu()||Q.isStreaming()&&!pu()}}else q&&Kn&&(Kn.style.display=`none`,Cn(i.voiceRecognition?.provider)?Q.isVoiceActive()&&Q.toggleVoice():Bf&&rp());if(yp(),i.attachments?.enabled===!0){if(!Jn||!qn){let e=i.attachments??{};Xn||(Xn=M(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),Xn.style.display=`none`,(H.parentElement??Dn).insertBefore(Xn,H)),Yn||(Yn=document.createElement(`input`),Yn.type=`file`,Yn.accept=(e.allowedTypes??pt).join(`,`),Yn.multiple=(e.maxFiles??4)>1,Yn.style.display=`none`,Yn.setAttribute(`aria-label`,`Attach files`),(H.parentElement??Dn).insertBefore(Yn,H)),Jn=M(`div`,`persona-send-button-wrapper`),qn=M(`button`,`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ue} ${xe}`),qn.type=`button`,qn.setAttribute(`aria-label`,e.buttonTooltipText??`Attach file`);let t=e.buttonIconName??`paperclip`;qn.style.fontSize=`18px`,qn.style.lineHeight=`1`;let n=N(t,24,`currentColor`,1.5);n?qn.appendChild(n):qn.textContent=`📎`,qn.addEventListener(`click`,e=>{e.preventDefault(),Yn?.click()}),Jn.appendChild(qn);let r=e.buttonTooltipText??`Attach file`;S({anchor:qn,trigger:Jn,text:()=>qn?.getAttribute(`aria-label`)??r}),Hn?Hn.append(Jn):Dn.appendChild(Jn),Y&&(Y.attachmentButton=qn,Y.attachmentInput=Yn??void 0,Y.attachmentPreviews=Xn??void 0),!Mr&&Yn&&Xn&&(Mr=ei.fromConfig(e,zr),Mr.setPreviewsContainer(Xn),Y?.addListener(Yn,`change`,async()=>{Mr&&Yn?.files&&(await Mr.handleFileSelect(Yn.files),Yn.value=``)}))}else{Jn.style.display=``;let e=i.attachments??{};Yn&&(Yn.accept=(e.allowedTypes??pt).join(`,`),Yn.multiple=(e.maxFiles??4)>1),Mr&&Mr.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}if(z.querySelector(`.persona-attachment-drop-overlay`)?.remove(),z.appendChild(Au(i.attachments?.dropOverlay)),qn){let e=i.attachments??{},t=e.buttonTooltipText??`Attach file`;qn.setAttribute(`aria-label`,t),qn.textContent=``;let n=N(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);n?qn.appendChild(n):qn.textContent=`📎`,Jn&&S({anchor:qn,trigger:Jn,text:()=>qn?.getAttribute(`aria-label`)??t})}}else Jn&&(Jn.style.display=`none`),Mr&&Mr.clearAttachments(),z.querySelector(`.persona-attachment-drop-overlay`)?.remove();let ke=i.sendButton??{},Ae=ke.useIcon??!1,je=ke.iconText??`↑`,Me=ke.iconName,Pe=ke.tooltipText??`Send message`,Fe=ke.showTooltip??!1,Ie=ke.size,Le=parseFloat(Ie??``)||40,Re=ke.backgroundColor,Ve=ke.textColor;if(Ae){if(U.style.width=Ie??``,U.style.height=Ie??``,U.style.minWidth=Ie??``,U.style.minHeight=Ie??``,U.style.fontSize=`18px`,U.style.lineHeight=`1`,Ve?U.style.color=Ve:U.style.color=`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`,!Q.isStreaming()){if(U.innerHTML=``,Me){let e=parseFloat(ke.iconSize??``)||Math.round(Le*.5),t=Ve?.trim()||`currentColor`,n=ke.iconStrokeWidth??2,r=N(Me,e,t,n),i=N(ke.stopIconName??`square`,e,t,n);r&&i?U.appendChild(we(r,i)):r?U.appendChild(r):U.textContent=je}else U.textContent=je}U.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${ue}`,Re?(U.style.backgroundColor=Re,U.classList.remove(`persona-bg-persona-primary`)):(U.style.backgroundColor=``,U.classList.add(`persona-bg-persona-primary`))}else U.textContent=i.copy?.sendButtonLabel??`Send`,U.style.width=``,U.style.height=``,U.style.minWidth=``,U.style.minHeight=``,U.style.fontSize=``,U.style.lineHeight=``,U.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`,Re?(U.style.backgroundColor=Re,U.classList.remove(`persona-bg-persona-accent`)):U.classList.add(`persona-bg-persona-accent`),Ve?U.style.color=Ve:U.classList.add(`persona-text-white`);ke.borderWidth?(U.style.borderWidth=ke.borderWidth,U.style.borderStyle=`solid`):(U.style.borderWidth=``,U.style.borderStyle=``),ke.borderColor?U.style.borderColor=ke.borderColor:U.style.borderColor=``,ke.paddingX?(U.style.paddingLeft=ke.paddingX,U.style.paddingRight=ke.paddingX):(U.style.paddingLeft=``,U.style.paddingRight=``),ke.paddingY?(U.style.paddingTop=ke.paddingY,U.style.paddingBottom=ke.paddingY):(U.style.paddingTop=``,U.style.paddingBottom=``),Q.isStreaming()||U.setAttribute(`aria-label`,Pe),Nu(),Wn&&S({anchor:U,trigger:Wn,text:()=>U.getAttribute(`aria-label`)??Pe,enabled:Fe}),ia(),Oo();let Ue=Ui(J.getState().activeModeIds,i.composer?.modes);J.setActiveModeIds(Ue),Vr().length>0!=!!qr&&ji(),qr?.render(Ue,Vr());for(let e of[...Yr.keys()])Ri(e,i.composer?.modeGroups)||Yr.delete(e);Yr.forEach(e=>e.repaint()),Gr?.repaint(),Ei?.resolve();let We=$a(i,P());if(wo(),We){V.style.maxWidth=We,V.style.marginLeft=`auto`,V.style.marginRight=`auto`,V.style.width=`100%`,jn.style.maxWidth=We,jn.style.marginLeft=`auto`,jn.style.marginRight=`auto`,jn.style.width=`100%`;for(let e of[Dn,En,Xn,W])e&&(e.style.maxWidth=We,e.style.marginLeft=`auto`,e.style.marginRight=`auto`,e.style.width=`100%`)}else{V.style.maxWidth=``,V.style.marginLeft=``,V.style.marginRight=``,V.style.width=``,jn.style.maxWidth=``,jn.style.marginLeft=``,jn.style.marginRight=``,jn.style.width=``;for(let e of[Dn,En,Xn,W])e&&(e.style.maxWidth=``,e.style.marginLeft=``,e.style.marginRight=``,e.style.width=``)}let Ge=i.statusIndicator??{};if(C(W,Dn,Ge),w(W,Ge,Q?.getStatus()??`idle`),Q){let e=Q.getStatus();gn(W,(e=>e===`idle`?Ge.idleText??xt.idle:e===`connecting`?Ge.connectingText??xt.connecting:e===`connected`?Ge.connectedText??xt.connected:e===`error`?Ge.errorText??xt.error:e===`paused`?Ge.pausedText??xt.paused:e===`resuming`?Ge.resumingText??xt.resuming:xt[e])(e),Ge,e)}W.classList.remove(`persona-text-left`,`persona-text-center`,`persona-text-right`);let Ye=Ge.align===`left`?`persona-text-left`:Ge.align===`center`?`persona-text-center`:`persona-text-right`;W.classList.add(Ye),yi(),Fu(),Vi(),cn()},open(){it()&&ou(!0,`api`)},close(){it()&&ou(!1,`api`)},toggle(){it()&&ou(!F,`api`)},reconnect(){Q.reconnectNow()},clearChat(){Sa=!1,c.clear(),o.clear(),s.clear(),l.clear(),Q.clearMessages(),i.layout?.topFade&&(B.scrollTop=0),B.removeAttribute(`data-persona-top-fade`),gs.clear(),il();try{localStorage.removeItem(yu),i.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${yu}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(i.clearChatHistoryStorageKey&&i.clearChatHistoryStorageKey!==yu)try{localStorage.removeItem(i.clearChatHistoryStorageKey),i.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${i.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let e=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(e),fe?.clear&&Ec(()=>fe.clear(),`[AgentWidget] Failed to clear storage adapter:`),pe={},ze.syncFromMetadata(),Mr?.clearAttachments(),Lc(),ni(void 0),Zr(void 0),Cs(),St?.clear(),wt?.reset(),Xt?.update()},setMessage(e){return!H||Q.isStreaming()||cu()?!1:(!F&&it()&&ou(!0,`system`),H.value=e,H.dispatchEvent(new Event(`input`,{bubbles:!0})),!0)},submitMessage(e){if(Q.isStreaming()||gu())return!1;let t=e?.trim()||H.value.trim();return t?(!F&&it()&&ou(!0,`system`),H.value=``,H.style.height=`auto`,Ir(),Ef(t,{consumeDraft:!1}),!0):!1},getComposerState(){return J.getState()},setQuote(e){let t=e?.text?.trim();t&&Zr({...e,text:t})},clearQuote(){Zr(void 0)},startVoiceRecognition(){return Q.isStreaming()?!1:Cn(i.voiceRecognition?.provider)?(Q.isVoiceActive()||Q.isBargeInActive()||(!F&&it()&&ou(!0,`system`),$.manuallyDeactivated=!1,vc(),Q.toggleVoice().then(()=>{$.active=mc(),vc(),gc(`user`),$.active&&op()})),!0):Bf?!0:tp()?(!F&&it()&&ou(!0,`system`),$.manuallyDeactivated=!1,vc(),np(`user`),!0):!1},stopVoiceRecognition(){return Cn(i.voiceRecognition?.provider)?!Q.isVoiceActive()&&!Q.isBargeInActive()?!1:((Q.isBargeInActive()?Q.deactivateBargeIn():Q.toggleVoice()).then(()=>{$.active=!1,$.manuallyDeactivated=!0,vc(),gc(`user`),lp()}),!0):Bf?($.manuallyDeactivated=!0,vc(),rp(`user`),!0):!1},injectMessage(e){return!F&&it()&&ou(!0,`system`),Q.injectMessage(e)},injectAssistantMessage(e){!F&&it()&&ou(!0,`system`);let t=Q.injectAssistantMessage(e);return at&&(at=!1,ot&&=(clearTimeout(ot),null),setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)),t},injectUserMessage(e){return!F&&it()&&ou(!0,`system`),Q.injectUserMessage(e)},injectSystemMessage(e){return!F&&it()&&ou(!0,`system`),Q.injectSystemMessage(e)},injectMessageBatch(e){return!F&&it()&&ou(!0,`system`),Q.injectMessageBatch(e)},injectComponentDirective(e){return!F&&it()&&ou(!0,`system`),Q.injectComponentDirective(e)},injectTestMessage(e){!F&&it()&&ou(!0,`system`),Q.injectTestEvent(e)},async connectStream(e,t){return Q.connectStream(e,t)},__pushEventStreamEvent(e){ft&&(an(),rn(e.type,e.payload))},showEventStream(){ft&&ui()},hideEventStream(){Qt&&di()},isEventStreamVisible(){return Qt},listConversations(e){return Q.listConversations(e)},getActiveConversationId(){return Q.getActiveConversationId()},openConversation(e,t){return Xd(n=>n.openHistoryConversation(e,{focusComposer:t?.focus===!0}))},startNewConversation(e){return Xd(t=>t.startNewConversation({focusComposer:e?.focus===!0}))},warmSession(){Qd()},deleteConversation(e){return Xd(t=>t.deleteHistoryConversation(e))},renameConversation(e,t){return Xd(n=>n.updateHistoryConversation(e,{title:t}))},setConversationStarred(e,t){return Xd(n=>n.updateHistoryConversation(e,{starred:t}))},clearConversationHistory(e){return Xd(t=>t.clearConversationHistory(e))},resetHistoryIdentity(){return Xd(e=>e.resetHistoryIdentity())},async getVisitorToken(){let e=md;if(!e)return null;let t=await e.get();return e===md?t:null},getHistoryIdentityStatus(){let e=Fd?.historyProvider;return e?e.getIdentityStatus():zd()?{state:`unavailable`,reason:`ineligible_mode`}:{state:`unavailable`,reason:`history_disabled`}},showHistory(e){return zd()?Xd(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...e?.focus===void 0?{}:{focus:e.focus}})):Promise.resolve()},hideHistory(e){Fd?.closeHistory(e?.restoreFocus===void 0?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible(){return on},showArtifacts(){Wc(i)&&(Sa=!1,Ea=!0,vo(),X?.setMobileOpen(!0))},hideArtifacts(){Wc(i)&&(Sa=!0,vo())},upsertArtifact(e){return Wc(i)?(rt(i.features?.artifacts,{artifactType:e.artifactType,...e.artifactType===`markdown`&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})===`panel`&&(Sa=!1,Ea=!0),Q.upsertArtifact(e)):null},selectArtifact(e){Wc(i)&&Q.selectArtifact(e)},clearArtifacts(){Wc(i)&&Q.clearArtifacts()},getArtifacts(){return Q?.getArtifacts()??[]},getSelectedArtifactId(){return Q?.getSelectedArtifactId()??null},focusInput(){return Be&&!F&&!P()||!H?!1:(H.focus(),!0)},async resolveApproval(e,t,n){let r=Q.getMessages().find(t=>t.variant===`approval`&&t.approval?.id===e);if(!r?.approval)throw Error(`Approval not found: ${e}`);if(v(r.approval))Q.resolveWebMcpApproval(r.id,t);else return Q.resolveApproval(r.approval,t,n)},setFollowUpSuggestions(e){ps(e)},clearFollowUpSuggestions(){fs()},getMessages(){return Q.getMessages()},getStatus(){return Q.getStatus()},getPersistentMetadata(){return{...pe}},updatePersistentMetadata(e){Ne(e)},on(e,t){return O.on(e,t)},off(e,t){O.off(e,t)},isOpen(){return it()&&F},isVoiceActive(){return $.active},toggleReadAloud(e){Q.toggleReadAloud(e)},stopReadAloud(){Q.stopSpeaking()},getReadAloudState(e){return Q.getReadAloudState(e)},onReadAloudChange(e){return Q.onReadAloudChange(e)},getState(){return{open:it()&&F,launcherEnabled:Be,voiceActive:$.active,streaming:Q.isStreaming()}},showCSATFeedback(e){!F&&it()&&ou(!0,`system`);let t=V.querySelector(`.persona-feedback-container`);t&&t.remove();let n=_u({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitCSATFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});V.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},showNPSFeedback(e){!F&&it()&&ou(!0,`system`);let t=V.querySelector(`.persona-feedback-container`);t&&t.remove();let n=vu({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitNPSFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});V.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},async submitCSATFeedback(e,t){return Q.submitCSATFeedback(e,t)},async submitNPSFeedback(e,t){return Q.submitNPSFeedback(e,t)},destroy(){jd(),vd!=null&&(clearInterval(vd),vd=null),c.clear(),o.clear(),s.clear(),l.clear(),Z.forEach(e=>e()),I.remove(),vn?.remove(),wp?.destroy(),Tp?.remove(),Qo&&G.removeEventListener(`click`,Qo)}};if(((r?.debugTools??!1)||i.debug)&&typeof window<`u`){let e=window.AgentWidgetBrowser,t={controller:sm,getMessages:sm.getMessages,getStatus:sm.getStatus,getMetadata:sm.getPersistentMetadata,updateMetadata:sm.updatePersistentMetadata,clearHistory:()=>sm.clearChat(),setVoiceActive:e=>e?sm.startVoiceRecognition():sm.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Z.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<`u`){let e=t.getAttribute(`data-persona-instance`)||t.id||`persona-`+Math.random().toString(36).slice(2,8),n=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.focusInput()};if(window.addEventListener(`persona:focusInput`,n),Z.push(()=>{window.removeEventListener(`persona:focusInput`,n)}),ft){let t=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.showEventStream()},n=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.hideEventStream()};window.addEventListener(`persona:showEventStream`,t),window.addEventListener(`persona:hideEventStream`,n),Z.push(()=>{window.removeEventListener(`persona:showEventStream`,t),window.removeEventListener(`persona:hideEventStream`,n)})}let r=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.showHistory()},i=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.hideHistory()};window.addEventListener(`persona:showHistory`,r),window.addEventListener(`persona:hideHistory`,i),Z.push(()=>{window.removeEventListener(`persona:showHistory`,r),window.removeEventListener(`persona:hideHistory`,i)});let a=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.showArtifacts()},o=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.hideArtifacts()},s=t=>{let n=t.detail;n?.instanceId&&n.instanceId!==e||n?.artifact&&sm.upsertArtifact(n.artifact)},c=t=>{let n=t.detail;n?.instanceId&&n.instanceId!==e||typeof n?.id==`string`&&sm.selectArtifact(n.id)},l=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.clearArtifacts()};window.addEventListener(`persona:showArtifacts`,a),window.addEventListener(`persona:hideArtifacts`,o),window.addEventListener(`persona:upsertArtifact`,s),window.addEventListener(`persona:selectArtifact`,c),window.addEventListener(`persona:clearArtifacts`,l),Z.push(()=>{window.removeEventListener(`persona:showArtifacts`,a),window.removeEventListener(`persona:hideArtifacts`,o),window.removeEventListener(`persona:upsertArtifact`,s),window.removeEventListener(`persona:selectArtifact`,c),window.removeEventListener(`persona:clearArtifacts`,l)})}let cm=Tu(i.persistState);if(cm&&it()){let e=Eu(cm.storage),n=`${cm.keyPrefix}widget-open`,r=`${cm.keyPrefix}widget-voice`,i=`${cm.keyPrefix}widget-voice-mode`;if(e){let a=cm.persist?.openState&&e.getItem(n)===`true`,o=cm.persist?.voiceState&&e.getItem(r)===`true`,s=cm.persist?.voiceState&&e.getItem(i)===`true`;if(a&&(wp?.setPanelOpen(!0,`auto`),setTimeout(()=>{sm.open(),setTimeout(()=>{if(o||s)sm.startVoiceRecognition();else if(cm.persist?.focusInput){let e=t.querySelector(`textarea`);e&&e.focus()}},100)},0)),cm.persist?.openState&&(O.on(`widget:opened`,()=>{e.setItem(n,`true`)}),O.on(`widget:closed`,()=>{e.setItem(n,`false`)})),cm.persist?.voiceState&&(O.on(`voice:state`,t=>{e.setItem(r,t.active?`true`:`false`)}),O.on(`user:message`,t=>{e.setItem(i,t.viaVoice?`true`:`false`)})),cm.clearOnChatClear){let t=()=>{e.removeItem(n),e.removeItem(r),e.removeItem(i)},a=()=>t();window.addEventListener(`persona:clear-chat`,a),Z.push(()=>{window.removeEventListener(`persona:clear-chat`,a)})}}}if(je&&it()&&(wp?.setPanelOpen(!0,`auto`),setTimeout(()=>{sm.open()},0)),nu(),!Ds){let e=Ve(()=>{Q&&(Es++,gs.clear(),Bl(V,Q.getMessages(),lt))});Z.push(e)}ee=()=>{Q&&(Es++,gs.clear(),Bl(V,Q.getMessages(),lt))},Q.getMessages().length>0&&Ll(),oe=()=>{Q&&(Es++,gs.clear(),Bl(V,Q.getMessages(),lt))};let lm=Fe(()=>{Q&&(Es++,gs.clear(),Bl(V,Q.getMessages(),lt))});Z.push(lm);let um=Uc(()=>{Q&&(Es++,gs.clear(),Bl(V,Q.getMessages(),lt),Hc()?.updateInlineArtifactBlocks(V,xa.artifacts,{suppressTransition:!0}),vo())});return Z.push(um),sm},Pu=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let i=/^(\d+(?:\.\d+)?)%$/i.exec(n);return i?Math.max(0,t*parseFloat(i[1])/100):420},Fu=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},Iu=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},Lu=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement(`div`);r.style.cssText=`width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;`,n.appendChild(r);let i=r.offsetHeight>0;r.style.height=`100%`;let a=r.offsetHeight>0;r.remove(),i&&!a&&console.warn(`[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout.`+(t.maxHeight===!1?` The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.`:` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Ru=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className=`persona-host`,e.style.height=n?``:`100%`,e.style.display=n?``:`flex`,e.style.flexDirection=n?``:`column`,e.style.flex=n?``:`1 1 auto`,e.style.minHeight=n?``:`0`,e.style.minWidth=n?``:`0`},zu=e=>{e.style.position=``,e.style.top=``,e.style.bottom=``,e.style.left=``,e.style.right=``,e.style.zIndex=``,e.style.transform=``,e.style.pointerEvents=``},Bu=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,zu(e)},Vu=e=>{e.style.transition=``},Hu=e=>{e.style.display=``,e.style.flexDirection=``,e.style.flex=``,e.style.minHeight=``,e.style.minWidth=``,e.style.width=``,e.style.height=``,e.style.alignItems=``,e.style.transition=``,e.style.transform=``,e.style.marginLeft=``},Uu=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},Wu=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},Gu=(e,t,n,r,i)=>{i?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Ku=(e,t,n,r,i,a)=>{let o=a?t:e;i===`left`?o.firstElementChild!==r&&o.replaceChildren(r,n):o.lastElementChild!==r&&o.replaceChildren(n,r)},qu=e=>{let t=Ya(e),n=t.components?.panel,r=(e,n)=>e==null||e===``?n:Ca(t,e)??e;return{inset:r(n?.inset,la),canvasBackground:r(n?.canvasBackground,ua)}},Ju=(e,t,n,r)=>{t?(e.style.boxSizing=`border-box`,e.style.padding=n,e.style.background=r):(e.style.padding=``,e.style.background=``,e.style.boxSizing=``)},Yu=(e,t,n,r,i,a,o,s)=>{let c=Co(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;Gu(e,t,n,r,l),Ku(e,t,n,r,c.side,l),e.dataset.personaHostLayout=`docked`,e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=o?`true`:`false`,e.style.width=`100%`,e.style.maxWidth=`100%`,e.style.minWidth=`0`,e.style.height=`100%`,e.style.minHeight=`0`,e.style.position=`relative`,n.style.display=`flex`,n.style.flexDirection=`column`,n.style.minHeight=`0`,n.style.position=`relative`,i.className=`persona-host`,i.style.height=`100%`,i.style.minHeight=`0`,i.style.minWidth=`0`,i.style.display=`flex`,i.style.flexDirection=`column`,i.style.flex=`1 1 auto`;let p=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,h=a?.launcher?.mobileBreakpoint??640,g=p!=null&&p.innerWidth<=h;if(m&&g&&o)e.dataset.personaDockMobileFullscreen=`true`,e.removeAttribute(`data-persona-dock-reveal`),Hu(t),Vu(r),Bu(r),Uu(n),Wu(i,r),Ju(r,!1,``,``),e.style.display=`flex`,e.style.flexDirection=`column`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.minWidth=`0`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.position=`fixed`,r.style.inset=`0`,r.style.width=`100%`,r.style.height=`100%`,r.style.maxWidth=`100%`,r.style.minWidth=`0`,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.zIndex=String(a?.launcher?.zIndex??1e5),r.style.transform=`none`,r.style.transition=`none`,r.style.pointerEvents=`auto`,r.style.flex=`none`,l&&(t.style.display=`flex`,t.style.flexDirection=`column`,t.style.width=`100%`,t.style.height=`100%`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.flex=`1 1 auto`,t.style.alignItems=`stretch`,t.style.transform=`none`,t.style.marginLeft=`0`,t.style.transition=`none`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.maxWidth=`100%`,n.style.minWidth=`0`);else if(e.removeAttribute(`data-persona-dock-mobile-fullscreen`),Bu(r),Fu(r,c.maxHeight),Ju(r,u&&o,d,f),c.reveal===`overlay`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`overlay`,Hu(t),Vu(r),Uu(n),Wu(i,r);let a=c.animate?`transform 180ms ease`:`none`,s=c.side===`right`?`translateX(100%)`:`translateX(-100%)`,l=o?`translateX(0)`:s;r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`none`,r.style.position=`absolute`,r.style.top=`0`,r.style.bottom=`0`,r.style.width=c.width,r.style.maxWidth=c.width,r.style.minWidth=c.width,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.transition=a,r.style.transform=l,r.style.pointerEvents=o?`auto`:`none`,r.style.zIndex=`2`,c.side===`right`?(r.style.right=`0`,r.style.left=``):(r.style.left=`0`,r.style.right=``)}else if(c.reveal===`push`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`push`,Vu(r),zu(r),Wu(i,r);let a=Pu(c.width,e.clientWidth),s=Math.max(0,e.clientWidth),l=c.animate?`margin-left 180ms ease`:`none`,u=c.side===`right`?o?-a:0:o?0:-a;t.style.display=`flex`,t.style.flexDirection=`row`,t.style.flex=`0 0 auto`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.alignItems=`stretch`,t.style.height=`100%`,t.style.width=`${s+a}px`,t.style.transition=l,t.style.marginLeft=`${u}px`,t.style.transform=``,n.style.flex=`0 0 auto`,n.style.flexGrow=`0`,n.style.flexShrink=`0`,n.style.width=`${s}px`,n.style.maxWidth=`${s}px`,n.style.minWidth=`${s}px`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 auto`,r.style.flexShrink=`0`,r.style.width=c.width,r.style.minWidth=c.width,r.style.maxWidth=c.width,r.style.position=`relative`,r.style.top=``,r.style.overflow=`hidden`,r.style.transition=`none`,r.style.pointerEvents=o?`auto`:`none`}else{e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=``,Hu(t),zu(r),Uu(n),Wu(i,r);let a=c.reveal===`emerge`;a?e.dataset.personaDockReveal=`emerge`:e.removeAttribute(`data-persona-dock-reveal`);let s=o?c.width:`0px`,l=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?`, padding 180ms ease`:``}`:`none`,f=!o;if(r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 ${s}`,r.style.width=s,r.style.maxWidth=s,r.style.minWidth=s,r.style.minHeight=`0`,Iu(r,c.maxHeight),r.style.overflow=a||f?`hidden`:`visible`,r.style.transition=l,a){r.style.alignItems=c.side===`right`?`flex-start`:`flex-end`;let t=u?`calc(${Pu(c.width,e.clientWidth)}px - (2 * ${d}))`:c.width;i.style.width=t,i.style.minWidth=t,i.style.maxWidth=t,i.style.boxSizing=`border-box`}}},Xu=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return Ru(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){Ru(n,e)},destroy(){n.remove()}}},Zu=(e,t)=>{let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw Error(`Docked widget target must be attached to the DOM`);let i=e.tagName.toUpperCase();if(i===`BODY`||i===`HTML`)throw Error(`Docked widget target must be a concrete container element, not "body" or "html"`);let a=e.nextSibling,o=n.createElement(`div`),s=n.createElement(`div`),c=n.createElement(`div`),l=n.createElement(`aside`),u=n.createElement(`div`),d=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;s.dataset.personaDockRole=`push-track`,c.dataset.personaDockRole=`content`,l.dataset.personaDockRole=`panel`,u.dataset.personaDockRole=`host`,l.appendChild(u),r.insertBefore(o,e),c.appendChild(e);let f=null,p=()=>{f?.disconnect(),f=null},m=null,h=()=>{m=t?.launcher?.detachedPanel===!0?qu(t):null};h();let g=()=>{Yu(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=Qa(()=>{h(),g()}))},y=()=>{p(),Co(t).reveal===`push`&&typeof ResizeObserver<`u`&&(f=new ResizeObserver(()=>{g()}),f.observe(o))},b=!1,x=()=>{g(),y(),d&&!b&&o.dataset.personaDockMobileFullscreen!==`true`&&(b=!0,Lu(o,Co(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),Co(t).reveal===`push`?(s.appendChild(c),s.appendChild(l),o.appendChild(s)):(o.appendChild(c),o.appendChild(l)),x(),v(),{mode:`docked`,host:u,shell:o,syncWidgetState(e){let t=!e.launcherEnabled||e.open;d!==t&&(d=t,x())},updateConfig(e){t=e,(t?.launcher?.enabled??!0)===!1&&(d=!0),h(),x(),v()},destroy(){S?.removeEventListener(`resize`,C),_?.(),_=null,p(),r.isConnected&&(a&&a.parentNode===r?r.insertBefore(e,a):r.appendChild(e)),o.remove()}}},Qu=(e,t)=>xo(t)?Zu(e,t):Xu(e,t),$u={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ed=`persona-preview-shell-theme`,td={load:()=>null,save:()=>{},clear:()=>{}},nd=[`How do I get started?`,`Pricing & plans`,`Talk to support`];function rd(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function id(e){return e===`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 ad(e){let t=id(e);return`* { box-sizing: border-box; }
|
|
123
123
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
124
124
|
html { color-scheme: ${e}; }
|
|
125
125
|
body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
|
|
@@ -143,7 +143,7 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
143
143
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
144
144
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
145
145
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
|
|
146
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
146
|
+
.preview-workspace-card.short { height: 96px; }`}function od(e,t){let n=e.contentDocument;if(!n?.documentElement)return;let r=n.getElementById(ed);r||(r=n.createElement(`style`),r.id=ed,n.head.appendChild(r)),r.textContent=ad(t)}function sd(e,t,n,r){let i=`
|
|
147
147
|
|
|
148
148
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
149
149
|
<div class="preview-iframe-chrome">
|
|
@@ -196,16 +196,16 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
196
196
|
<head>
|
|
197
197
|
<meta charset="UTF-8">
|
|
198
198
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
199
|
-
<link rel="stylesheet" href="${
|
|
200
|
-
<style id="${
|
|
199
|
+
<link rel="stylesheet" href="${rd(r)}">
|
|
200
|
+
<style id="${ed}">${ad(t)}</style>
|
|
201
201
|
</head>
|
|
202
202
|
<body>
|
|
203
203
|
${n?a:i}
|
|
204
204
|
</body>
|
|
205
|
-
</html>`}const
|
|
206
|
-
${c?`<div class="preview-frame-meta"><span class="preview-frame-label">${
|
|
205
|
+
</html>`}const cd=()=>[{id:`preview-adv-1`,role:`user`,content:`Can you create the product and gather the docs?`,createdAt:(/* @__PURE__ */ new Date(Date.now()-18e4)).toISOString()},{id:`preview-adv-2`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ 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:(/* @__PURE__ */ 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:(/* @__PURE__ */ 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:(/* @__PURE__ */ new Date(Date.now()-3e4)).toISOString()}],ld=e=>!!(e?.features?.toolCallDisplay?.activePreview||e?.features?.toolCallDisplay?.grouped||e?.features?.toolCallDisplay?.collapsedMode&&e.features.toolCallDisplay.collapsedMode!==`tool-call`||e?.features?.reasoningDisplay?.activePreview);function ud(e,t,n=[]){if(e===`follow-ups`){let e=Date.now();return[{id:`preview-follow-up-user`,role:`user`,content:`What can Persona help me build?`,createdAt:(/* @__PURE__ */ new Date(e-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:(/* @__PURE__ */ new Date(e-6e4)).toISOString()},{id:`preview-follow-up-suggestions`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date(e-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 e===`home`?[]:e===`minimized`?[{id:`preview-min-1`,role:`assistant`,content:`We are here whenever you are ready.`,createdAt:(/* @__PURE__ */ new Date()).toISOString()}]:e===`artifact`?[{id:`preview-art-1`,role:`user`,content:`Can you draft a quick overview of the project?`,createdAt:(/* @__PURE__ */ new Date(Date.now()-12e4)).toISOString()},{id:`preview-art-2`,role:`assistant`,content:`Here’s a project overview document for you.`,createdAt:(/* @__PURE__ */ new Date(Date.now()-6e4)).toISOString()}]:e===`conversation`&&ld(t)?[...cd(),...n]:[{id:`preview-conv-1`,role:`assistant`,content:`Hello! How can I help you today?`,createdAt:(/* @__PURE__ */ new Date(Date.now()-18e4)).toISOString()},{id:`preview-conv-2`,role:`user`,content:`I want to customize the theme editor preview.`,createdAt:(/* @__PURE__ */ 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’s possible, then adjust colors and tokens to match your brand.`,createdAt:(/* @__PURE__ */ new Date(Date.now()-6e4)).toISOString()},...n]}function dd(e,t,n=[]){let r={...e.launcher,enabled:!0,autoExpand:t!==`minimized`},i={...e,launcher:r,suggestionChips:t===`home`?e.suggestionChips?.length?e.suggestionChips:nd:e.suggestionChips,initialMessages:ud(t,e,n),storageAdapter:td};return t===`artifact`&&(i.features={...i.features,artifacts:{...i.features?.artifacts,enabled:!0}}),t===`messages`&&(i.features={...i.features,history:{presentation:`panel`,...i.features?.history,enabled:!0}}),i}function fd(e,t){let n=re(e.config),r=e.config?.future,i=e.theme?Oa(e.theme,{validate:!1,future:r}):Oa(void 0,{future:r});return{...n,...e.config,theme:i,darkTheme:e.darkTheme,colorScheme:t??e.config?.colorScheme??`light`}}function pd(e,t){let n=e.scene??`conversation`;return dd(fd(e,t),n,e.appendedMessages??[])}function md(e){let t=e.compareMode??`off`,n=e.shellMode??`light`;return t===`themes`?[{mountId:`preview-light`,label:`Light`,config:pd(e,`light`),shellMode:`light`},{mountId:`preview-dark`,label:`Dark`,config:pd(e,`dark`),shellMode:`dark`}]:t===`baseline`&&(e.baselineConfig||e.baselineTheme)?[{mountId:`preview-baseline`,label:`Baseline`,config:pd({...e,config:e.baselineConfig??e.config,theme:e.baselineTheme??e.theme,darkTheme:e.baselineDarkTheme??e.darkTheme},n),shellMode:n},{mountId:`preview-current`,label:`Current`,config:pd(e,n),shellMode:n}]:[{mountId:`preview-current`,label:`Current`,config:pd(e,n),shellMode:n}]}function hd(e,t){let n={...t},r=[],i=[],a=null,o=!1,s=1,c=1,l=0;function u(){return n.device??`desktop`}function d(){return n.zoom??s}function f(){let t=getComputedStyle(e),r=parseFloat(t.paddingLeft)+parseFloat(t.paddingRight),i=parseFloat(t.paddingTop)+parseFloat(t.paddingBottom),a=(n.compareMode??`off`)!==`off`,o=(e.clientWidth-r-40)/(a?2:1),s=e.clientHeight-i-40;if(o<=0||s<=0)return 1;let c=$u[u()]??$u.desktop;return Math.min(o/c.w,s/c.h,1)}function p(){s=f();let t=Math.max(.15,Math.min(1.5,d()));c=t;let r=Array.from(e.querySelectorAll(`.preview-iframe-wrapper`));for(let e of r){let n=e.dataset.device??`desktop`,r=$u[n]??$u.desktop;e.style.width=`${r.w*t}px`,e.style.height=`${r.h*t}px`,n===`mobile`&&(e.style.borderRadius=`${32*t}px`);let i=e.querySelector(`iframe`);i&&(i.style.width=`${r.w}px`,i.style.height=`${r.h}px`,i.style.transformOrigin=`top left`,i.style.transition=`none`,i.style.transform=`scale(${t})`)}n.onScaleChange?.(t)}function m(){n.onBeforeDestroy?.();for(let e of r)e.destroy();for(let e of i)e();r=[],i=[]}function h(){return Array.from(e.querySelectorAll(`iframe[data-mount-id]`))}function g(){if(o)return;m();let t=++l,a=md(n),s=u(),c=(n.compareMode??`off`)!==`off`,d=(n.scene??`conversation`)===`minimized`,f=n.widgetCssPath??`/widget-dist/widget.css`,g=n.buildSrcdoc??sd,_=s===`mobile`?`preview-iframe-wrapper preview-iframe-wrapper-mobile`:`preview-iframe-wrapper`,v=e=>`<div class="${_}" data-mount-id="${e.mountId}" data-device="${s}" data-shell-mode="${e.shellMode}">
|
|
206
|
+
${c?`<div class="preview-frame-meta"><span class="preview-frame-label">${rd(e.label)}</span></div>`:``}
|
|
207
207
|
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${e.mountId}"></iframe>
|
|
208
|
-
</div>`,y=c?`<div class="preview-compare-grid">${a.map(e=>`<div class="preview-compare-cell">${v(e)}</div>`).join(``)}</div>`:`<div class="preview-single">${v(a[0])}</div>`;n.morphContainer?n.morphContainer(e,y):e.innerHTML=y,p();let b=h(),x=0,S=b.length,C=()=>{if(o||t!==l)return;for(let e of b){let t=e.dataset.mountId;if(!t||!e.contentDocument)continue;let n=a.find(e=>e.mountId===t);if(!n)continue;let o=()=>{},s=
|
|
208
|
+
</div>`,y=c?`<div class="preview-compare-grid">${a.map(e=>`<div class="preview-compare-cell">${v(e)}</div>`).join(``)}</div>`:`<div class="preview-single">${v(a[0])}</div>`;n.morphContainer?n.morphContainer(e,y):e.innerHTML=y,p();let b=h(),x=0,S=b.length,C=()=>{if(o||t!==l)return;for(let e of b){let t=e.dataset.mountId;if(!t||!e.contentDocument)continue;let n=a.find(e=>e.mountId===t);if(!n)continue;let o=()=>{},s=xo(n.config),c=s?(()=>{let r=e.contentDocument?.getElementById(`preview-content-${t}`);if(!r)return null;let i=Qu(r,n.config),a=e.contentDocument.createElement(`div`);a.id=t,a.style.height=`100%`,a.style.display=`flex`,a.style.flexDirection=`column`,a.style.flex=`1`,a.style.minHeight=`0`,i.host.appendChild(a);let s=()=>i.syncWidgetState(l.getState()),c=o;return o=()=>{i.destroy(),c()},a.__syncDock=s,a.__hostLayout=i,a})():e.contentDocument.getElementById(t);if(!c)continue;let l=Nu(c,n.config);if(r.push(l),s&&c.__syncDock){let e=c.__syncDock,t=l.on(`widget:opened`,e),n=l.on(`widget:closed`,e),r=o;o=()=>{t(),n(),r()},e()}i.push(o),d&&l.close()}let e=n.scene??`conversation`;if(e===`messages`)for(let e of r)e.showHistory({focus:!1});if(e===`artifact`||n.config?.features?.artifacts?.enabled)for(let e of r)e.upsertArtifact({id:`preview-sample`,artifactType:`markdown`,title:`Sample Document`,content:`# Sample Artifact
|
|
209
209
|
|
|
210
210
|
This is a preview of the artifact sidebar.
|
|
211
211
|
|
|
@@ -213,4 +213,4 @@ This is a preview of the artifact sidebar.
|
|
|
213
213
|
|
|
214
214
|
- Markdown rendering
|
|
215
215
|
- Document toolbar
|
|
216
|
-
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:b,controllers:[...r]})};for(let e of b){let t=e.dataset.mountId;if(!t)continue;let n=a.find(e=>e.mountId===t);n&&(e.addEventListener(`load`,()=>{x++,x>=S&&C()},{once:!0}),e.srcdoc=g(t,n.shellMode,
|
|
216
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:b,controllers:[...r]})};for(let e of b){let t=e.dataset.mountId;if(!t)continue;let n=a.find(e=>e.mountId===t);n&&(e.addEventListener(`load`,()=>{x++,x>=S&&C()},{once:!0}),e.srcdoc=g(t,n.shellMode,xo(n.config),f))}S===0&&C()}function _(){if(o)return;let t=md(n);if(r.length!==t.length)g();else if(t.some(t=>{let n=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${t.mountId}"]`);return!n||n.dataset.shellMode!==t.shellMode}))g();else{r.forEach((e,r)=>{e.update(t[r].config),(n.scene??`conversation`)===`minimized`&&e.close()});for(let n of t){let t=e.querySelector(`iframe[data-mount-id="${n.mountId}"]`);t&&od(t,n.shellMode)}n.onAfterUpdate?.({iframes:h(),controllers:[...r]})}}return typeof ResizeObserver<`u`&&(a=new ResizeObserver(()=>{o||p()}),a.observe(e)),g(),{update(e){if(o)return;let t=e.device!==void 0&&e.device!==n.device||e.scene!==void 0&&e.scene!==n.scene||e.compareMode!==void 0&&e.compareMode!==n.compareMode||e.widgetCssPath!==void 0&&e.widgetCssPath!==n.widgetCssPath;n={...n,...e},t?g():_()},destroy(){o||(o=!0,m(),a?.disconnect(),e.innerHTML=``)},getControllers(){return[...r]},fitToContainer(){o||(n={...n,zoom:void 0},p())},getIframes(){return h()},getScale(){return c},setZoom(e){o||(n={...n,zoom:e},p())}}}export{hd as createThemePreview};
|