@runtypelabs/persona 4.29.0 → 4.29.2
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-B2HCRERn.js +9 -0
- package/dist/chunk-Bm2-bemv.js +1 -0
- package/dist/chunk-BvhTpG6k.js +1 -0
- package/dist/{chunk-DjOvgFsn.js → chunk-Car1mORT.js} +1 -1
- package/dist/chunk-D5B629Mj.js +1 -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-DrpuvY5W.js +1 -0
- package/dist/{chunk-dRBlrLd7.js → chunk-DtmtfIkd.js} +1 -1
- 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-D3sB8_P_.d.cts → composer-input-C3Xh1Qzj.d.cts} +1 -1
- package/dist/{composer-input-D3sB8_P_.d.ts → composer-input-C3Xh1Qzj.d.ts} +1 -1
- package/dist/{context-mention-manager-D2qxE5op.d.cts → context-mention-manager-BsEiGObk.d.cts} +1 -1
- package/dist/{context-mention-manager-D2qxE5op.d.ts → context-mention-manager-BsEiGObk.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-Dsw66XqE.d.cts → defaults-DN-L67ak.d.cts} +1 -1
- package/dist/{defaults-Dsw66XqE.d.ts → defaults-DN-L67ak.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-DJpJcWAk.d.cts → fallback-speech-engine-Cph8FTux.d.cts} +1 -1
- package/dist/{fallback-speech-engine-DJpJcWAk.d.ts → fallback-speech-engine-Cph8FTux.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 +56 -56
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.global.js +2 -3
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +42 -42
- package/dist/index.js.map +1 -1
- package/dist/{markdown-parsers-loader-CCY7T4Up.d.cts → markdown-parsers-loader-C4Xze-Jw.d.cts} +1 -1
- package/dist/{markdown-parsers-loader-CCY7T4Up.d.ts → markdown-parsers-loader-C4Xze-Jw.d.ts} +1 -1
- package/dist/{preview-DKKpfTo7.d.cts → preview-m9QlqsZi.d.cts} +2 -2
- package/dist/{preview-DKKpfTo7.d.ts → preview-m9QlqsZi.d.ts} +2 -2
- package/dist/{session-DleMr9dZ.d.ts → session-BtvvmWnw.d.cts} +21 -9
- package/dist/{session-DleMr9dZ.d.cts → session-BtvvmWnw.d.ts} +21 -9
- package/dist/session-actions.js +1 -1
- 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 +62 -62
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +41 -41
- 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-oAZ1VReS.d.cts → types-DL-oBHE1.d.cts} +41 -3
- package/dist/{types-oAZ1VReS.d.ts → types-DL-oBHE1.d.ts} +41 -3
- package/dist/voice-client-tools.d.cts +1 -1
- package/dist/voice-client-tools.d.ts +1 -1
- package/dist/voice-runtime.cjs +3 -3
- package/dist/voice-runtime.d.cts +10 -4
- package/dist/voice-runtime.d.ts +10 -4
- 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-Deg0NfmB.d.cts → webmcp-runtime-entry-T6SU_TlL.d.cts} +1 -1
- package/dist/{webmcp-runtime-entry-Deg0NfmB.d.ts → webmcp-runtime-entry-T6SU_TlL.d.ts} +1 -1
- package/dist/webmcp-runtime.d.cts +1 -1
- package/dist/webmcp-runtime.d.ts +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -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 +24 -4
- 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 +7 -1
- 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 +23 -0
- package/src/session.ts +211 -46
- package/src/session.voice.test.ts +169 -0
- package/src/styles/widget.css +4 -2
- package/src/types.ts +37 -2
- package/src/ui.restored-browser-tools.test.ts +128 -0
- package/src/ui.scroll.test.ts +7 -2
- package/src/ui.stream-replay.test.ts +86 -0
- package/src/ui.streaming-coalescing.test.ts +183 -0
- package/src/ui.ts +152 -124
- package/src/ui.typing-indicator.test.ts +21 -0
- 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/message-fingerprint.test.ts +9 -0
- package/src/utils/message-fingerprint.ts +18 -5
- package/src/utils/morph.ts +10 -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 +13 -8
- package/src/voice/session-voice-wiring.ts +1 -2
- package/src/voice/voice-delegation.ts +10 -3
- package/src/voice/voice.test.ts +38 -2
- package/dist/chunk-B6zZsT6F.js +0 -1
- package/dist/chunk-CIVsNcrk.js +0 -1
- package/dist/chunk-CKdlNyzM.js +0 -9
- package/dist/chunk-DbhxjyOB.js +0 -4
- package/dist/chunk-DsdqLStH.js +0 -1
- package/dist/chunk-GIqbL2Eg.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-CIVsNcrk.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-BkW8s3fj.js`)}),In=Fn,{setLoader:W,load:Ln}=me({fallbackImport:()=>import(`./chunk-lA5CJCgK.js`)}),Rn=Ln;function zn(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function Bn(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=zn(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=zn(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 G(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Vn(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Hn(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}const Un=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),Wn=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Gn=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=Un(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:Wn(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},K=(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=Gn(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:Kn,load:qn,provide:Jn}=me({fallbackImport:()=>import(`./chunk-DjOvgFsn.js`)}),Yn=qn;var Xn=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const Zn=e=>`reason`in e?e.reason:void 0,Qn=(e,t)=>e instanceof Xn&&e.code===t,$n=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),er=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),tr=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function nr(e){switch(e){case`json`:return Be;case`regex-json`:return ke;case`xml`:return Re;default:return Fe}}var rr=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??nr(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}getVoiceClientTools(){if(this.config.webmcp?.enabled!==!0)return null;let e=()=>this.#S(),t={open:async e=>(await Rn()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:Pe(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=Bn(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 Xn(`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 Yn();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await Yn()).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&&Zn(t)===Zn(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 Xn(`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 Xn(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new Xn(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new Xn(`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(!Qn(n,`not_found`)&&!Qn(n,`visitor_required`)&&!Qn(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 Xn(`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 Xn(`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:Xn,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 Yn()).listConversations(this.#G(),e)}async getConversation(e,t){return(await Yn()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await Yn()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await Yn()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await Yn()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await Yn()).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=Hn();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($n).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 Xn(`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 Xn(`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 Xn)&&!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=K(er(e),e=>$n(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?tr(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=K(er(e),e=>$n(e)?tr(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:ir,load:ar,provide:or,getSync:sr}=me({fallbackImport:()=>import(`./chunk-U_UTkSiO.js`)}),cr=ar,lr=sr,{setLoader:ur,load:dr,provide:fr,getSync:pr}=me({fallbackImport:()=>import(`./chunk-DsdqLStH.js`)}),mr=dr,hr=pr,gr=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function _r(e){let t=e?.text?.trim()??``;return t?yt(gr(e),t):``}function vr(e){let t=_r(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 O,N as ee,O as te,P as ne,R as re,S as ie,T as ae,U as oe,V as k,W as se,_ as ce,a as A,b as le,c as ue,d as j,f as de,g as fe,h as pe,i as me,j as he,k as ge,l as _e,m as ve,n as ye,o as be,p as xe,r as Se,s as Ce,t as we,u as Te,v as Ee,w as De,x as Oe,y as ke,z as Ae}from"./chunk-BIhTjsVQ.js";import{i as je,r as M,t as N}from"./chunk-D5BxWOFB.js";import{a as Me,n as P,r as Ne,t as Pe}from"./chunk-BypiAEpx.js";import{c as Fe,d as Ie,f as Le,i as Re,l as ze,m as Be,n as Ve,p as He,r as Ue,t as We,u as Ge}from"./chunk-SE7Q9NmG.js";import{n as Ke,r as qe,t as Je}from"./chunk-BvhTpG6k.js";import{f as Ye,r as Xe,s as Ze,u as Qe}from"./chunk-CD4-AYdH.js";import{a as $e,i as et,r as tt}from"./chunk-CfNME4R9.js";import{a as F,i as nt,n as rt,r as I,t as it}from"./chunk-CPdEltCR.js";import{t as at}from"./chunk-DrpuvY5W.js";import{a as ot,c as st,d as ct,l as lt,n as ut,o as dt,t as ft,u as pt}from"./chunk-BlTD-Wgn.js";import{a as mt,n as ht,r as gt,s as _t,t as vt}from"./chunk-DpyghsEW.js";import{n as yt}from"./chunk-DTDHeUsG.js";import{i as bt,n as xt}from"./chunk-Bb41bKyp.js";import{t as St}from"./chunk-C8560fIY.js";import{i as Ct,n as wt,r as Tt,t as Et}from"./chunk-lwPt6bL9.js";import{t as Dt}from"./chunk-CQw6A6rt.js";import{n as Ot}from"./chunk-py2YB6PV.js";import{a as kt,c as At,i as jt,l as Mt,n as Nt,o as Pt,r as Ft,s as It,t as Lt}from"./chunk-CVMIncEY.js";import{a as Rt,c as zt,i as Bt,l as Vt,n as Ht,o as Ut,r as Wt,s as Gt,t as Kt,u as qt}from"./chunk-BExOAPZb.js";import{Activity as Jt,ArrowRight as Yt,Check as Xt,ChevronDown as Zt,ChevronUp as Qt,Circle as $t,Clock as en,Copy as tn,File as nn,FileCode as rn,FileSpreadsheet as an,FileText as on,MessageSquare as sn,X as cn}from"lucide";import"partial-json";import{Idiomorph as ln}from"idiomorph";const un=[`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`],dn=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),fn=(e,t)=>{let n=N(`div`,[`persona-message-bubble`,e,...un].join(` `));return n.id=`bubble-${t}`,n.setAttribute(`data-message-id`,t),n},pn=e=>{let t=N(`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},mn=(e,t,n)=>{e.innerHTML=``;let r=b(t?Qt:Zt,16,n,2);r?e.appendChild(r):e.textContent=t?`Hide`:`Show`},hn=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let r=N(`div`,`persona-flex persona-items-center`);mn(r,n.expanded,n.iconColor);let i=N(`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},gn=e=>{let t=N(`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?.();dn(t,n)||(t.textContent=e.previewText),t.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},L=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&mn(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`},R=(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&&mn(s,r,n.iconColor),a.style.display=r?``:`none`,o&&(o.style.display=r?`none`:o.textContent||o.childNodes.length?``:`none`)};function _n(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[n]:{...t===`tool`?O:he,...e?.future?.v5Defaults===!0?te.features?.[n]:{},...e?.features?.[n]}}}}function vn(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[n]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function yn(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 z(e,t,n,r){if(vn(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=N(`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?P(d,16,`currentColor`,2):c===`pending`?b($t,16,`currentColor`,2):c===`awaiting-approval`?b(en,16,`currentColor`,2):P(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=N(`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?``:yn(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 bn(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 xn(e,t,n,r){let i=N(`div`,``);i.id=`bubble-${e.id}`,i.dataset.messageId=e.id;let a=N(`button`,``);a.type=`button`,a.dataset.expandHeader=`true`,a.dataset.bubbleType=`tool`,a.setAttribute(`aria-expanded`,String(n));let o=N(`div`,``);typeof r==`string`?o.textContent=r:o.appendChild(r),hn(a,o,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||`currentColor`,metaGap:!0});let s=N(`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),z(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 B(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 V=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function H(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:V()}catch{return!1}}const Cn=/^\s*\|?[\s:|-]*-[\s:|-]*$/,wn=e=>e.includes(`|`),Tn=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())},U=e=>`| ${e.join(` | `)} |`,W=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,En=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),G=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(!wn(r)||Cn.test(r)||!Cn.test(i))continue;let a=Tn(r).length;if(a<1)continue;let o=W(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()===``||!wn(e))break;let r=U(En(Tn(e),a));t[s]!==r&&(t[s]=r,n=!0)}e=s-1}return n?t.join(`
|
|
3
|
+
`):e},Dn=`var(--persona-md-table-scroll-fade, 24px)`,On=/* @__PURE__ */ new WeakSet;function kn(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 An(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`:Dn),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:Dn)}function jn(e){On.has(e)||(On.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&An(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(An)}const{setLoader:Mn,load:Nn,provide:Pn,getSync:K}=Me({fallbackImport:()=>import(`./chunk-B1-_pp-Y.js`)}),Fn=Nn,In=K,{setLoader:Ln,load:Rn}=Me({fallbackImport:()=>import(`./chunk-BkW8s3fj.js`)}),zn=Rn,{setLoader:q,load:Bn}=Me({fallbackImport:()=>import(`./chunk-lA5CJCgK.js`)}),Vn=Bn;function Hn(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function Un(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=Hn(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=Hn(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 Wn=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),J=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Gn=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=Wn(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:J(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},Kn=(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=Gn(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:qn,load:Jn,provide:Yn}=Me({fallbackImport:()=>import(`./chunk-Car1mORT.js`)}),Xn=Jn;var Zn=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const Qn=e=>`reason`in e?e.reason:void 0,$n=(e,t)=>e instanceof Zn&&e.code===t,er=e=>e.voiceCaption||yt(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),tr=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),nr=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function rr(e){switch(e){case`json`:return f;case`regex-json`:return t;case`xml`:return u;default:return s}}var ir=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":at,...e.headers},this.debug=!!e.debug,this.#n=e.streamParser??rr(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 zn().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 Vn()).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=Un(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 Zn(`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":at,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await Xn();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await Xn()).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&&Qn(t)===Qn(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":at},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 Zn(`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 Zn(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new Zn(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new Zn(`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(!$n(n,`not_found`)&&!$n(n,`visitor_required`)&&!$n(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 Zn(`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 Zn(`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":at},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:Zn,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 Xn()).listConversations(this.#G(),e)}async getConversation(e,t){return(await Xn()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await Xn()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await Xn()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await Xn()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await Xn()).resetVisitor(this.#G())}async dispatch(e,t){return e.signal?.throwIfAborted(),Fn().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#q(e,t)}async#K(e,t){let n=Ke();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(er).map(e=>{let t=l?mt(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":at,...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 Zn(`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 Zn(`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 Zn)&&!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 Fn()).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 Fn()).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=Kn(tr(e),e=>er(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?nr(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=[...F(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=Kn(tr(e),e=>er(e)?nr(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=[...F(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}=In()??await Fn();return i({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#o,onSSEEvent:(e,t)=>this.#c?.(e,t)},e,t,n,r)}};const{setLoader:ar,load:or,provide:sr,getSync:cr}=Me({fallbackImport:()=>import(`./chunk-U_UTkSiO.js`)}),lr=or,ur=cr,{setLoader:dr,load:fr,provide:pr,getSync:mr}=Me({fallbackImport:()=>import(`./chunk-DjFpGFGA.js`)}),hr=fr,gr=mr,_r=e=>typeof e==`object`&&!!e&&!Array.isArray(e),vr=(e,t)=>{let n=/* @__PURE__ */ new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!_r(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=_r(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}}}]})},yr=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function br(e){let t=e?.text?.trim()??``;return t?Ct(yr(e),t):``}function xr(e){let t=br(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[ot(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
4
4
|
|
|
5
|
-
`)}:{}}function
|
|
5
|
+
`)}:{}}function Sr(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Cr(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 wr(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 Tr(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 wr(e,n.id)?n.id:null}return null}function Er(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 Dr(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 Or=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):Dr(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()}},kr=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)}},Ar=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:jr,load:Mr,getSync:Y}=Me({fallbackImport:()=>import(`./chunk-B2HCRERn.js`)}),Nr=Mr,Pr=Y;function Fr(e){if(!e)return``;let t=Ir(e);return Lr(t===null?e:t)}function Ir(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 Lr(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 J=()=>import(`./chunk-59UOGW9N.js`),{setLoader:Fr,load:Ir}=me({fallbackImport:()=>import(`./chunk-B6zZsT6F.js`)}),Lr=Ir,Rr=/* @__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 zr(e,t){return Rr.some(n=>e[n]!==t[n])}var Br=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function Vr(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 Hr=e=>We(e)||e===`suggest_replies`;var Ur=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 Dr,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Er(()=>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)&&mr().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 rr(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&&jr().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&&J().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=Tr.isSupported()?new Tr({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 J().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=jr().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 Dr,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 Br(`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 Br(`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 Br(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new Br(`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 Br(`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 Br(`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 Br(`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 Br(`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 Xn&&(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 Xn?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 Xn&&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=zr(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 rr(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`?G():t===`assistant`?Vn():`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`?G():e===`assistant`?Vn():`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 Rr=()=>import(`./chunk-59UOGW9N.js`),{setLoader:zr,load:Br}=Me({fallbackImport:()=>import(`./chunk-DO9_WSpy.js`)}),Vr=Br,Hr=/* @__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 Ur(e,t){return Hr.some(n=>e[n]!==t[n])}var Wr=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function Gr(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 Kr=e=>g(e)||e===`suggest_replies`;var qr=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 Ar,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new kr(()=>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)&&hr().catch(()=>{});let r=e.message.toolCall,i=!!r?.name&&(g(r.name)||r.name===`suggest_replies`&&$e(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.#gt(this.messages),this.client=new ir(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&&Nr().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&&Rr().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 H(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=Or.isSupported()?new Or({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 Rr().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=Nr().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(!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 Ar,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 Wr(`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 St(`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 Wr(`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 Wr(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new Wr(`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=_t(this.messages,o);this.messages=this.#gt(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 Wr(`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 Wr(`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 Wr(`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 Wr(`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=_t(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.#gt(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=mt(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=mt(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 Zn&&(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 Zn?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 Zn&&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=B(this.config,n),i=Ur(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.#We();return}this.#He(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.client=new ir(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`?qe():t===`assistant`?Je():`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`?qe():e===`assistant`?Je():`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.#gt([...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??G(),s=Vn();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=vr({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=Vr(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=br(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=Vn();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=Vr(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{}if(e.signal?.aborted)return Promise.resolve(!1);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(t=>{this.webMcpApprovalResolvers.set(n,t),e.signal?.addEventListener(`abort`,()=>this.resolveWebMcpApproval(n,`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`)}#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=hr();if(n)return e(n,t);let r=this.#Ie;return mr().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=Lr().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=>Vr(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=Vn(),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=Nr(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return wr(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=Nr(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&&Hr(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&&Hr(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 Wr={add:e=>ct(e)},Gr=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Kr={allowedTypes:lt,maxFileSize:10485760,maxFiles:4};function qr(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Jr(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 Yr=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??Kr.allowedTypes,maxFileSize:e.maxFileSize??Kr.maxFileSize,maxFiles:e.maxFiles??Kr.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:Wr}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:Kr.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:qr(),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=Gr(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=Jr(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 Xr=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Zr=(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 Qr(){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=>{Zr(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{Xr(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{Xr(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 $r=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},ei=(e,t)=>{let n=j(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function ti(e,t={}){let n=$r(e,`[data-persona-composer-form]`),r=$r(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:$r(e,`[data-persona-composer-header]`),body:$r(e,`[data-persona-composer-body]`),actionsStart:$r(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:$r(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:$r(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:$r(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:$r(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=ei(`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=ei(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=$r(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:$r(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:$r(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:$r(e,`[data-persona-composer-submit]`)??void 0,micButton:$r(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 ni=[`--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`],ri=`data-persona-menu-focus`,ii=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function ai(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const oi=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function si(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&&ai(t)===e;t.toggleAttribute(ri,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(ai).filter(e=>!oi(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(ri);e&&i.focus()}},D=(e=0,t=!1)=>{if(n||T())return;u=t,ee(i,a,ni),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(ii.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(ri);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 ci={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},li=`data-persona-composer-action`,ui=`data-persona-composer-disable-when-streaming`,di=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function fi(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 pi(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 mi=(e,t)=>{e&&typeof console<`u`&&console.warn(t)},hi=(e,t)=>t.includes(`:`)?t:`${e}:${t}`;function gi(e){let{debug:t}=e,n=[],r=/* @__PURE__ */ new Map,i=0,a=e=>{let i=r.get(e.id);i?mi(t,`[Persona] composer action "${e.id}" is already contributed by ${Y(i)}; the ${Y(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?hi(r,e.id):e.id,s=e.order??ci.custom;e.placement===`end`&&s>=ci.send&&(mi(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${ci.send-1}.`),s=ci.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 Y=e=>e.source===`plugin`?`plugin "${e.pluginId}"`:e.source===`config`?`composer.actions`:`a core built-in`,_i=(e,t,n)=>e===void 0?n:typeof e==`function`?e(t)===!0:e===!0,vi=e=>e.phase===`streaming`||e.text.trim().length>0||e.attachments.length>0;function yi(e,t){if(!e||e===`always`)return!0;let n=vi(t);return e===`when-text`?n:!n}const bi=e=>e.kind===`custom`,xi=e=>e instanceof HTMLButtonElement?e:e.querySelector(`button`)??e,Si=e=>{let t=xi(e);return t.getAttribute(`aria-label`)?.trim()||t.getAttribute(`title`)?.trim()||``};function Ci(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 wi=e=>Ci(e).length===0;function Ti(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(ui,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(li,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(li,t.id),r.element.toggleAttribute(ui,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?bi(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=si({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:a}),g),C=e=>{_!==e&&(v?.disconnect(),_=e,b=pi(e),typeof ResizeObserver<`u`&&(v=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??pi(e);n!==b&&(b=n,k())}),v.observe(e)))},w=(e,t)=>{let n=fi(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=b||pi(t);return r>0&&r<n},T=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=di(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(!wi(e.element)){e.menuLabel?.remove(),e.menuLabel=void 0;return}let n=Si(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&&!bi(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(xi(e.element)),e.menuSlot=t;let n=t=>{let n=xi(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||_i(r.visible,a,!0)&&yi(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=_i(r.disabled,a,!1)||r.disableWhenStreaming===!0&&o;h(n,e),!bi(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:ci.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=gi(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&&bi(r)!==bi(i)||r&&i&&bi(r)&&bi(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&&!bi(i)?s(n,i):i&&n.element.toggleAttribute(ui,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 Ei=[`--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`],Di=()=>({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 Oi(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}=Di();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,Ei),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}=Di();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 ki(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 Ai=e=>`core:mode:${e}`,ji=e=>Math.min(300+e,499),Mi=e=>`core:mode-group:${e}`;function Ni(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function Pi(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function Fi(e,t){return e?.length?e.filter(e=>!Ni(e.groupId,t)&&!Pi(e.groupId,t)):[]}const Ii=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function Li(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(Ii(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 Ri(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function zi(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function Bi(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}function Vi(e){let t=null;return{action:{id:Mi(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 Hi(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=yr(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 Ui(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=yr(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 Wi(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 Gi(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 Ki(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 Ji(e){return e.wrapped||e.text.includes(`
|
|
12
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function Yi(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Xi(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 Zi(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 Qi(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const $i=e=>typeof e?.then==`function`;function ea(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 ta(e,t,n){let r;try{r=e(Zi(t),{signal:n})}catch(e){return{status:`error`,error:e}}return $i(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:ea(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):ea(t,r)}const na=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),ra={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`},ia=`16px`,aa=`transparent`,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`},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`}},sa={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`}},ca={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:ia,canvasBackground:aa,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`}}},la=oa.colors.gray,ua={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},da={...oa,colors:{...oa.colors,gray:la}},fa={...oa,colors:{...oa.colors,gray:ua},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},pa=sa,ma={...sa,colors:{...sa.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...sa.typography,fontSize:`14px`,lineHeight:`1.5`}},X=ca,ha={...ca,launcher:ra,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:{...ca.input,borderRadius:`palette.radius.full`},introCard:{...ca.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...ca.suggestion.chip,fontWeight:`400`},card:{...ca.suggestion.card,fontWeight:`400`},list:{...ca.suggestion.list,fontWeight:`400`}},panel:{...ca.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...ca.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:{...ca.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...ca.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:{...ca.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},composer:{...ca.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)`}},ga=e=>a({future:e}),_a=e=>ga(e)===`v5`?{palette:fa,semantic:ma,components:ha}:{palette:da,semantic:pa,components:X};function va(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.`))?va(e,r):r}function ya(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=va(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 ba(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 xa(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)?xa(t,r):r}return n}function Sa(e,t){return t?xa(e,t):e}function Ca(e,t={}){let n=_a(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:Sa(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=ba(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 wa=e=>e.trim()===`0`?`0px`:e,Ta=`--persona-`,Ea=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},Da=(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[Ta+n],t!==void 0)break;t!==void 0&&(e[Ta+n]=t)}};function Oa(e){let t=ya(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}Da(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`],Da(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`]]),Da(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`]}`,Da(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`,Da(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`]]),Da(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`],Da(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`],Da(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)}Da(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,Da(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`]]),Da(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),Da(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`]]),Da(n,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),Da(n,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),Da(n,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),Da(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)}Da(n,[[`message-border`,`components-message-border`,`border`]]),Da(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`]=wa(t.toggleGroupGap)),t.toggleBorderRadius&&(n[`--persona-artifact-toolbar-toggle-radius`]=t.toggleBorderRadius),t.toggleGroupPadding&&(n[`--persona-artifact-toolbar-toggle-group-padding`]=wa(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`]=va(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`]=wa(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`]=va(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`]=va(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`]=va(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(n[`--persona-artifact-inline-chrome-border`]=va(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(n[`--persona-artifact-inline-title-color`]=va(e,t.titleColor)??t.titleColor),t.mutedColor&&(n[`--persona-artifact-inline-muted-color`]=va(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`]=va(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=Ea(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 ka=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),Aa=(e,t)=>{if(!t||!ka(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(Va(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:a(t)===`v5`?`400px`:`420px`}}}:e},ja={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`}}},Ma={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)`}}}},Na=ja,Pa={...Na,colors:{...Na.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`}}},Fa=Ma,Ia={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:{...Ma.components,button:{...Ma.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:{...Ma.components?.eventStream,badge:{...Ma.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`}}}}},La=e=>a({future:e})===`v5`?{palette:Pa,components:Ia}:{palette:Na,components:Fa},Ra=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},za=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,Ba=e=>{let t=e?.colorScheme??`light`;return t===`light`?`light`:t===`dark`?`dark`:za()},Va=e=>Ba(e),Ha=(e,t={})=>Ca(e,t),Ua=(e,t={})=>{let n=La(t.future),r=_(n.components,e??{})??{};return Ca({...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})},Wa=e=>{let t=Va(e),n=Ra(e?.theme),r=na(e)===`circle`?ra:{...X.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}},i=_({components:{launcher:r}},n),a=Ra(e?.darkTheme);return Aa(t===`dark`?Ua(_(i??{},a??{}),{future:e?.future}):Ha(i,{future:e?.future}),e)},Ga=e=>Oa(e),Ka=(e,t)=>{let n=Wa(t),r=Ga(n);for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute(`data-persona-color-scheme`,Va(t)),e.setAttribute(`data-persona-defaults`,a(t))},qa=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(za())});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(za());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())}},Ja=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),Ya=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,Xa=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},Za=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight),Qa=(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}}}})},$a=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),eo={index:-1,draft:``};function to(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 no(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 ro(){return/* @__PURE__ */ new Map}function io(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function ao(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function oo(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}const{setLoader:so,load:co}=me({fallbackImport:()=>import(`./chunk-Dg7uqL8l.js`)}),lo=co;function uo(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 fo=0,po=null;function mo(e=document){if(fo++,fo===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;po={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,fo=Math.max(0,fo-1),fo===0&&po)){let t=e.body,n=e.defaultView??window;t.style.overflow=po.originalOverflow,t.style.position=po.originalPosition,t.style.top=po.originalTop,t.style.width=po.originalWidth,n.scrollTo(0,po.scrollY),po=null}}}const ho={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},go=e=>(e?.launcher?.mountMode??`floating`)===`docked`,_o=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,vo=e=>{let t=e?.launcher?.dock,n=s(e).dockWidth?t?.width:va(Wa(e),`components.panel.width`);return{side:t?.side??ho.side,width:n??ho.width,animate:t?.animate??ho.animate,reveal:t?.reveal??ho.reveal,maxHeight:t?.maxHeight??ho.maxHeight}},yo=e=>e===`followUp`?`follow-up`:e,bo=(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`}},xo=/* @__PURE__ */ new WeakSet,So=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Co=e=>{So()||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`})})},wo=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},To=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`;!xo.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(xo.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(bo).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=yo(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=wo({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,Co(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})))}}},Eo={"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`},Do={x:[1.4,1.05]},Oo=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,ko=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=Do[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)},Ao=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:i,iconName:a,iconText:o,wrapperClassName:s=Oo,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||No.actionIconColor,backgroundColor:d,border:x?`${f||`0px`} solid ${p||`transparent`}`:void 0,borderRadius:m,paddingLeft:h,paddingRight:h,paddingTop:g,paddingBottom:g}});return a?ko(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}},jo=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=Oo,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=Ao({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}},Mo=(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}=Ao({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}},No={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)`},Po={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)`},Z={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)`},Fo=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:No.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:No.titleColor,...Po}}),f=A(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:No.subtitleColor,...Z}});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=Mo(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}=jo(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:_}},Io=(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))},Lo=e=>{let t=Fo({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 Ro(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=Ao({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 zo={default:Lo,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=No.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=No.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=No.titleColor,Object.assign(u.style,Po),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}=jo(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=j(`div`,`persona-flex persona-items-center persona-gap-1`);c||Ro(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=Mo(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:_}}},Bo=e=>zo[e]??zo.default,Vo=(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=Bo(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},Ho=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}},Uo=()=>{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}},Wo=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}},Go=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}},Ko=(e,t)=>{if(!e)return null;let n=Go(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},qo=(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},Jo=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},Yo=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(`:`))},Xo=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),Zo=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),Q=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),Qo=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),$o=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},es=(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},ts=(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(es(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}}},ns=(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}),Jo(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}},rs=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(!Yo(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}},is=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(!Yo(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}},as=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(!Yo(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}},os=()=>{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},ss=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:os};if(t){let e=t(r);if(e!==null)return e}return os()},cs=(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},ls=(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},us=(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},ds={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`}},fs=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=ds[n??`bubble`]??ds.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)`)},ps=e=>`custom:${e}`,ms=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),hs=(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=ms(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,ps(e.id)));return _},gs=(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=us(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=_a(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;fs(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=Xo(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?ts(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=ls(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=ns(v,!b&&!!y,()=>{b&&k&&(k.style.display=``)});e?h.appendChild(e):b&&k&&(k.style.display=``)}let ee=Zo(e);if(ee.length>0){let e=rs(ee);e&&h.appendChild(e)}let te=Q(e);if(te.length>0){let e=is(te);e&&h.appendChild(e)}let ne=Qo(e);if(ne.length>0){let e=as(ne);e&&h.appendChild(e)}let re=e.contentSegments?.length?null:$o(e.contextMentions);if(re&&h.appendChild(re),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=ls(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let ie=e.role===`assistant`?Ko(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=ss(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}ie&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild(qo(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||ms(r,`user`).length>0);if((ae||se)&&r){let t=hs(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=cs(c,e.role);return f===`right`||f===`left`&&e.role===`user`?ce.append(h,le):ce.append(le,h),ce},_s=(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}},vs=(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}},ys=(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)},bs=(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===``,_s(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`)},xs=`data-persona-welcome-overlay`,Ss=`persona-welcome-overlay-active`,Cs=/* @__PURE__ */ new WeakMap,ws=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(xs,``),e.classList.contains(Ss)||(Cs.set(e,e.scrollTop),e.classList.add(Ss),e.scrollTop=0)},Ts=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(xs),e.classList.contains(Ss)&&(e.classList.remove(Ss),e.scrollTop=Cs.get(e)??e.scrollTop,Cs.delete(e))},Es=()=>{let e=A(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},Ds=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=A(`div`,{className:us(`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},Os=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,ks=(e,t)=>{if(Os()||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},As=(e,t,n,r=260)=>{if(t<=1||Os()||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`})},js=/* @__PURE__ */ new WeakSet,Ms=(e,t)=>!!e&&e[t]!==void 0,Ns=(e,t)=>{e&&e.debug===!0&&t.length&&(js.has(e)||(js.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},Ps=(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=Ms(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:Ms(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];Ms(n,`title`)&&Ms(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),Ms(n,`subtitle`)&&Ms(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),Ms(n,`variant`)&&Ms(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&Ms(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`&&Ms(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=Xa(n?.anchorComposerTop)!==null;return Ms(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(Ms(n,`anchorComposerTop`)||Ms(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),Ns(e,c),{title:Ms(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:Ms(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`}},Fs=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,Is=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`),Ls=`var(--persona-components-panel-height)`,Rs=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, ${Ls})`:`max(200px, calc(${Ls} - ${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)`}},zs=`16px`,Bs=`10px`,Vs=`14px`,Hs=e=>{let t=e?.launcher?.enabled??!0,n=go(e);if(_o(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?Rs(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&&Eo[r.position]?Eo[r.position]:Eo[`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=Rs(e);return o.style.width=c.width,o.style.maxWidth=c.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},Us=e=>{let t=A(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":yo(e)}});return t.hidden=!0,t},Ws=(e,t)=>{let n=Us(`starter`),r=vs(e,n,{flatShadow:go(e)}),i=Ps(e);bs(r,i),ys(t,r.host,Is(i,e?.initialMessages));let a=Es();return Ds(a,i.message,e),{welcome:r,greetingHost:a}},Gs=(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}=jo(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:zs,iconSize:Bs});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=Mo(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:zs,iconSize:Vs});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}=Ws(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 _=Us(`followUp`),v=Ja(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=Wo({config:e}),{root:x,textNode:S}=Uo();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}},Ks=(e,t=!0)=>{if(_o(e))return Gs(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?Vo(e,r,{showClose:t}):Fo({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}=Ws(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=Us(`followUp`),h=Ja(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=Ho({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),Io(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}},qs=(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(ot(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(ot(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??qe(),s=Je();this.#i=null;let c=t?.contentParts&<(t.contentParts)?ut:``,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=xr({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=vr(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=Gr(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=Cr(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=Je();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=Gr(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=gr();if(n)return e(n,t);let r=this.#Le;return hr().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=nt(this.config.features?.artifacts,e),r=it(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=nt(this.config.features?.artifacts,t),i=it(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.#gt(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=Vr().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=>Gr(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)?Je():this.#rt();t||(t=Je(),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=Fr(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Dr(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=Fr(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),n=this.messages[this.messages.length-1];this.messages=!n||this.#ht(n,t)<=0?[...this.messages,t]:this.#gt([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#pt(e),n=this.messages.findIndex(e=>e.id===t.id);if(n===-1){this.#ft(t);return}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&&Kr(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&&Kr(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});let r=this.messages[n],i=this.messages[n-1],a=this.messages[n+1];(i&&this.#ht(i,r)>0||a&&this.#ht(r,a)>0)&&(this.messages=this.#gt(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,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}#gt(e){return[...e].sort((e,t)=>this.#ht(e,t))}};const Jr={add:e=>dt(e)},Yr=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Xr={allowedTypes:ft,maxFileSize:10485760,maxFiles:4};function Zr(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Qr(e){return e===`application/pdf`||e.startsWith(`text/`)||e.includes(`word`)?on:e.includes(`excel`)||e.includes(`spreadsheet`)?an:e===`application/json`?rn:nn}var $r=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??Xr.allowedTypes,maxFileSize:e.maxFileSize??Xr.maxFileSize,maxFiles:e.maxFiles??Xr.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:Jr}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:Xr.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=ct(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:Zr(),file:n,previewUrl:pt(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=Yr(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=pt(e.file),n=N(`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=N(`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=N(`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=Qr(e.file.type),i=b(r,20,`var(--persona-muted, #6b7280)`,1.5);i&&t.appendChild(i);let a=N(`span`);a.textContent=st(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=M(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),i=N(`div`,`persona-attachment-progress`);i.appendChild(N(`div`,`persona-attachment-progress__bar`));let a=M(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),o=P(`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=N(`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(cn,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 ei=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),ti=(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 ni(){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=>{ti(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{ei(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{ei(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 ri=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},ii=(e,t)=>{let n=N(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function ai(e,t={}){let n=ri(e,`[data-persona-composer-form]`),r=ri(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:ri(e,`[data-persona-composer-header]`),body:ri(e,`[data-persona-composer-body]`),actionsStart:ri(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:ri(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:ri(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:ri(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:ri(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=ii(`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=ii(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=ri(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:ri(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:ri(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:ri(e,`[data-persona-composer-submit]`)??void 0,micButton:ri(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 oi=[`--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`],si=`data-persona-menu-focus`,ci=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function li(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const ui=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function di(e){let t=e.label,n=!1,r=N(`div`,`persona-send-button-wrapper`),i=M(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${A} ${be}`,attrs:{type:`button`,"aria-haspopup":`menu`,"aria-expanded":`false`,"data-persona-composer-overflow-trigger":``}});r.appendChild(i);let a=M(`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=P(`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&&li(t)===e;t.toggleAttribute(si,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(li).filter(e=>!ui(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||=Dt({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(si);e&&i.focus()}},E=(e=0,t=!1)=>{if(n||w())return;u=t,ve(i,a,oi),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)},O=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))},ee=e=>{switch(ci.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`,O),a.addEventListener(`keydown`,ee),{trigger:r,triggerButton:i,panel:a,setItems:e=>{for(let t of c)e.includes(t)||t.removeAttribute(si);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`,O),a.removeEventListener(`keydown`,ee),S?.destroy(),S=null,r.remove(),a.remove(),c=[]}}}const fi={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},pi=`data-persona-composer-action`,mi=`data-persona-composer-disable-when-streaming`,hi=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function gi(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=N(`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 _i(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??fi.custom;e.placement===`end`&&s>=fi.send&&(vi(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${fi.send-1}.`),s=fi.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=N(`span`,`persona-composer-overflow-menu__icon`);if(t.iconName){let e=P(t.iconName,16,`currentColor`,1.5);e&&r.appendChild(e)}let i=N(`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(mi,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=je(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button`,A,be,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=P(t.iconName,24,`currentColor`,1.5);e&&n.appendChild(e)}if(o){let e=N(`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=M(`button`,{attrs:{type:`button`}}),a=i;if(n===`bar`){let e=N(`div`,`persona-send-button-wrapper`);e.appendChild(i),a=e}a.setAttribute(pi,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(pi,t.id),r.element.toggleAttribute(mi,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=di({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:i}),p),y=e=>{m!==e&&(h?.disconnect(),m=e,g=_i(e),typeof ResizeObserver<`u`&&(h=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??_i(e);n!==g&&(g=n,E())}),h.observe(e)))},b=(e,t)=>{let n=gi(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=g||_i(t);return r>0&&r<n},x=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=hi(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||=N(`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=M(`div`,{className:`persona-composer-overflow-menu__slot`,attrs:{role:`none`,[ie]:``}});t.appendChild(e.element),ae(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:fi.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(mi,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:M(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:M(`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=M(`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=M(`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=M(`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=N(`span`,`persona-composer-model-picker-label`),o=N(`span`,`persona-composer-model-picker-suffix`);n.append(a,o);let s=M(`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||=Dt({anchor:n,content:s,placement:`top-start`,offset:6,onDismiss:()=>n.setAttribute(`aria-expanded`,`false`)}),ve(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=M(`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=P(e.icon,16,`currentColor`,1.5);if(n){let e=N(`span`,`persona-composer-model-option-icon`);e.appendChild(n),t.appendChild(e)}}let n=N(`span`,`persona-composer-model-option-body`),r=N(`span`,`persona-composer-model-option-label`);if(r.textContent=e.label,n.appendChild(r),e.description){let t=N(`span`,`persona-composer-model-option-description`);t.textContent=e.description,n.appendChild(t)}t.appendChild(n);let i=N(`span`,`persona-composer-model-option-check`);i.setAttribute(`aria-hidden`,`true`);let a=P(`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=M(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=N(`span`,`persona-mention-chip-icon`),r=P(t.iconName,12,`currentColor`,1.5);r&&e.appendChild(r),n.appendChild(e)}let r=N(`span`,`persona-mention-chip-label`);r.textContent=t.shortLabel??t.label,n.appendChild(r);let i=M(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label}`}}),a=P(`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(),Tt(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}Tt(t)},destroy:()=>{r=!0,c(),Tt(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=M(`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=M(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let n=P(e.iconName,16,`currentColor`,1.5);n&&t.appendChild(n)}let n=N(`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=M(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=N(`span`,`persona-composer-quote-bar`),i=N(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=N(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=M(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=Sr(n.text),i.appendChild(a);let o=M(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=P(`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=M(`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=M(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=P(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=Sr(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=N(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=M(`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=M(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=M(`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=N(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=M(`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:ge,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 O=n[`--persona-surface`],ee=n[`--persona-container`],te=n[`--persona-palette-colors-gray-100`]??`#f3f4f6`,ne=n[`--persona-palette-colors-gray-200`]??`#e5e7eb`,re=n[`--persona-palette-colors-gray-300`]??`#d1d5db`,ie=!ee||ee===O,ae=ja(O??n[`--persona-background`]),oe=ie&&ae!==void 0&&ae<.179,k=oe?`rgba(255, 255, 255, 0.08)`:te,se=oe?`rgba(255, 255, 255, 0.12)`:ne,ce=oe?`rgba(255, 255, 255, 0.16)`:re,A=ie?k:ee,le=ie?se:ee;return n[`--persona-icon-btn-hover-bg`]=n[`--persona-icon-btn-hover-bg`]??A,n[`--persona-icon-btn-active-bg`]=n[`--persona-icon-btn-active-bg`]??le,ie&&(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`]??A,n[`--persona-artifact-tab-hover-bg`]=n[`--persona-artifact-tab-hover-bg`]??A,n[`--persona-artifact-card-hover-bg`]=n[`--persona-artifact-card-hover-bg`]??A,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=se(n.components,e??{})??{};return Oa({...r,palette:{...r.palette,colors:T(t)===`v5`?se(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=se({components:{launcher:r}},n),a=Ua(e?.darkTheme);return Fa(t===`dark`?Ja(se(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;ln.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement){if(t instanceof HTMLElement&&t.hasAttribute(`data-persona-reuse`)&&e.id===t.id)return!1;if(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}}}const so=/* @__PURE__ */ new WeakMap;function co(e){if(typeof e==`string`)return e.length;if(!e)return 0;if(typeof e!=`object`)return JSON.stringify(e)?.length??0;let t=so.get(e);return t===void 0&&(t=JSON.stringify(e)?.length??0,so.set(e,t)),t}function lo(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)??``,co(e.toolCall?.args),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 uo(){return/* @__PURE__ */ new Map}function fo(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function po(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function mo(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}const{setLoader:ho,load:go}=Me({fallbackImport:()=>import(`./chunk-Dg7uqL8l.js`)}),_o=go;function vo(e,t=xt){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 yo=0,bo=null;function xo(e=document){if(yo++,yo===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;bo={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,yo=Math.max(0,yo-1),yo===0&&bo)){let t=e.body,n=e.defaultView??window;t.style.overflow=bo.originalOverflow,t.style.position=bo.originalPosition,t.style.top=bo.originalTop,t.style.width=bo.originalWidth,n.scrollTo(0,bo.scrollY),bo=null}}}const So={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},Co=e=>(e?.launcher?.mountMode??`floating`)===`docked`,wo=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,To=e=>{let t=e?.launcher?.dock,n=D(e).dockWidth?t?.width:Ca(Ya(e),`components.panel.width`);return{side:t?.side??So.side,width:n??So.width,animate:t?.animate??So.animate,reveal:t?.reveal??So.reveal,maxHeight:t?.maxHeight??So.maxHeight}},Eo=e=>e===`followUp`?`follow-up`:e,Do=(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`}},Oo=/* @__PURE__ */ new WeakSet,ko=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Z=e=>{ko()||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`})})},Ao=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=N(`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=P(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=N(`span`,`persona-suggestion__copy`);if(n.appendChild(M(`span`,{className:`persona-suggestion__label`,text:t.label})),t.description&&a!==`chip`&&n.appendChild(M(`span`,{className:`persona-suggestion__description`,text:t.description})),e.appendChild(n),a!==`chip`){let t=b(Yt,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},jo=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`;!Oo.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(Oo.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(Do).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=Eo(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=Ao({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,Z(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})))}}},Mo={"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`},No={x:[1.4,1.05]},Po=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,Fo=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=No[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=P(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)},Io=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:r,iconName:i,iconText:a,wrapperClassName:o=Po,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=N(`div`,o),b=!!(d||f),x=M(`button`,{className:je(`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||zo.actionIconColor,backgroundColor:u,border:b?`${d||`0px`} solid ${f||`transparent`}`:void 0,borderRadius:p,paddingLeft:m,paddingRight:m,paddingTop:h,paddingBottom:h}});return i?Fo(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}},Lo=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=Po,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=Io({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}},Ro=(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}=Io({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}},zo={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)`},Bo={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)`},Vo={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)`},Ho=e=>{let{config:t,showClose:n=!0}=e,r=M(`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:zo.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=M(`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=P(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=N(`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=N(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=M(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:zo.titleColor,...Bo}}),f=M(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:zo.subtitleColor,...Vo}});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=Ro(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}=Lo(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:_}},Uo=(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))},Wo=e=>{let t=Ho({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 Go(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=Io({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?gt(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=vt(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=Fe({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 Ko={default:Wo,minimal:e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=N(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=zo.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=Ue({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=zo.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=N(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=N(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=zo.titleColor,Object.assign(u.style,Bo),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}=Lo(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=N(`div`,`persona-flex persona-items-center persona-gap-1`);c||Go(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=Ro(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=N(`div`);v.style.display=`none`;let y=N(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}}},qo=e=>Ko[e]??Ko.default,Jo=(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=N(`div`);i.style.display=`none`;let a=N(`span`),o=N(`span`),s=N(`button`);s.style.display=`none`;let c=N(`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=qo(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},Yo=e=>{let{config:t}=e,n=M(`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=xe(),i=M(`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}=_e(t);o();let s=j(t),c=Te(t),l=ue(t),u=de(t),d=M(`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=M(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=M(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=M(`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}},Xo=()=>{let e=M(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),t=N(`span`,`persona-pill-peek__icon`),n=b(sn,16,`currentColor`,1.5);n&&t.appendChild(n);let r=N(`span`,`persona-pill-peek__text`),i=N(`span`,`persona-pill-peek__caret`),a=b(Qt,16,`currentColor`,1.5);return a&&i.appendChild(a),e.append(t,r,i),{root:e,textNode:r}},Zo=e=>{let{config:t}=e,n=M(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=xe(),i=de(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=_e(t,{defaultMaxLines:5});o();let s=j(t),c=Te(t),l=ue(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=M(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=M(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=M(`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=M(`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}},Qo=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}},Q=(e,t)=>{if(!e)return null;let n=Qo(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},$o=(e,t)=>{let n=N(`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},es=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},ts=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(`:`))},ns=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),rs=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),is=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),as=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),os=e=>{if(!e||e.length===0)return null;let t=M(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=M(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=N(`span`,`persona-mention-chip-icon`),i=P(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(M(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},ss=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(we(r.ref,{readonly:!0,render:t}));return n},cs=(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(ss(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(we(i.ref,{readonly:!0,render:r}),a),n=a}}},ls=(e,t,n)=>{if(e.length===0)return null;try{let r=N(`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=N(`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}),es(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}},us=e=>{if(e.length===0)return null;try{let t=N(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!ts(e.audio))return;let r=N(`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}},ds=e=>{if(e.length===0)return null;try{let t=N(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!ts(e.video))return;let r=N(`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}},fs=e=>{if(e.length===0)return null;try{let t=N(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!ts(e.data))return;let r=N(`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}},ps=()=>{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},ms=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:ps};if(t){let e=t(r);if(e!==null)return e}return ps()},hs=(e,t)=>{let n=N(`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=N(`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},gs=(e,t,n=`div`)=>{let r=N(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},_s=(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},vs={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`}},ys=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=vs[n??`bubble`]??vs.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)`)},bs=e=>`custom:${e}`,xs=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),Ss=(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=xs(t,e.role);if(!i&&!a&&!o&&!s&&!c&&!l&&!u&&d.length===0){let t=N(`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],_=N(`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=Re({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,bs(e.id)));return _},Cs=(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=_s(e.role,s),h=N(`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;ys(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=ns(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=zt(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?Vt(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?Ht(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`?qt(n,`char`,e.id,{skipTags:C.skipTags}):T&&C?.wrap===`word`?qt(n,`word`,e.id,{skipTags:C.skipTags}):n},ee=null;if(b?(ee=document.createElement(`div`),ee.innerHTML=O(),ee.style.display=`none`,E.appendChild(ee)):e.contentSegments?.length?cs(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=Bt(),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=gs(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=ls(v,!b&&!!y,()=>{b&&ee&&(ee.style.display=``)});e?h.appendChild(e):b&&ee&&(ee.style.display=``)}let te=rs(e);if(te.length>0){let e=us(te);e&&h.appendChild(e)}let ne=is(e);if(ne.length>0){let e=ds(ne);e&&h.appendChild(e)}let re=as(e);if(re.length>0){let e=fs(re);e&&h.appendChild(e)}let ie=e.contentSegments?.length?null:os(e.contextMentions);if(ie&&h.appendChild(ie),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=gs(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let ae=e.role===`assistant`?Q(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(Wt());else if(t)h.appendChild(Wt());else{let e=ms(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}ae&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild($o(e.stopReason,ae)));let oe=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,k=a?.actionEligibility,se=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&k?.canEdit===!0||r?.showQuote===!0&&k?.canQuote===!0||xs(r,`user`).length>0);if((oe||se)&&r){let t=Ss(e,se?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,k);h.appendChild(t)}if(!u||e.role===`system`)return h;let ce=N(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),A=hs(c,e.role);return f===`right`||f===`left`&&e.role===`user`?ce.append(h,A):ce.append(A,h),ce},ws=(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=P(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(M(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(M(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},Ts=(e,t,n={})=>{let r=M(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=N(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=N(`h2`,`persona-welcome-title`),o=N(`p`,`persona-welcome-subtitle`),s=M(`div`,{className:`persona-welcome-head-text`},i,a),c=M(`div`,{className:`persona-welcome-title-row`},r,s);return{host:M(`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}},Es=(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)},Ds=(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===``,ws(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`)},Os=`data-persona-welcome-overlay`,ks=`persona-welcome-overlay-active`,As=/* @__PURE__ */ new WeakMap,js=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(Os,``),e.classList.contains(ks)||(As.set(e,e.scrollTop),e.classList.add(ks),e.scrollTop=0)},Ms=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(Os),e.classList.contains(ks)&&(e.classList.remove(ks),e.scrollTop=As.get(e)??e.scrollTop,As.delete(e))},Ns=()=>{let e=M(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},Ps=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=M(`div`,{className:_s(`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(M(`div`,{className:`persona-flex`},i)),e.hidden=!1},Fs=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Is=(e,t)=>{if(Fs()||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},Ls=(e,t,n,r=260)=>{if(t<=1||Fs()||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`})},Rs=/* @__PURE__ */ new WeakSet,zs=(e,t)=>!!e&&e[t]!==void 0,Bs=(e,t)=>{e&&e.debug===!0&&t.length&&(Rs.has(e)||(Rs.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},Vs=(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=zs(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:zs(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];zs(n,`title`)&&zs(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),zs(n,`subtitle`)&&zs(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),zs(n,`variant`)&&zs(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&zs(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`&&zs(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 zs(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(zs(n,`anchorComposerTop`)||zs(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),Bs(e,c),{title:zs(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:zs(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`}},Hs=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,Us=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`),Ws=`var(--persona-components-panel-height)`,Gs=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, ${Ws})`:`max(200px, calc(${Ws} - ${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)`}},Ks=`16px`,qs=`10px`,Js=`14px`,Ys=e=>{let t=e?.launcher?.enabled??!0,n=Co(e);if(wo(e)){let t=e?.launcher?.composerBar??{},n=N(`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=N(`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=N(`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=N(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=N(`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=N(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=N(`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?Gs(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&&Mo[r.position]?Mo[r.position]:Mo[`bottom-right`],a=N(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=N(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),s=Gs(e);return o.style.width=s.width,o.style.maxWidth=s.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},Xs=e=>{let t=M(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":Eo(e)}});return t.hidden=!0,t},Zs=(e,t)=>{let n=Xs(`starter`),r=Ts(e,n,{flatShadow:Co(e)}),i=Vs(e);Ds(r,i),Es(t,r.host,Us(i,e?.initialMessages));let a=Ns();return Ps(a,i.message,e),{welcome:r,greetingHost:a}},Qs=(e,t)=>{let n=N(`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}=Lo(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:Ks,iconSize:qs});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=Ro(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:Ks,iconSize:Js});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=M(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=M(`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}=Zs(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=N(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=Xs(`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=M(`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=Zo({config:e}),{root:x,textNode:S}=Xo();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:N(`span`),headerTitle:N(`span`),headerSubtitle:N(`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}},$s=(e,t=!0)=>{if(wo(e))return Qs(e,t);let n=M(`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?Jo(e,r,{showClose:t}):Ho({config:e,showClose:t}),o=M(`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}=Zs(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=N(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=Xs(`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=Yo({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),Uo(n,a,e),n.append(o);let v=M(`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}},ec=(e,t)=>{let n=N(`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
|
-
`):``},hc=(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)`},gc=(e,t)=>{let n=e.toolCall,r=t?.features?.toolCallDisplay,i=r?.collapsedMode??c.collapsedMode,a=n?.success===!1?n.error||`Tool failed`:mc(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}},_c=(e,t,n,r)=>{mn(e,t,{stateSet:n,previewKind:`tool`,iconColor:pc(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},vc=(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}=gc(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=pc(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)dc(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`,hc(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`,hc(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`,hc(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:yc,load:bc,provide:xc,getSync:Sc}=me({fallbackImport:()=>import(`./chunk-GIqbL2Eg.js`)}),Cc=bc,wc=Sc,{setLoader:Tc,load:Ec}=me({fallbackImport:()=>import(`./chunk-DvqveR1q.js`)}),Dc=Ec,Oc=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:kc,load:Ac,provide:jc,getSync:Mc}=me({fallbackImport:()=>import(`./chunk-Do_1TKAR.js`)});let Nc=null;const Pc=/* @__PURE__ */ new Set,Fc=e=>{if(Nc)return Nc;Nc=e,e.initArtifactsUi({componentRegistry:Ee});for(let t of Oc)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=[...Pc];Pc.clear();for(let e of n)try{e()}catch{}return e},Ic=()=>Ac().then(Fc),Lc=()=>{if(Nc)return Nc;let e=Mc();return e?Fc(e):null},Rc=e=>Nc?()=>{}:(Pc.add(e),()=>{Pc.delete(e)});function zc(e){return e?.features?.artifacts?.enabled===!0}function Bc(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`),!zc(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 Vc(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 Hc=[`panel`,`seamless`,`detached`];function Uc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Hc.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function Wc(e){return!e||!zc(e)?!1:Uc(e)===`detached`}function Gc(e,t){if(!zc(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`),Vc(e),Bc(e,t);return}let n=t.features?.artifacts?.layout,r=Uc(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)}Bc(e,t)}function Kc(e,t){for(let t of Hc)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`),!zc(t))return;let n=t.features?.artifacts?.layout,r=Uc(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||!zc(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}const Jc=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),Yc=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),Xc=/* @__PURE__ */ new Set([`markdown`,`component`]),Zc=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Qc=e=>typeof e==`object`&&!!e&&!Array.isArray(e),$c=e=>!Jc.has(e),el=e=>typeof e==`string`&&Yc.has(e),tl=e=>Object.keys(e).length>0;function nl(e,t,n,r){e.push({path:t,code:n,message:r})}const rl=`Ignored an unsupported value.`,il={kind:`mode`,message:rl},al={kind:`string`,message:`Expected a CSS length string.`},ol={kind:`boolean`},sl={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:ol,showReasoning:ol,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:rl},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:rl},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:rl},expandable:ol,grouped:ol}},reasoningDisplay:{kind:`object`,children:{expandable:ol,activePreview:ol}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:il,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:il,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:Xc,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:Xc}}},filePreview:{kind:`object`,children:{enabled:ol}},layout:{kind:`object`,children:{paneWidth:al,paneMaxWidth:al,paneMinWidth:al,expandedPanelWidth:al,resizableMinWidth:al,resizableMaxWidth:al,expandLauncherPanelWhenOpen:ol,resizable:ol}}}}}};function cl(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:nl(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:nl(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:nl(r,n,`invalid_value`,t.message);case`mode`:return el(e)?tt(e):nl(r,n,`invalid_value`,t.message);case`modeMap`:{if(!Qc(e))return nl(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);$c(t)&&(i?i.has(t):Zc.test(e))?el(o)?a[e]=tt(o):nl(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):nl(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 tl(a)?a:void 0}case`object`:{if(t.bareMode&&el(e))return tt(e);if(!Qc(e))return nl(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))(!$c(t)||!i.includes(t))&&nl(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=cl(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&nl(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=Qc(l)&&Qc(s)?{...l,...s}:s}return tl(o)?o:void 0}}}function ll(e){let t=[];return{preferences:(e===null?void 0:cl(e,sl,``,t))??{},issues:t}}function ul(e){if(Array.isArray(e))return e.map(ul);if(!Qc(e))return e;let t={};for(let[n,r]of Object.entries(e))$c(n)&&r!==void 0&&(t[n]=ul(r));return t}function dl(e,t){let n=ul(e);for(let[e,r]of Object.entries(t)){if(!$c(e)||r===void 0)continue;let t=n[e];n[e]=Qc(t)&&Qc(r)?dl(t,r):ul(r)}return n}function fl(e){let t={},n;for(let r of e){let e=ll(r).preferences;n=ml(n,e.artifacts?.display),t=dl(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function pl(e,t){if(t===void 0)return e===void 0?void 0:ul(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}:{},...tl(i)?{byMediaType:i}:{}};return tl(a)?a:void 0}function ml(e,t){if(t===void 0)return e===void 0?void 0:ul(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=pl(n.files,t.files),o={...r?{default:r}:{},...tl(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return tl(o)?o:void 0}function hl(e={},t){let n=fl(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=ml(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 gl(e){let t=e.preferences;return!t||!tl(t)?e:{...e,features:hl(e.features??{},[t])}}function _l(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 vl(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 yl(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function bl(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function xl(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 Sl(e,t,n,r,i,a,o=200){let s=_l(i,200),c=bl(t,n,r,o);c=Math.max(s,c);let l=vl(a);return l!==null&&(c=Math.min(c,l)),yl(e,s,c)}const{setLoader:Cl,load:wl,provide:Tl,getSync:El}=me({fallbackImport:()=>import(`./chunk-Bp9uGcpc.js`)}),Dl=wl,Ol=El,kl=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()}},Al=e=>typeof e==`object`&&!!e&&!Array.isArray(e),jl=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),Ml=(e,t,n)=>{if(!Al(e)||!Al(t)||jl.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]=Ml(e[i],t[i],a)}return r};function Nl(e,n){let r=h(u),i=o(e,n,r),a=g(t(Ml(e,n,``),r,i),i);return f(l(a),fe(e,n))}const Pl=()=>{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)}})}}},Fl=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Il=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},Ll=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=Fl(e),n=Il(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}},Rl=e=>typeof e==`string`?e:e==null?``:String(e),zl={message:e=>{if(e.type===`message`)return{handled:!0,displayText:Rl(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=Rl(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:Rl(n.text)}}},Bl=e=>Array.isArray(e)?e.map(e=>String(e)):[],Vl=e=>{let t=new Set(Bl(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Bl(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}},Hl=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}},Ul=e=>e.map(e=>({...e,streaming:!1})),Wl=e=>e.map(e=>({...e,status:`complete`})),Gl=(e=`persona-state`)=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Hl(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?Ul(n.messages):void 0,artifacts:n.artifacts?Wl(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)}}}},Kl=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`)},ql=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 Kl(e)},Jl=async(e,t)=>{let n=await ql(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await ql(`${e}\0${t}`)}`}},Yl=(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 Jl(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:Xl,load:Zl}=me({fallbackImport:()=>import(`./chunk-Zom7XuVp.js`)}),Ql=Zl,{setLoader:$l,load:eu,provide:tu,getSync:nu}=me({fallbackImport:()=>import(`./chunk-Bvr_E4ga.js`)}),ru=eu,iu=nu;function au(){return null}function ou(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=Ee.get(e.component);if(!a){if(Oc.includes(e.component)){Ic().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 su(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 cu(e){let t=su(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 lu(e){let t=su(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 uu=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function du(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=uu}=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=Co(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=P(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=P(t.callToActionIconName,r,`currentColor`,1.5);i?u.appendChild(i):u.textContent=t.callToActionIconText??`↗`}else u.textContent=t.callToActionIconText??`↗`}let d=t.position&&Mo[t.position]?Mo[t.position]:Mo[`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()}}},tc=/* @__PURE__ */ new Set,nc=e=>{let t=e?.persistState;return`${(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`}teaser-dismissed`},rc=(e,t)=>{if(tc.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)===`1`}catch{return!1}},ic=(e,t)=>{if(tc.add(e),t)try{window.localStorage.setItem(e,`1`)}catch{}},ac=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,oc=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Co(e??{})?null:t},sc=(e,t)=>{let n=N(`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(),ic(nc(r),e&&p())},_=e=>{i&&!d&&g(e===`user`&&l)},v=()=>{c=null,!(!a||d||f)&&(u=!0,l=!0,a.hidden=!1,!(ac()||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||rc(nc(r),p())||(m(),c=setTimeout(v,Math.max(0,i.delayMs??0))))},b=()=>{g(p()),t()},x=e=>{e.stopPropagation(),g(p())},S=ec(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=M(`button`,{className:`persona-launcher-teaser-text`,attrs:{type:`button`}}),s.addEventListener(`click`,b),o=M(`button`,{className:`persona-launcher-teaser-dismiss`,attrs:{type:`button`},text:`×`}),o.addEventListener(`click`,x),a=M(`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=Mo[e]??Mo[`bottom-right`];a?(n.className=je(`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=oc(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()}}},cc=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:i}=Ys(e),a=$s(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}}},lc=({config:e,plugins:t,onToggle:n})=>{let r=t.find(e=>e.renderLauncher);if(r?.renderLauncher){let t=r.renderLauncher({config:e,defaultRenderer:()=>ec(e,n).element,onToggle:n});if(t)return{instance:null,element:t}}let i=sc(e,n);return{instance:i,element:i.element}},uc=e=>{let t=e?.persistState;return(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`},dc=(e,t,n)=>`${uc(e)}plugin:${t}:${n}`,fc=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=>dc(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
|
+
`):``},pc=(e,t,n)=>{R(e,t,{stateSet:n,previewKind:`reasoning`,iconColor:`currentColor`})},mc=(e,t,n=/* @__PURE__ */ new Set)=>{t=_n(t,`reasoning`);let r=e.reasoning,i=fn(`persona-reasoning-bubble`,e.id);if(!r)return z(i,e,t,`reasoning`);let a=t?.features?.reasoningDisplay??{},o=a.expandable??he.expandable,s=o&&n.has(e.id),c=r.status!==`complete`,l=$(e,a.previewMaxLines??he.previewMaxLines),u=pn({expandable:o,expanded:s,bubbleType:`reasoning`}),f=N(`div`,`persona-flex persona-flex-col persona-text-left`),h=N(`span`,`persona-text-xs persona-text-persona-primary`),g=vn(t,`reasoning`)===`row`,_=g&&!c?`Thought for ${yn(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=N(`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=N(`span`,`persona-text-xs persona-text-persona-primary`);S.textContent=p(r),g||f.appendChild(S);let C=a.loadingAnimation??he.loadingAnimation,w=v.activeTextTemplate,T=v.completeTextTemplate,E=c?w:T,D=x instanceof HTMLElement,O=(e,t)=>{h.textContent=``;let n=d(e,``),i=0;for(let e of n){let n=e.styles.length>0?(()=>{let t=N(`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=Ve(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`),O(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)),O(E,!0))}else O(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=``,Ve(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=N(`span`,`persona-reasoning-header-icon`),t=P(a.iconName,16,`currentColor`,2);t&&(e.appendChild(t),u.appendChild(e))}let ee=`currentColor`,te=hn(u,f,{expandable:o,expanded:s,iconColor:ee,metaGap:!1}),ne=gn({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,ne),z(i,e,t,`reasoning`);let re=N(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3`);re.style.display=s?``:`none`;let ie=r.chunks.join(``),ae=N(`div`,`persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted`);return ae.textContent=ie||(r.status===`complete`?`No additional context was shared.`:`Waiting for details…`),re.appendChild(ae),L({expanded:s,header:u,toggleIcon:te,content:re,collapsedPreview:ne,iconColor:ee}),i.append(u,ne,re),z(i,e,t,`reasoning`)},hc=e=>{if(e==null)return!0;if(typeof e==`string`){if(!e.trim())return!0;try{return hc(JSON.parse(e))}catch{return!1}}return typeof e==`object`&&Object.keys(e).length===0},gc=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 _c(e,t,n){let r=t.toolCall;if(!r)return;let a=n.toolCall??{},o=(t,n)=>{let r=M(`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=M(`div`,{className:`persona-tool-detail-label`,text:t,style:{color:a.labelTextColor}}),s=i(n),c=M(`pre`,{className:`persona-tool-detail-value${gc(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=M(`button`,{className:`persona-tool-detail-copy`,attrs:{type:`button`,"data-persona-copy-tool-detail":``,"aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),u=P(`copy`,14,`currentColor`,1.7);u&&l.appendChild(u),r.append(o,c,l),e.appendChild(r)};hc(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(M(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``,role:`status`}}))}const vc=/* @__PURE__ */ new WeakMap;async function yc(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(vc.get(e));try{await navigator.clipboard.writeText(n.textContent??``),e.dataset.copied=`true`,e.setAttribute(`aria-label`,`Copied`),e.title=`Copied`;let t=P(`check`,14,`currentColor`,2);t&&e.replaceChildren(t)}catch{e.setAttribute(`aria-label`,`Copy failed — try again`),e.title=`Copy failed — try again`}vc.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute(`aria-label`,r),e.title=r;let t=P(`copy`,14,`currentColor`,1.7);t&&e.replaceChildren(t),vc.delete(e)},1800))}const bc=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?`currentColor`:`var(--persona-primary, #171717)`),xc=(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
|
+
`):``},Sc=(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)`},Cc=(e,t)=>{let n=e.toolCall,i=t?.features?.toolCallDisplay,a=i?.collapsedMode??O.collapsedMode,o=n?.success===!1?n.error||`Tool failed`:xc(e,i?.previewMaxLines??O.previewMaxLines),s=n?.interrupted?`${n.name?.trim()||`Tool`} · Interrupted`:n?vn(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}},wc=(e,t,n,r)=>{R(e,t,{stateSet:n,previewKind:`tool`,iconColor:bc(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},Tc=(e,t,n=/* @__PURE__ */ new Set)=>{t=_n(t,`tool`);let r=e.toolCall,a=t?.toolCall??{},o=fn(`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 z(o,e,t,`tool`);let s=t?.features?.toolCallDisplay??{},c=s.expandable??O.expandable,u=c&&n.has(e.id),{summary:f,previewText:p,isActive:m}=Cc(e,t),h=pn({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=N(`div`,`persona-flex persona-flex-col persona-text-left`),_=N(`span`,`persona-text-xs persona-text-persona-primary`);a.headerTextColor&&(_.style.color=a.headerTextColor);let v=String(r.startedAt??Date.now()),y=()=>{let e=N(`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??O.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??O.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=N(`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=Ve(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=``,Ve(_,e,0)}}else w&&E(w,!1)}let D=bc(a,vn(t,`tool`)===`row`),ee=hn(h,g,{expandable:c,expanded:u,iconColor:D,metaGap:!0}),te=gn({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,te),z(o,e,t,`tool`);let ne=N(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);if(ne.style.display=u?``:`none`,a.contentBackgroundColor&&(ne.style.backgroundColor=a.contentBackgroundColor),a.contentTextColor&&(ne.style.color=a.contentTextColor),a.contentPaddingX&&(ne.style.paddingLeft=a.contentPaddingX,ne.style.paddingRight=a.contentPaddingX),a.contentPaddingY&&(ne.style.paddingTop=a.contentPaddingY,ne.style.paddingBottom=a.contentPaddingY),t.future?.v5Defaults===!0)_c(ne,e,t);else{if(r.name){let e=N(`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,ne.appendChild(e)}if(r.args!==void 0){let e=N(`div`,`persona-space-y-1`),t=N(`div`,`persona-text-xs persona-text-persona-muted`);a.labelTextColor&&(t.style.color=a.labelTextColor),t.textContent=`Arguments`;let n=N(`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`,Sc(n,a),n.textContent=i(r.args),e.append(t,n),ne.appendChild(e)}if(r.chunks&&r.chunks.length){let e=N(`div`,`persona-space-y-1`),t=N(`div`,`persona-text-xs persona-text-persona-muted`);a.labelTextColor&&(t.style.color=a.labelTextColor),t.textContent=`Activity`;let n=N(`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`,Sc(n,a),n.textContent=r.chunks.join(``),e.append(t,n),ne.appendChild(e)}if(r.success===!1&&ne.appendChild(M(`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=N(`div`,`persona-space-y-1`),t=N(`div`,`persona-text-xs persona-text-persona-muted`);a.labelTextColor&&(t.style.color=a.labelTextColor),t.textContent=`Result`;let n=N(`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`,Sc(n,a),n.textContent=i(r.result),e.append(t,n),ne.appendChild(e)}if(r.status===`complete`&&typeof r.duration==`number`){let e=N(`div`,`persona-text-xs persona-text-persona-muted`);a.contentTextColor&&(e.style.color=a.contentTextColor),e.textContent=`Duration: ${r.duration}ms`,ne.appendChild(e)}}return L({expanded:u,header:h,toggleIcon:ee,content:ne,collapsedPreview:te,iconColor:D}),o.append(h,te,ne),z(o,e,t,`tool`)},{setLoader:Ec,load:Dc,provide:Oc,getSync:kc}=Me({fallbackImport:()=>import(`./chunk-Bm2-bemv.js`)}),Ac=Dc,jc=kc,{setLoader:Mc,load:Nc}=Me({fallbackImport:()=>import(`./chunk-DvqveR1q.js`)}),Pc=Nc,Fc=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:Ic,load:Lc,provide:Rc,getSync:zc}=Me({fallbackImport:()=>import(`./chunk-Do_1TKAR.js`)});let Bc=null;const Vc=/* @__PURE__ */ new Set,Hc=e=>{if(Bc)return Bc;Bc=e,e.initArtifactsUi({componentRegistry:We});for(let t of Fc)We.has(t)||We.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Le();t?e.__provideMarkdownParsers(t):Be(()=>{let t=Le();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>Ne());let n=[...Vc];Vc.clear();for(let e of n)try{e()}catch{}return e},Uc=()=>Lc().then(Hc),Wc=()=>{if(Bc)return Bc;let e=zc();return e?Hc(e):null},Gc=e=>Bc?()=>{}:(Vc.add(e),()=>{Vc.delete(e)});function Kc(e){return e?.features?.artifacts?.enabled===!0}function qc(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`),!Kc(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 Jc(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 Yc=[`panel`,`seamless`,`detached`];function Xc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Yc.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function Zc(e){return!e||!Kc(e)?!1:Xc(e)===`detached`}function Qc(e,t){if(!Kc(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`),Jc(e),qc(e,t);return}let n=t.features?.artifacts?.layout,r=Xc(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)}qc(e,t)}function $c(e,t){for(let t of Yc)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`),!Kc(t))return;let n=t.features?.artifacts?.layout,r=Xc(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 el(e,t){return!t||!Kc(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}const tl=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),nl=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),rl=/* @__PURE__ */ new Set([`markdown`,`component`]),il=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,al=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ol=e=>!tl.has(e),sl=e=>typeof e==`string`&&nl.has(e),cl=e=>Object.keys(e).length>0;function ll(e,t,n,r){e.push({path:t,code:n,message:r})}const ul=`Ignored an unsupported value.`,dl={kind:`mode`,message:ul},fl={kind:`string`,message:`Expected a CSS length string.`},pl={kind:`boolean`},ml={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:pl,showReasoning:pl,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:ul},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:ul},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:ul},expandable:pl,grouped:pl}},reasoningDisplay:{kind:`object`,children:{expandable:pl,activePreview:pl}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:dl,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:dl,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:rl,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:rl}}},filePreview:{kind:`object`,children:{enabled:pl}},layout:{kind:`object`,children:{paneWidth:fl,paneMaxWidth:fl,paneMinWidth:fl,expandedPanelWidth:fl,resizableMinWidth:fl,resizableMaxWidth:fl,expandLauncherPanelWhenOpen:pl,resizable:pl}}}}}};function hl(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:ll(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:ll(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:ll(r,n,`invalid_value`,t.message);case`mode`:return sl(e)?rt(e):ll(r,n,`invalid_value`,t.message);case`modeMap`:{if(!al(e))return ll(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:I(t);ol(t)&&(i?i.has(t):il.test(e))?sl(o)?a[e]=rt(o):ll(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):ll(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 cl(a)?a:void 0}case`object`:{if(t.bareMode&&sl(e))return rt(e);if(!al(e))return ll(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))(!ol(t)||!i.includes(t))&&ll(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=hl(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&ll(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=al(l)&&al(s)?{...l,...s}:s}return cl(o)?o:void 0}}}function gl(e){let t=[];return{preferences:(e===null?void 0:hl(e,ml,``,t))??{},issues:t}}function _l(e){if(Array.isArray(e))return e.map(_l);if(!al(e))return e;let t={};for(let[n,r]of Object.entries(e))ol(n)&&r!==void 0&&(t[n]=_l(r));return t}function vl(e,t){let n=_l(e);for(let[e,r]of Object.entries(t)){if(!ol(e)||r===void 0)continue;let t=n[e];n[e]=al(t)&&al(r)?vl(t,r):_l(r)}return n}function yl(e){let t={},n;for(let r of e){let e=gl(r).preferences;n=xl(n,e.artifacts?.display),t=vl(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function bl(e,t){if(t===void 0)return e===void 0?void 0:_l(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}:{},...cl(i)?{byMediaType:i}:{}};return cl(a)?a:void 0}function xl(e,t){if(t===void 0)return e===void 0?void 0:_l(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=bl(n.files,t.files),o={...r?{default:r}:{},...cl(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return cl(o)?o:void 0}function Sl(e={},t){let n=yl(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=xl(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 Cl(e){let t=e.preferences;return!t||!cl(t)?e:{...e,features:Sl(e.features??{},[t])}}function wl(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 Tl(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 El(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Dl(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function Ol(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 kl(e,t,n,r,i,a,o=200){let s=wl(i,200),c=Dl(t,n,r,o);c=Math.max(s,c);let l=Tl(a);return l!==null&&(c=Math.min(c,l)),El(e,s,c)}const{setLoader:Al,load:jl,provide:Ml,getSync:Nl}=Me({fallbackImport:()=>import(`./chunk-Bp9uGcpc.js`)}),Pl=jl,Fl=Nl,Il=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()}},Ll=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Rl=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),zl=(e,t,n)=>{if(!Ll(e)||!Ll(t)||Rl.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]=zl(e[i],t[i],a)}return r};function Bl(e,t){let n=oe(te),r=E(e,t,n),i=k(x(zl(e,t,``),n,r),r);return re(ee(i),Ae(e,t))}const Vl=()=>{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)}})}}},Hl=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Ul=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},Wl=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=Hl(e),n=Ul(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}},Gl=e=>typeof e==`string`?e:e==null?``:String(e),Kl={message:e=>{if(e.type===`message`)return{handled:!0,displayText:Gl(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=Gl(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:Gl(n.text)}}},ql=e=>Array.isArray(e)?e.map(e=>String(e)):[],Jl=e=>{let t=new Set(ql(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ql(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}},Yl=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}},Xl=e=>e.map(e=>({...e,streaming:!1})),Zl=e=>e.map(e=>({...e,status:`complete`})),Ql=e=>`${e??`persona-`}state`,$l=(e=Ql())=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Yl(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?Xl(n.messages):void 0,artifacts:n.artifacts?Zl(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)}}}},eu=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`)},tu=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 eu(e)},nu=async(e,t)=>{let n=await tu(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await tu(`${e}\0${t}`)}`}},ru=(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 nu(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:iu,load:au}=Me({fallbackImport:()=>import(`./chunk-Zom7XuVp.js`)}),ou=au,{setLoader:su,load:cu,provide:lu,getSync:uu}=Me({fallbackImport:()=>import(`./chunk-Bvr_E4ga.js`)}),du=cu,fu=uu;function pu(){return null}function mu(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=We.get(e.component);if(!a){if(Fc.includes(e.component)){Uc().catch(()=>{});let e=N(`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 hu(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 gu(e){let t=hu(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 _u(e){let t=hu(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 vu=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function yu(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=vu}=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 fu(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 pu=`persona-chat-history`,mu=`data-persona-composer-reason`,hu=`data-persona-composer-notice`,gu={"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 _u(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=gu[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 vu(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 yu(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 bu(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const xu=e=>!e||typeof e!=`object`?{}:{...e},Su=e=>e.map(e=>({...e,streaming:!1})),Cu=(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 wu(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 Tu=(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},Eu=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Tu(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),Du=(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)=>{hs.delete(e);let n=Array.from(B.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?_c(e,n,u,c):sc(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=gl(c);let g=kl.getForInstance(c.plugins),x=ft(t),S=[],C=!1,D=ac(()=>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=wc();return e?(fe(e),e):(Cc().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=Ol();i?i.enhanceWithForms(e,t,n,r):Dl().then(()=>{A||me||!he||(me=!0,he())}).catch(()=>{})};c.components&&Ee.registerAll(c.components);let be=Pl(),xe=c.persistState===!1?null:c.storageAdapter??Gl(),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=xu(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:[Ll],Be=c.actionHandlers&&c.actionHandlers.length?c.actionHandlers:[zl.message,zl.messageAndClick],Ve=Vl({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=()=>_o(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=Cu(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??=[],Dc().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(mu)||e.hasAttribute(hu))){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=tc({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,qn=L.attachmentButton,Jn=L.attachmentButtonWrapper,Yn=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`,ar=()=>_t.pauseOnInteraction===!0,or=()=>_t.showActivityWhilePinned!==!1,sr=()=>_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,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(c.launcher?.mobileFullscreen??!0)&&e.innerWidth<=(c.launcher?.mobileBreakpoint??640)&&(He||go(c))||c.launcher?.fullHeight===!0&&!c.launcher.sidebarMode&&!go(c)},wr=()=>Ps(c,br()),Tr=`empty`,Er=0,Dr=()=>Er||parseFloat(t.style.getPropertyValue(`--persona-composer-lift`))||0,Or=()=>{let e=G.style.display===`none`?0:G.offsetHeight;dr.style.bottom=`${e+Dr()+12}px`};Or();let kr=()=>{mi||(G.style.marginBottom=Er>0?`${Er}px`:``)},Ar=()=>{let e=Ya(c,N()),n=wr();t.setAttribute(`data-persona-welcome-fullscreen`,String(br())),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`?Xa(n.anchorComposerTop)??Xa(`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)):Za({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,kr(),Or()},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=Qr();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??[],Br=()=>Fi(zr(),c.composer?.modeGroups);{let e=Ri(c.composer?.defaultActiveModeIds??[],zr());e.length&&J.setActiveModeIds(e)}function Vr(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 Hr(e){J.setActiveModeIds(e),qr?.render(e,Br()),Jr.forEach(e=>e.repaint()),Ei?.resolve(),id(),ra()}function Wr(e){Hr(Li(J.getState().activeModeIds,e,zr(),c.composer?.modeGroups))}let Gr=null,Kr=null,qr=null,Jr=/* @__PURE__ */ new Map,Xr=null;function Zr(e){J.setQuote(e),Xr?.render(J.getState().quote),ra(),Nc()}let $r=!1;function ei(){let e=c.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?c.clientToken?`interrupt`:(!$r&&c.debug===!0&&($r=!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=Jr.get(e);if(t)return t;let n=Vi({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 Jr.set(e,n),n},ai=()=>{let e=[],t=J.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(zr().forEach((r,i)=>{if(Ni(r.groupId,c.composer?.modeGroups)){let t=r.groupId;if(n.has(t))return;n.add(t);let a=ii(t);a.action.order=ji(i),a.action.label=c.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(a.action)}else e.push({id:Ai(r.id),kind:`button`,placement:`start`,order:ji(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||Kr!==t)&&(Kr=t,Gr=Oi({getModels:()=>c.composer?.models??[],getSelectedModelId:()=>J.getState().selectedModelId,onSelect:e=>Vr(e),presentation:t,getSuffix:()=>c.composer?.modelPicker?.suffix})),e.push(Gr.action)}return e},oi=null,si=g.find(e=>e.renderHeader);if(si?.renderHeader){let e=si.renderHeader({config:c,defaultRenderer:()=>{let e=Fo({config:c,showClose:at()});return Io(R,e,c),e.header},onClose:()=>uu(!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():Dc().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 ${No.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=No.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:()=>{Tu()||Yn?.click()},models:n?.models,selectedModelId:J.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>Vr(e),onVoiceToggle:c.voiceRecognition?.enabled===!0?()=>{oi?.()}:void 0})},gi=hi(()=>Ho({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&&(qn=e.attachmentButton,Jn=e.attachmentButton.parentElement),Yn=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=ti(e,{debug:c.debug===!0}),Y&&_i(Y),vi()};pi(G),yi(G),Fr();let bi=Ja(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=Ja(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 Si=()=>{c.attachments?.enabled&&Yn&&Zn&&(q?q.remountPreviews(Zn):(q=Yr.fromConfig(c.attachments,Rr),q.setPreviewsContainer(Zn)),Y?.addListener(Yn,`change`,e=>{let t=e.target;q?.handleFileSelect(t.files),t.value=``}),R.querySelector(`.persona-attachment-drop-overlay`)||R.appendChild(wu(c.attachments.dropOverlay)))};Si();let Ci=()=>Pr?.prefetch(),wi=()=>{if(!c.contextMentions?.enabled||!V)return;let e=lr();if(!e){let e=V;cr().then(()=>{!Pr&&V===e&&e.isConnected&&(wi(),Ei?.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)}};wi();let Ei=null,Di={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:()=>{Tu()||Yn?.click()},toggleVoice:()=>{oi?.()},requestRender:()=>Ei?.resolve()},Mi=()=>{let e=[];return(Pr?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:ci.mention+n,element:t,managed:!0})}),Jn&&e.push({id:`core:attachment`,placement:`start`,order:ci.attachment,element:Jn}),Kn&&e.push({id:`core:mic`,placement:`end`,order:ci.mic,element:Kn}),Wn&&e.push({id:`core:send`,placement:`end`,order:ci.send,element:Wn}),e},Pi=()=>{Ei?.destroy(),Ei=Ti({getBindings:()=>Y,collect:()=>({builtIns:Mi(),configActions:[...ai(),...c.composer?.actions??[]],plugins:g,contributionContext:{config:c,getState:()=>J.getState(),requestRender:()=>Ei?.resolve()},debug:c.debug===!0}),actionContext:Di,getState:()=>J.getState(),getOverflow:()=>c.composer?.actionOverflow,reportError:(e,t)=>{typeof console<`u`&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),Ei.resolve()};Pi();let Ii=()=>{if(qr?.destroy(),qr=null,!Br().length)return;let e=Y?.header;e&&(qr=ki({row:bt(e),onRemove:e=>Wr(e),initialIds:J.getState().activeModeIds}),qr.render(J.getState().activeModeIds,Br()))};Ii();let $i=()=>{Xr?.destroy(),Xr=null,ni?.destroy(),ni=null;let e=Y?.header;e&&(Xr=Hi({onDismiss:()=>Zr(void 0)}),e.appendChild(Xr.element),Xr.render(J.getState().quote),ei()===`defer-one`&&(ni=Ui({onEdit:()=>pf(),onRemove:()=>ri(void 0)}),e.appendChild(ni.element),ni.render(J.getState().pendingSubmission)))};$i();let ea=Yi(),na=()=>{let e=Y?.header?.querySelector(St);if(e)return e.childElementCount>0;let t=J.getState();return t.mentionRefs.length>0||Ri(t.activeModeIds,Br()).length>0};function ra(){let e=J.getState(),t=ea.observe(Xi(V),e.text);G.toggleAttribute(`data-persona-composer-compact`,Ji({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(()=>{Ei?.sync(),Au(),ju(),ra(),Nc()}),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(),fc(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;$s(),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),sc(r,n,d);else if(i===`tool`)u.has(r)?u.delete(r):u.add(r),_c(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)}hs.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=$a(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,ha=!1,ga=null,_a=()=>{},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=Lc();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=Lc();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),So())}),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),So())}),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=>{cr().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=lr();a?i(a):Pa||(Pa=!0,cr().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,Ra=null,za=null,Ba=null,Ha=()=>{},Ua=!1,Ga=``,so=``;function co(){Ba?.(),Ba=null}let fo=()=>{let e=Nd?.railShell?Nd.railHost:null,t=e?.isConnected?e:null,n=t?t.getBoundingClientRect().width:0;return n<=0?200:n+360},po=()=>{if(!La||!Ra)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){Ra.style.removeProperty(`position`),Ra.style.removeProperty(`left`),Ra.style.removeProperty(`top`),Ra.style.removeProperty(`bottom`),Ra.style.removeProperty(`width`),Ra.style.removeProperty(`z-index`);return}let i=La.firstElementChild;if(!i||i===Ra)return;Ra.style.position=`absolute`,Ra.style.top=`0`,Ra.style.bottom=`0`,Ra.style.width=`10px`,Ra.style.zIndex=`5`;let a=xl(La,n),o=i.offsetWidth+a/2-5;Ra.style.left=`${Math.max(0,o)}px`},ho=()=>{},yo=()=>{let e=t.ownerDocument.defaultView??window,n=c.launcher?.mobileFullscreen??!0,r=c.launcher?.mobileBreakpoint??640;return!n||e.innerWidth>r?!1:He||go(c)},xo=()=>!zc(c)||!Da()||t.classList.contains(`persona-artifact-narrow-host`)||yo()||(t.ownerDocument.defaultView??window).innerWidth<641?`none`:Wc(c)?`detached`:`welded`,So=()=>{if(!X||!zc(c))return;Gc(t,c),Kc(t,c),ho();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!==Ua){let e=X.element;Ca?(Ga=e.style.width,so=e.style.maxWidth,e.style.removeProperty(`width`),e.style.removeProperty(`max-width`)):(Ga&&(e.style.width=Ga),so&&(e.style.maxWidth=so),Ga=``,so=``),Ua=Ca}t.classList.toggle(`persona-artifact-expanded`,Ca),X.setExpanded(Ca);let a=xo();a!==ya&&(ya=a,_a()),Ha()};if(zc(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=>{ha||X||(X=e.createArtifactPane(c,{onSelect:e=>Oa.current?.selectArtifact(e),onDismiss:()=>{Sa=!0,So()},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),So())}}),X.element.classList.add(`persona-hidden`),n.appendChild(X.element),X.backdrop&&I.appendChild(X.backdrop),Ha(),So())},i=Lc();i?r(i):(Rc(()=>{let e=Lc();e&&r(e)}),Ic().catch(()=>{})),Ha=()=>{if(La&&X){if(c.features?.artifacts?.layout?.resizable!==!0)za?.(),za=null,co(),Ra&&=(Ra.remove(),null),X.element.style.removeProperty(`width`),X.element.style.removeProperty(`maxWidth`);else{if(!Ra){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(),co();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=xl(La,r),u=c?0:e.getBoundingClientRect().width||6,d=Sl(o-(n.clientX-a),i,l,u,s?.resizableMinWidth,s?.resizableMaxWidth,fo());X.element.style.width=`${d}px`,X.element.style.maxWidth=`none`,po()},u=()=>{n.removeEventListener(`pointermove`,l),n.removeEventListener(`pointerup`,u),n.removeEventListener(`pointercancel`,u),Ba=null;try{e.releasePointerCapture(i.pointerId)}catch{}};Ba=u,n.addEventListener(`pointermove`,l),n.addEventListener(`pointerup`,u),n.addEventListener(`pointercancel`,u);try{e.setPointerCapture(i.pointerId)}catch{}};e.addEventListener(`pointerdown`,i),Ra=e,La.insertBefore(e,X.element),za=()=>{e.removeEventListener(`pointerdown`,i)}}if(Ra){let e=Da();Ra.classList.toggle(`persona-hidden`,!e),po()}}}},ho=()=>{if(!He||!X||(c.launcher?.sidebarMode??!1)||go(c)&&vo(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||!qc(c,He))return;let i=Rs(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`&&(ga=new ResizeObserver(()=>{So()}),ga.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 Co=()=>{let e=yo()||N()&&c.launcher?.composerBar?.expandedSize===`fullscreen`||c.launcher?.fullHeight===!0&&!c.launcher?.sidebarMode&&!go(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=Wa(c),a=(e,t)=>e==null||e===``?t:va(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=go(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=Va(c)===`dark`?_(l??{},u??{}):l,f=Wa(c),p=(e,t)=>e==null||e===``?t:va(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=xo(),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`&&zc(c)&&Wc(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 bu(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 xu=`persona-chat-history`,Su=`data-persona-composer-reason`,Cu=`data-persona-composer-notice`,wu={"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 Tu(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=wu[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 Eu(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 Du(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 Ou(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const ku=e=>!e||typeof e!=`object`?{}:{...e},Au=e=>e.filter(e=>!yt(e)).map(e=>({...e,streaming:!1})),ju=(e,t,n)=>{let r=e?.markdown?Ge(e.markdown):null,i=ze(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=Le()!==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?G(o):o,t=r(e);l=i&&c?i(t):t}else l=Ie(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)),Ie(e.text??``)}}};function Mu(e){let t=N(`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=P(n,r,i,a);if(o&&t.appendChild(o),e?.label){let n=N(`span`,`persona-drop-overlay-label`);n.textContent=e.label,t.appendChild(n)}return t}const Nu=(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},Pu=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Nu(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),Fu=(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=ee(n),o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=bn((e,t)=>{hs.delete(e);let n=Array.from(H.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?wc(e,n,o,i):pc(e,n,s))}),l=/* @__PURE__ */ new Map,u=()=>{De({delayMs:i.tooltip?.delayMs??200,skipDelayMs:i.tooltip?.skipDelayMs??300})};u();let d=i.features;i=Cl(i);let f=Il.getForInstance(i.plugins),p=ht(t),m=[],g=!1,_=fc(()=>i),y=null,x=null,T=null,E=!1,O=null,te=t=>{y=t,t.initApprovalUi({webMcpToolTitle:e});let n=t.createBuiltInApprovalPlugin(l);x=n.plugin,T=n.teardown},ne=()=>{if(y)return y;let e=jc();return e?(te(e),e):(Ac().then(e=>{E||y||(te(e),O?.())}).catch(()=>{}),null)},re=!1,ie=!1,ae=null,oe=(e,t,n,r)=>{if(!e.querySelector(`[data-tv-form]`))return;let i=Fl();i?i.enhanceWithForms(e,t,n,r):Pl().then(()=>{re||ie||!ae||(ie=!0,ae())}).catch(()=>{})};i.components&&We.registerAll(i.components);let k=Vl(),ue=i.persistState===!1?null:i.storageAdapter??$l(Ql(typeof i.persistState==`object`?i.persistState.keyPrefix:void 0)),j=!!i.clientToken&&typeof i.reconnectStream!=`function`,de={},he=null,ge,_e=new Promise(e=>{ge=e}),ve=()=>{},xe=new Promise(e=>{ve=e}),we,Ae=!1,je=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&&(Ae=!0),e}return t}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}return e};if(ue?.load)try{let e=ue.load();if(e&&typeof e.then==`function`)he=e.then(e=>je(e??{messages:[],metadata:{}}));else{let t=je(e??{messages:[],metadata:{}});t.metadata&&(de=ku(t.metadata)),t.messages?.length&&(i={...i,initialMessages:t.messages}),t.artifacts?.length&&(i={...i,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),we=t.draft}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to load stored state:`,e)}else if(i.onStateLoaded)try{let e=je({messages:[],metadata:{}});e.messages?.length&&(i={...i,initialMessages:e.messages})}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}he||ge();let M=()=>de,Me=e=>{de=e({...de})??{},kc()},Ne=i.actionParsers&&i.actionParsers.length?i.actionParsers:[Wl],Fe=i.actionHandlers&&i.actionHandlers.length?i.actionHandlers:[Kl.message,Kl.messageAndClick],Re=Jl({parsers:Ne,handlers:Fe,getSessionMetadata:M,updateSessionMetadata:Me,emit:k.emit,documentRef:typeof document<`u`?document:null});Re.syncFromMetadata();let ze=i.launcher?.enabled??!0,Ve=i.launcher?.autoExpand??!1,Ue=i.autoFocusInput??!1,Ge=Ve,Ke=ze,qe=i.layout?.header?.layout,Je=!1,F=()=>wo(i),rt=()=>ze||F(),I=F()?!1:!ze||Ve,it=!1,at=null,st=()=>{it=!0,at&&clearTimeout(at),at=setTimeout(()=>{it&&=(typeof console<`u`&&console.warn(`[AgentWidget] Resubmit requested but no injection occurred within 10s`),!1)},1e4)},ct=ju(i,Re,st),lt=i.features?.showReasoning??!0,ut=i.features?.showToolCalls??!0,dt=i.features?.showEventStreamToggle??!1,pt=i.features?.scrollToBottom??{},mt=i.features?.scrollBehavior??{},gt=()=>(typeof i.persistState==`object`?i.persistState?.keyPrefix:void 0)??`persona-`,_t=`${gt()}event-stream`,vt=null,yt=i.features?.eventStream?.maxEvents??2e3,xt=null,Ct=null,Tt=null,Dt=!1,Yt=null,Zt=!1,Qt=null,$t=0,en=(e,t)=>{xt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},nn=(e,t)=>{Ct?.processEvent(e,t),xt?en(e,t):Tt&&(Tt.length>=yt&&Tt.shift(),Tt.push({type:e,payload:t}))},rn=()=>{!xt&&dt&&(Tt??=[],Pc().then(e=>{if(Dt||xt||!dt)return;vt=new e.EventStreamStore(_t),xt=new e.EventStreamBuffer(yt,vt),Ct??=new e.ThroughputTracker,vt.open().then(()=>xt?.restore()).catch(e=>{i.debug&&console.warn(`[AgentWidget] IndexedDB not available for event stream:`,e)});let t=Tt??[];Tt=null;for(let e of t)Ct?.processEvent(e.type,e.payload),en(e.type,e.payload)}).catch(()=>{}))};dt&&rn();let an=!1,on=null,sn=()=>{},cn=()=>{},ln=()=>{},un=()=>{},dn=()=>{},fn=()=>Zt||an&&on===`panel`,pn={onCopy:e=>{k.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=>{k.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 mn=(e,t=i.statusIndicator??{})=>e===`idle`?t.idleText??bt.idle:e===`connecting`?t.connectingText??bt.connecting:e===`connected`?t.connectedText??bt.connected:e===`error`?t.errorText??bt.error:e===`paused`?t.pausedText??bt.paused:e===`resuming`?t.resumingText??bt.resuming:bt[e];function hn(e,t,n,r){if(!F()&&(n.mode===`transient`||e.classList.contains(`persona-mb-2`))&&(C(e,En,n),w(e,n,r)),!(e.hasAttribute(Su)||e.hasAttribute(Cu))){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 gn=cc({config:i,showClose:rt()}),{wrapper:L,panel:R,pillRoot:_n}=gn.shell,z=gn.panelElements,{container:B,body:V,messagesWrapper:H,starterSuggestions:Cn,transcriptSuggestions:wn,suggestions:Tn,textarea:U,sendButton:W,composerForm:En,statusText:G,welcomeHost:Dn,welcomeIconHolder:On,greetingHost:An,introKicker:Mn,introTitle:Nn,introSubtitle:Pn,closeButton:K,iconHolder:In,headerTitle:Ln,headerSubtitle:Rn,header:zn,footer:q,actionsRow:Bn}=z,Vn=z.leftActions,Hn=z.rightActions,Un=z.sendButtonWrapper,Wn=z.setSendButtonMode,J=z.micButton,Gn=z.micButtonWrapper,Kn=z.attachmentButton,qn=z.attachmentButtonWrapper,Jn=z.attachmentInput,Yn=z.attachmentPreviewsContainer;B.classList.add(`persona-relative`),V.classList.add(`persona-relative`);let Xn=()=>pt.label??``,Qn=()=>pt.iconName??`arrow-down`,$n=()=>pt.enabled!==!1,er=()=>mt.mode??`anchor-top`,tr=()=>er()===`follow`||er()===`anchor-top`&&Qs,nr=()=>mt.anchorTopOffset??16,rr=()=>mt.restorePosition??`bottom`,ir=()=>mt.pauseOnInteraction===!0,ar=()=>mt.showActivityWhilePinned!==!1,or=()=>mt.announce===!0,sr=()=>mt.scrollbar??`on-scroll`,cr=N(`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`);cr.type=`button`,cr.style.display=`none`,cr.setAttribute(`data-persona-scroll-to-bottom`,`true`);let dr=N(`span`,`persona-flex persona-items-center`),fr=N(`span`,``),pr=N(`span`,``);pr.setAttribute(`data-persona-scroll-to-bottom-count`,``),pr.style.display=`none`,cr.append(dr,fr,pr),B.appendChild(cr);let mr=N(`div`,`persona-stream-anchor-spacer`);mr.setAttribute(`aria-hidden`,`true`),mr.setAttribute(`data-persona-anchor-spacer`,``),mr.style.flexShrink=`0`,mr.style.pointerEvents=`none`,mr.style.height=`0px`,mr.style.display=`none`,V.appendChild(mr);let hr=N(`div`,`persona-sr-only`);hr.setAttribute(`aria-live`,`polite`),hr.setAttribute(`aria-atomic`,`true`),hr.setAttribute(`role`,`status`),hr.setAttribute(`data-persona-live-region`,``),Object.assign(hr.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`}),B.appendChild(hr);let gr=null,_r=null,vr=e=>{or()&&e&&(_r=e,gr===null&&(gr=setTimeout(()=>{gr=null,_r&&or()&&(hr.textContent=_r),_r=null},400)))},yr=()=>{let e=t.ownerDocument.defaultView??window;return(i.launcher?.mobileFullscreen??!0)&&e.innerWidth<=(i.launcher?.mobileBreakpoint??640)&&(ze||Co(i))||i.launcher?.fullHeight===!0&&!i.launcher.sidebarMode&&!Co(i)},br=()=>Vs(i,yr()),xr=`empty`,Sr=0,Cr=()=>Sr||parseFloat(t.style.getPropertyValue(`--persona-composer-lift`))||0,Dr=()=>{let e=q.style.display===`none`?0:q.offsetHeight;cr.style.bottom=`${e+Cr()+12}px`};Dr();let Or=()=>{mi||(q.style.marginBottom=Sr>0?`${Sr}px`:``)},kr=()=>{let e=eo(i,F()),n=br();t.setAttribute(`data-persona-welcome-fullscreen`,String(yr())),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=q.style.display===`none`?0:q.offsetHeight,a=n.anchor===`center`&&xr===`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(V):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?V.getBoundingClientRect().top-B.getBoundingClientRect().top:0,f=!o||Dn.hidden?0:(Dn.querySelector(`[data-persona-welcome-plugin]`)??Dn).offsetHeight,p=a===null||F()?0:o?Math.max(0,Math.round((B.clientHeight-d-f-u-r)/2)):no({columnHeight:B.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`),Sr=e===`block`?p:0,Or(),Dr()},Ar=()=>{let e=!!Xn();cr.setAttribute(`aria-label`,Xn()||`Jump to latest`),cr.title=Xn(),cr.setAttribute(`data-persona-scroll-to-bottom-has-label`,e?`true`:`false`),dr.innerHTML=``;let t=P(Qn(),`14px`,`currentColor`,2);t?(dr.appendChild(t),dr.style.display=``):dr.style.display=`none`,fr.textContent=Xn(),fr.style.display=e?``:`none`};Ar();let jr=null,Mr=null,Y=ni();Y.subscribe(e=>{try{B.dispatchEvent(new CustomEvent(`persona:composer:state`,{detail:e,bubbles:!0,composed:!0}))}catch{}});let Fr=()=>{Y.setText(U?.value??``)},Ir=()=>{Y.setMentionRefs(Mr?.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));Y.setAttachments(t);try{i.attachments?.onChange?.(t)}catch(e){console.error(`[AgentWidget] attachments.onChange failed:`,e)}Nu()};Y.setSelectedModelId(i.composer?.selectedModelId);let zr=()=>i.composer?.modes??[],Br=()=>Bi(zr(),i.composer?.modeGroups);{let e=Ui(i.composer?.defaultActiveModeIds??[],zr());e.length&&Y.setActiveModeIds(e)}function Vr(e){if(Y.getState().selectedModelId!==e){Y.setSelectedModelId(e),Wr?.repaint();try{i.composer?.onModelChange?.(e)}catch(e){console.error(`[AgentWidget] composer.onModelChange failed:`,e)}}}function Hr(e){Y.setActiveModeIds(e),Kr?.render(e,Br()),Jr.forEach(e=>e.repaint()),Ei?.resolve(),cd(),Vi()}function Ur(e){Hr(Hi(Y.getState().activeModeIds,e,zr(),i.composer?.modeGroups))}let Wr=null,Gr=null,Kr=null,Jr=/* @__PURE__ */ new Map,Yr=null;function Xr(e){Y.setQuote(e),Yr?.render(Y.getState().quote),Vi(),Ic()}let Zr=!1;function Qr(){let e=i.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?i.clientToken?`interrupt`:(!Zr&&i.debug===!0&&(Zr=!0,typeof console<`u`&&console.warn(`[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".`)),`block`):e}let ei=null;function ti(e){Y.setPendingSubmission(e),ei?.render(Y.getState().pendingSubmission),Vi()}let ri=e=>{let t=Jr.get(e);if(t)return t;let n=Ki({groupId:e,getGroup:()=>i.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>zr().filter(t=>t.groupId===e),getActiveIds:()=>Y.getState().activeModeIds,onSelect:e=>Ur(e)});return Jr.set(e,n),n},ii=()=>{let e=[],t=Y.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(zr().forEach((r,a)=>{if(Ri(r.groupId,i.composer?.modeGroups)){let t=r.groupId;if(n.has(t))return;n.add(t);let o=ri(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:()=>Ur(r.id)})}),i.composer?.models?.length&&!f.some(e=>e.renderComposer)){let t=i.composer?.modelPicker?.presentation??`native`;(!Wr||Gr!==t)&&(Gr=t,Wr=Ni({getModels:()=>i.composer?.models??[],getSelectedModelId:()=>Y.getState().selectedModelId,onSelect:e=>Vr(e),presentation:t,getSuffix:()=>i.composer?.modelPicker?.suffix})),e.push(Wr.action)}return e},oi=null,si=f.find(e=>e.renderHeader);if(si?.renderHeader){let e=si.renderHeader({config:i,defaultRenderer:()=>{let e=Ho({config:i,showClose:rt()});return Uo(B,e,i),e.header},onClose:()=>cu(!1,`user`)});if(e){let t=zn;t&&(t.replaceWith(e),zn=e,gn.header.element=e)}}let ci=()=>{Yt&&(V.style.display=`none`,q.parentNode?.insertBefore(Yt.element,q),Yt.update())},li=()=>{if(!xt){rn();return}if(Zt=!0,Yt?ci():Pc().then(e=>{!Yt&&Zt&&xt&&(Yt=e.createEventStreamView({buffer:xt,getFullHistory:()=>xt.getAllFromStore(),onClose:()=>ui(),config:i,plugins:f,getThroughput:()=>Ct?.getMetric()??{status:`idle`},renderIconByName:P}),ci())}).catch(()=>{ui()}),di){di.style.boxShadow=`inset 0 0 0 1.5px ${zo.actionIconColor}`;let e=i.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&di.classList.add(e))}let e=()=>{if(!Zt)return;let t=Date.now();t-$t>=200&&(Yt?.update(),$t=t),Qt=requestAnimationFrame(e)};$t=0,Qt=requestAnimationFrame(e),il(),k.emit(`eventStream:opened`,{timestamp:Date.now()})},ui=()=>{if(Zt){if(Zt=!1,Yt&&Yt.element.remove(),V.style.display=``,di){di.style.boxShadow=``;let e=i.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&di.classList.remove(e))}Qt!==null&&(cancelAnimationFrame(Qt),Qt=null),il(),k.emit(`eventStream:closed`,{timestamp:Date.now()})}},di=null;if(dt){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:``);di=N(`button`,t),di.style.width=`28px`,di.style.height=`28px`,di.style.color=zo.actionIconColor,di.type=`button`,di.setAttribute(`aria-label`,`Event Stream`),di.title=`Event Stream`;let n=b(Jt,`18px`,`currentColor`,1.5);n&&di.appendChild(n);let r=z.clearChatButtonWrapper,a=z.closeButtonWrapper,o=r||a;o&&o.parentNode===zn?zn.insertBefore(di,o):zn.appendChild(di),di.addEventListener(`click`,()=>{Zt?ui():li()})}let pi=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=N(`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=N(`input`);n.type=`file`,n.setAttribute(`data-persona-composer-attachment-input`,``),n.accept=(t.allowedTypes??ft).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=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:()=>Gp(),storage:_(t.id),onSubmit:e=>{Q&&!Q.isStreaming()&&Tf(e.trim(),{consumeDraft:!1})},streaming:r,disabled:r,openAttachmentPicker:()=>{uu()||Jn?.click()},models:n?.models,selectedModelId:Y.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>Vr(e),onVoiceToggle:i.voiceRecognition?.enabled===!0?()=>{oi?.()}:void 0})},gi=hi(()=>Yo({config:i}).footer);gi&&(gn.replaceComposer(gi),q=gn.composer.footer,mi=!0);let _i=null,vi=e=>{En=e.form,U=e.input,Un=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(W=e.sendButton),e.micButton&&(J=e.micButton,Gn=e.micButton.parentElement),e.found.status&&(G=e.found.status),e.found.suggestions&&(Tn=e.found.suggestions),e.attachmentButton&&(Kn=e.attachmentButton,qn=e.attachmentButton.parentElement),Jn=e.attachmentInput??null,Yn=e.attachmentPreviews??null,e.found.actionsRow&&(Bn=e.found.actionsRow),Vn=e.found.actionsStart,Hn=e.found.actionsEnd};function yi(){let e=U;if(!e)return;let t=i.composer?.inputAttributes,n=!t?.ariaLabel&&!(e instanceof HTMLTextAreaElement)?e.getAttribute(`aria-label`):null;fe(e,t),n&&e.setAttribute(`aria-label`,n),pe(e,{submitKey:i.composer?.submitKey,insertNewlineOnTouchEnter:i.composer?.insertNewlineOnTouchEnter,coarsePointer:Ee(e)}),ce(e,Oe(i.composer?.maxLines,F()?5:3))}let bi=e=>{_i=ai(e,{debug:i.debug===!0}),_i&&vi(_i),yi()};pi(q),bi(q),Fr();let xi=$a(i,F());xi&&(H.style.maxWidth=xi,H.style.marginLeft=`auto`,H.style.marginRight=`auto`,H.style.width=`100%`,An.style.maxWidth=xi,An.style.marginLeft=`auto`,An.style.marginRight=`auto`,An.style.width=`100%`,Cn.style.maxWidth=xi,wn.style.maxWidth=xi,wn.style.marginLeft=`auto`,wn.style.marginRight=`auto`,wn.style.width=`100%`);let Si=()=>{let e=$a(i,F());if(e&&!F())for(let t of[En,Tn,Yn,G])t&&(t.style.maxWidth=e,t.style.marginLeft=`auto`,t.style.marginRight=`auto`,t.style.width=`100%`)};Si();let Ci=()=>{i.attachments?.enabled&&Jn&&Yn&&(jr?jr.remountPreviews(Yn):(jr=$r.fromConfig(i.attachments,Rr),jr.setPreviewsContainer(Yn)),_i?.addListener(Jn,`change`,e=>{let t=e.target;jr?.handleFileSelect(t.files),t.value=``}),B.querySelector(`.persona-attachment-drop-overlay`)||B.appendChild(Mu(i.attachments.dropOverlay)))};Ci();let wi=()=>Mr?.prefetch(),Ti=()=>{if(!i.contextMentions?.enabled||!U)return;let e=ur();if(!e){let e=U;lr().then(()=>{!Mr&&U===e&&e.isConnected&&(Ti(),Ei?.resolve())},()=>{});return}let t=_i?.header??null,n=t?wt(t):void 0;if(Mr=e.createContextMentionOrchestrator({deps:{loadContextMentions:me,loadContextMentionsInline:Se,renderLucideIcon:P,createMentionButton:ye},config:i,textarea:U,anchor:En??U,getMessages:()=>Q.getMessages(),liveRegionHost:B,chipRow:n}),Mr&&!n){let e=U;e.parentElement?.insertBefore(Mr.contextRow,e)}};Ti();let Ei=null,Di={getState:()=>Y.getState(),getValue:()=>U?.value??``,setValue:e=>{U&&(U.value=e,U.dispatchEvent(new Event(`input`,{bubbles:!0})),Fr())},submit:()=>{Ot(_i?.form??null)},openAttachmentPicker:()=>{uu()||Jn?.click()},toggleVoice:()=>{oi?.()},requestRender:()=>Ei?.resolve()},Oi=()=>{let e=[];return(Mr?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:fi.mention+n,element:t,managed:!0})}),qn&&e.push({id:`core:attachment`,placement:`start`,order:fi.attachment,element:qn}),Gn&&e.push({id:`core:mic`,placement:`end`,order:fi.mic,element:Gn}),Un&&e.push({id:`core:send`,placement:`end`,order:fi.send,element:Un}),e},ki=()=>{Ei?.destroy(),Ei=Ai({getBindings:()=>_i,collect:()=>({builtIns:Oi(),configActions:[...ii(),...i.composer?.actions??[]],plugins:f,contributionContext:{config:i,getState:()=>Y.getState(),requestRender:()=>Ei?.resolve()},debug:i.debug===!0}),actionContext:Di,getState:()=>Y.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(Kr?.destroy(),Kr=null,!Br().length)return;let e=_i?.header;e&&(Kr=Pi({row:wt(e),onRemove:e=>Ur(e),initialIds:Y.getState().activeModeIds}),Kr.render(Y.getState().activeModeIds,Br()))};ji();let Mi=()=>{Yr?.destroy(),Yr=null,ei?.destroy(),ei=null;let e=_i?.header;e&&(Yr=qi({onDismiss:()=>Xr(void 0)}),e.appendChild(Yr.element),Yr.render(Y.getState().quote),Qr()===`defer-one`&&(ei=Ji({onEdit:()=>mf(),onRemove:()=>ti(void 0)}),e.appendChild(ei.element),ei.render(Y.getState().pendingSubmission)))};Mi();let Li=ea(),zi=()=>{let e=_i?.header?.querySelector(Et);if(e)return e.childElementCount>0;let t=Y.getState();return t.mentionRefs.length>0||Ui(t.activeModeIds,Br()).length>0};function Vi(){let e=Y.getState(),t=Li.observe(ta(U),e.text);q.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`&&!F()?q.setAttribute(`data-persona-composer-layout`,`single-row`):q.removeAttribute(`data-persona-composer-layout`)}ia(),Y.subscribe(()=>{Ei?.sync(),Nu(),Fu(),Vi(),Ic()}),Fu();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 V.querySelector(`[data-persona-intro-card]`);case`messages`:return H;case`footer-top`:return Tn;case`composer`:return En;case`footer-bottom`:return G;default:return null}},n=(e,t)=>{switch(e){case`header-left`:case`header-center`:case`header-right`:if(e===`header-left`)zn.insertBefore(t,zn.firstChild);else if(e===`header-right`)zn.appendChild(t);else{let e=zn.querySelector(`.persona-flex-col`);e?e.parentNode?.insertBefore(t,e.nextSibling):zn.appendChild(t)}break;case`body-top`:{let e=V.querySelector(`[data-persona-intro-card]`);e?e.replaceWith(t):V.insertBefore(t,V.firstChild);break}case`body-bottom`:V.appendChild(t);break;case`footer-top`:Tn.replaceWith(t);break;case`footer-bottom`:G.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)}})(),H.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(),yc(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;nc(),al();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),pc(r,n,s);else if(a===`tool`)o.has(r)?o.delete(r):o.add(r),wc(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)}hs.delete(r)};H.addEventListener(`pointerdown`,e=>{e.target.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),ca(e))}),H.addEventListener(`click`,e=>{e.detail===0&&e.target.closest(`.persona-activity-row`)&&ca(e)}),H.addEventListener(`keydown`,e=>{let t=e.target;(e.key===`Enter`||e.key===` `)&&t.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),ca(e))}),H.addEventListener(`copy`,e=>{let{clipboardData:t}=e;if(!t)return;let n=H.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=P(n,14,`currentColor`,2);i&&(e.innerHTML=``,e.appendChild(i))},ma=()=>{H.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`)})};H.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&&pn.onCopy){let n=e.content||``;navigator.clipboard.writeText(n).then(()=>{t.classList.add(`persona-message-action-success`);let e=b(Xt,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e)),setTimeout(()=>{t.classList.remove(`persona-message-action-success`);let e=b(tn,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))},2e3)}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to copy message:`,e)}),pn.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=P(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=P(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=P(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&&pn.onFeedback&&pn.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;H.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=>nt(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}};H.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=Wc();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:a,markdown:r,file:o}))}),H.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{}}),H.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=Wc();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(Xt,16,`currentColor`,2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=b(tn,16,`currentColor`,2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),H.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),go())}),H.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),go())}),H.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=z.composerOverlay,Ma=e=>{lr().catch(()=>{}),Xe(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=ur();a?i(a):Fa||(Fa=!0,lr().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=Pd?.railShell?Pd.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=Ol(Ra,n),o=i.offsetWidth+a/2-5;za.style.left=`${Math.max(0,o)}px`},so=()=>{},co=()=>{let e=t.ownerDocument.defaultView??window,n=i.launcher?.mobileFullscreen??!0,r=i.launcher?.mobileBreakpoint??640;return!n||e.innerWidth>r?!1:ze||Co(i)},ho=()=>!Kc(i)||!Oa()||t.classList.contains(`persona-artifact-narrow-host`)||co()||(t.ownerDocument.defaultView??window).innerWidth<641?`none`:Zc(i)?`detached`:`welded`,go=()=>{if(!X||!Kc(i))return;Qc(t,i),$c(t,i),so();let e=i.features?.artifacts?.layout?.narrowHostMaxWidth??520,n=R.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=ho();o!==ya&&(ya=o,va()),Ha()};if(Kc(i)){R.style.position=`relative`;let e=N(`div`,`persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0`),n=N(`div`,`persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root`);e.appendChild(B),Ra=n,n.appendChild(e),R.appendChild(n);let r=e=>{ga||X||(X=e.createArtifactPane(i,{onSelect:e=>ka.current?.selectArtifact(e),onDismiss:()=>{Sa=!0,go()},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),go())}}),X.element.classList.add(`persona-hidden`),n.appendChild(X.element),X.backdrop&&R.appendChild(X.backdrop),Ha(),go())},a=Wc();a?r(a):(Gc(()=>{let e=Wc();e&&r(e)}),Uc().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=N(`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=Ol(Ra,r),u=a?0:e.getBoundingClientRect().width||6,d=kl(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()}}}},so=()=>{if(!ze||!X||(i.launcher?.sidebarMode??!1)||Co(i)&&To(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||!el(i,ze))return;let a=Gs(i).width,o=i.features?.artifacts?.layout?.expandedPanelWidth??`min(720px, calc(100vw - 24px))`;Oa()?(R.style.width=o,R.style.maxWidth=o):(R.style.width=a,R.style.maxWidth=a)},typeof ResizeObserver<`u`&&(_a=new ResizeObserver(()=>{go()}),_a.observe(R))}else R.appendChild(B);F()&&_n&&(z.peekBanner&&_n.appendChild(z.peekBanner),_n.appendChild(q)),t.appendChild(L),_n&&t.appendChild(_n);let yo=()=>{let e=co()||F()&&i.launcher?.composerBar?.expandedSize===`fullscreen`||i.launcher?.fullHeight===!0&&!i.launcher?.sidebarMode&&!Co(i);if(H.style.gap=e?`var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))`:`var(--persona-components-message-gap, 12px)`,H.style.setProperty(`--persona-transcript-gap`,H.style.gap),F()){R.style.width=`100%`,R.style.maxWidth=`100%`;let e=i.launcher?.composerBar??{},t=L.dataset.state===`expanded`,n=e.expandedSize??`anchored`;if(!(t&&n!==`fullscreen`)){B.style.background=``,B.style.border=``,B.style.borderRadius=``,B.style.overflow=``,B.style.boxShadow=``;return}let r=i.theme?.components?.panel,a=Ya(i),o=(e,t)=>e==null||e===``?t:Ca(a,e)??e;B.style.background=`var(--persona-surface, #ffffff)`,B.style.border=o(r?.border,`1px solid var(--persona-border)`),B.style.borderRadius=o(r?.borderRadius,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`),B.style.boxShadow=o(r?.shadow,`var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))`),B.style.overflow=`hidden`;return}let n=Co(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`?se(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&&ze,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))`)),O=s&&!_&&!v,ee=_||v?`mobile`:O?`floating`:n?`docked`:r?`sidebar`:o?`inline`:`floating`,te=u?.modes?.[ee];O?t.setAttribute(`data-persona-panel-detached`,`true`):t.removeAttribute(`data-persona-panel-detached`);let ne=O?w:r||_?`none`:w,re=O?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&&!_&&!O&&(re=`none`,ne=`none`);let ie=O?E:r||_?`0`:E,ae=f(te?.border??u?.border,S(ee,`border`,ne)),oe=f(te?.shadow??u?.shadow,S(ee,`shadow`,re)),k=f(te?.borderRadius??u?.borderRadius,S(ee,`borderRadius`,ie)),ce=ho(),A=ce===`detached`,le=ce===`welded`;t.classList.toggle(`persona-artifact-detached-split`,A),t.classList.toggle(`persona-artifact-welded-split`,le);let ue=`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)))))`,j=(i.features?.artifacts?.layout?.chatSurface===`flush`?`flush`:`card`)==`flush`&&Kc(i)&&Zc(i)&&o&&!n;t.classList.toggle(`persona-artifact-chat-flush`,j);let de=A||j?`none`:oe,fe=A?w:le?`none`:ae,pe=A?E:k;j&&(fe=`none`,pe=`0`);let me=te?.borderRadius!=null&&te.borderRadius!==``||u?.borderRadius!=null&&u.borderRadius!==``,he=j&&!me?`0`:k,ge=V.scrollTop;t.style.cssText=``,L.style.cssText=``,R.style.cssText=``,B.style.cssText=``,V.style.cssText=``,mi||(q.style.cssText=``),Zt&&(V.style.display=`none`),(a||o)&&(t.style.minWidth=`0`);let _e=()=>{ge<=0||(V.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(V.scrollTop===ge)return;let e=V.scrollHeight-V.clientHeight;e<=0||(V.scrollTop=Math.min(ge,e))})};if(_){L.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`),L.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
|
+
`,R.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
|
+
`,B.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
|
+
`,V.style.flex=`1 1 0%`,V.style.minHeight=`0`,V.style.overflowY=`auto`,q.style.flexShrink=`0`,Or(),Je=!0,_e();return}let ve=Gs(i);if(!r&&!n)o&&a?(R.style.width=`100%`,R.style.maxWidth=`100%`):(R.style.width=ve.width,R.style.maxWidth=ve.maxWidth);else if(n){if(To(i).reveal===`emerge`&&!s){let e=To(i).width;R.style.width=e,R.style.maxWidth=e}else R.style.width=`100%`,R.style.maxWidth=`100%`}if(so(),R.style.boxShadow=de,R.style.borderRadius=he,A?R.style.border=`none`:le&&(R.style.border=ae),B.style.border=fe,B.style.borderRadius=pe,B.style.boxShadow=A&&!j?ue:``,j&&(B.style.background=`transparent`,V.style.background=`transparent`,q.style.background=`transparent`,q.style.borderTop=`none`),le){let e=i.features?.artifacts?.layout;ba=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||k}else ba=null;let ye=te?.border!=null||u?.border!=null;if(n&&!_&&!O&&!A&&!le&&!ye&&(B.style.border=`none`,To(i).side===`right`?B.style.borderLeft=`1px solid var(--persona-border)`:B.style.borderRight=`1px solid var(--persona-border)`),n&&!_&&le&&!ye&&(To(i).side===`right`?R.style.borderLeft=`1px solid var(--persona-border)`:R.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%`),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%`,o&&(L.style.overflow=`hidden`),R.style.display=`flex`,R.style.flexDirection=`column`,R.style.flex=`1 1 0%`,R.style.minHeight=`0`,R.style.maxHeight=`100%`,R.style.height=`100%`,A||(R.style.overflow=`hidden`),B.style.display=`flex`,B.style.flexDirection=`column`,B.style.flex=`1 1 0%`,B.style.minHeight=`0`,B.style.maxHeight=`100%`,B.style.overflow=`hidden`,V.style.flex=`1 1 0%`,V.style.minHeight=`0`,V.style.overflowY=`auto`,q.style.flexShrink=`0`),o&&(O||A||j)&&!n&&(j||(L.style.padding=`var(--persona-panel-inset)`),L.style.background=`var(--persona-panel-canvas-bg)`),L.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&&(Mo[y]??Mo[`bottom-right`]).split(` `).forEach(e=>L.classList.add(e)),r){let e=D(i).sidebarWidth?i.launcher?.sidebarWidth??`420px`:Ca(Ya(i),`components.panel.width`)??`420px`;s?L.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
|
+
`:L.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
|
+
`,R.style.cssText=`
|
|
91
91
|
position: relative !important;
|
|
92
92
|
display: flex !important;
|
|
93
93
|
flex-direction: column !important;
|
|
@@ -98,10 +98,10 @@ import{t as e}from"./chunk-BtTP1Wgi.js";import{B as t,C as n,D as r,E as i,F as
|
|
|
98
98
|
min-height: 0 !important;
|
|
99
99
|
margin: 0 !important;
|
|
100
100
|
padding: 0 !important;
|
|
101
|
-
box-shadow: ${
|
|
102
|
-
border-radius: ${
|
|
103
|
-
${
|
|
104
|
-
`,
|
|
101
|
+
box-shadow: ${de} !important;
|
|
102
|
+
border-radius: ${he} !important;
|
|
103
|
+
${A?`border: none !important;`:le?`border: ${ae} !important;`:``}
|
|
104
|
+
`,R.style.setProperty(`width`,`100%`,`important`),R.style.setProperty(`max-width`,`100%`,`important`),B.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
|
-
`,mi||(
|
|
113
|
+
border-radius: ${pe} !important;
|
|
114
|
+
border: ${fe} !important;
|
|
115
|
+
${A&&!j?`box-shadow: ${ue} !important;`:``}
|
|
116
|
+
${j?`background: transparent !important;`:``}
|
|
117
|
+
`,mi||(q.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}kr(),ge()},Do=()=>{t.style.setProperty(`--persona-content-max-width`,Ja(c,N()))},Oo=!1;function jo(){c.layout?.topFade&&z.scrollTop>1?z.setAttribute(`data-persona-top-fade`,`true`):z.removeAttribute(`data-persona-top-fade`)}let Mo=()=>{jo();let e=Ya(c,N());N()&&c.composer?.placement&&c.debug===!0&&!Oo&&(Oo=!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`),Ar()},Po=()=>{if(N())return;let e=go(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=Rs(c);I.style.height=o.height,I.style.maxHeight=o.maxHeight};Co(),Ka(t,c),Gc(t,c),Kc(t,c),Do(),Mo(),_a=()=>{Co(),Po(),Ka(t,c),Gc(t,c),Kc(t,c),Do(),Mo(),ba?t.style.setProperty(`--persona-artifact-welded-outer-radius`,ba):t.style.removeProperty(`--persona-artifact-welded-outer-radius`),ln(),cn()};let Z=[];Z.push(()=>{ha=!0}),Z.push(()=>{S.forEach(e=>e()),x.destroy()}),Z.push(()=>{document.removeEventListener(`keydown`,Ia)}),Z.push(()=>{_r!==null&&clearTimeout(_r)});let Lo=null,Ro=null;Z.push(()=>{Lo?.(),Lo=null,Ro?.(),Ro=null}),ga&&Z.push(()=>{ga?.disconnect(),ga=null}),Z.push(()=>{za?.(),za=null,co(),Ra&&=(Ra.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 zo=null,Bo=()=>{zo&&=(zo(),null),c.colorScheme===`auto`&&(zo=qa(()=>{Ka(t,c)}))};Bo(),Z.push(()=>{zo&&=(zo(),null)}),Z.push(()=>{re=!0,ee?.()}),Z.push(()=>{A=!0});let Uo=!1;Z.push(()=>{Uo=!0});let Go=(e,n)=>{let r=Lt(e,n);return r||!Ht.includes(e)?r:(lo().then(r=>{if(Uo)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=To(En),Jo=To(wn),Yo=To(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),rs=e=>{for(let t=e.length-1;t>=0;t--)if(Qe(e[t]))return e[t].id??null;return null},is=!1,as=()=>{is||c.debug!==!0||(is=!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||c.debug!==!0||t.enabled&&!t.expose&&($o||cs&&(Q.isStreaming()||e.some(Qe)||(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.`))))},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||rs(t)!==ts)&&(Qo=null);let i=Xe(c);ls(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=br(),d=c.suggestions?.starters??(l?{}:void 0);if(d){let e=Is(wr(),t),i=d.placement??`auto`,a=i===`auto`?e?`welcome`:`composer`:i;if(a===`welcome`&&!e){as(),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())},ps=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=rs(n),ds(n)},ms=!1,hs=ro(),_s=/* @__PURE__ */ new Map,vs=/* @__PURE__ */ new Map,xs=/* @__PURE__ */ new Map,Ss=null,Cs=null;function Es(){if(!Ss)return;let e=Ss;Ss=null,Cs?.destroy(),Cs=null,hs.delete(e),R.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),Q&&Hl(B,Q.getMessages(),ut)}let Os=0,js=ye()!==null,Ms=jt(),Ns=0,Ls=null,zs=!1,Hs=!1,Us=0,Ws=null,Gs=null,Ks=!1,qs=!1,Js=null,Ys=!0,Xs=!1,Zs=null,Qs=!1,$s=()=>{Qs=!0,oc()},ec=null,rc=null,ic=()=>{t.setAttribute(`data-persona-scrollbar`,ur()),ur()!==`on-scroll`&&(rc!==null&&clearTimeout(rc),rc=null,z.removeAttribute(`data-persona-scrollbar-visible`))},oc=()=>{ur()===`on-scroll`&&(z.setAttribute(`data-persona-scrollbar-visible`,``),rc!==null&&clearTimeout(rc),rc=setTimeout(()=>{rc=null,Mt(z,24)&&z.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};ic(),Z.push(()=>{rc!==null&&clearTimeout(rc)});let lc=/* @__PURE__ */ new Map,uc=!1,dc=null,$={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};ra();let pc=c.voiceRecognition?.autoResume??!1,mc=()=>Q.isVoiceActive()||Q.isBargeInActive(),hc=!1,gc=e=>{be.emit(`voice:state`,{active:$.active,source:e,timestamp:Date.now()})},yc=()=>{Re(e=>({...e,voiceState:{active:$.active,timestamp:Date.now(),manuallyDeactivated:$.manuallyDeactivated}}))},bc=()=>{if(c.voiceRecognition?.enabled===!1)return;let e=xu(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=mc(),gc(`restore`),$.active?ip():(yc(),ff(`Tap the mic to resume your voice call`,1e4))}):ep(`restore`))},Sn(c.voiceRecognition?.provider)?0:1e3)},xc=e=>{hc=!e.persisted,$.active&&yc()};typeof window<`u`&&(window.addEventListener(`pagehide`,xc),Z.push(()=>window.removeEventListener(`pagehide`,xc)));let Sc=()=>Q?Su(Q.getMessages()).filter(e=>!e.__skipPersist):[],Tc=null,Ec=(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=>{Ec(t,e)})}catch(e){return Ec(t,e),null}},r=Tc,i=r?r.then(()=>n()??void 0):n();if(!i)return;let a=i.finally(()=>{Tc===a&&(Tc=null)});Tc=a};function kc(e){if(!xe?.save)return;let t=e?Su(e):Q?Sc():[],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=qi({write:()=>{if(!jc())return;let e=J.getState(),t=Gi({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 Nc(){jc()&&Mc.schedule()}function Pc(){Mc.flush()}function Fc(e){if(!jc())return;let t=Ki(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()),Hr(t.activeModeIds??[]),t.quote&&Zr(t.quote),Mc.cancel())}function Bc(){Mc.cancel(),Ac&&(Ac=void 0,jc()&&kc())}let Vc=null,Hc=()=>F.querySelector(`#persona-scroll-container`)||z,Uc=()=>{Vc!==null&&(cancelAnimationFrame(Vc),Vc=null),zs=!1},Jc=()=>{Ls!==null&&(cancelAnimationFrame(Ls),Ls=null),Hs=!1,Uc()},Yc=()=>ms&&$c()&&(tr()!==`anchor-top`||or()),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):pl(e)-z.scrollTop-z.clientHeight<=24},$c=()=>nr()?!Ms.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),Or();let e=Dt(z)>0&&$c()&&el();e?Xc():Zc(),dr.style.display=e?``:`none`},nl=()=>{Ms.pause()&&(Jc(),tl())},rl=()=>{Ms.resume(),Zc(),tl()},il=(e=!1)=>{nr()&&el()&&Ms.isFollowing()&&(e||ms)&&(Ls!==null&&(cancelAnimationFrame(Ls),Ls=null),Hs=!0,Ls=requestAnimationFrame(()=>{Ls=null,Hs=!1,Ms.isFollowing()&&ol(Hc(),e?220:140)}))},al=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(Uc(),Math.abs(o)<1){zs=!0,e.scrollTop=a,Ns=e.scrollTop,zs=!1;return}let s=performance.now();zs=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){Uc();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,Ns=e.scrollTop,p<1?Vc=requestAnimationFrame(l):(e.scrollTop=a,Ns=e.scrollTop,Vc=null,zs=!1)};Vc=requestAnimationFrame(l)},ol=(e,t=500)=>{let n=Dt(e)-e.scrollTop;Math.abs(n)<1?Ns=e.scrollTop:Math.abs(n)>=80?(Uc(),zs=!0,e.scrollTop=Dt(e),Ns=e.scrollTop,zs=!1):al(e,()=>Dt(e),t,()=>Ms.isFollowing())},sl=()=>{if(!el()){tl();return}let e=Hc();zs=!0,e.scrollTop=Dt(e),Ns=e.scrollTop,zs=!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 zs=!0,z.scrollTop=i,Ns=z.scrollTop,zs=!1,tr()===`follow`&&!Mt(z,24)&&Ms.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))},pl=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},ml=()=>{if(!Ws||Ws.spacerHeight<=0)return;let e=pl(Ws.spacerHeight),t=Math.max(0,Math.round(z.scrollTop)+z.clientHeight-e+24);t<Ws.spacerHeight&&(fl(t),tl())},hl=()=>{Gs!==null&&(cancelAnimationFrame(Gs),Gs=null),Uc(),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,`\\"`),vl=e=>z.querySelector(`[data-message-id="${_l(e)}"]`),yl=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=pl(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)})},bl=()=>{if(tr()!==`anchor-top`||!Ws||!Zs)return;let e=vl(Zs);if(!e)return;Uc();let t=Ws.spacerHeight,n=pl(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),zs=!0,z.scrollTop=r,Ns=z.scrollTop,zs=!1,tl()},Cl=()=>{if(nr()){if(!Ms.isFollowing()||Mt(z,1))return;il(!ms)}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()}},wl=e=>{let t=tr();t===`follow`?(rl(),il(!0)):t===`anchor-top`&&(Ys=!1,Xs=!0,Qs=!1,Zs=e,yl(e))},Tl=()=>{tr()===`anchor-top`&&(Xs?Ys=!1:(Ys=!0,hl(),rl(),il(!0)))},El=e=>{if(Js===null)return!0;let t=vl(Js),n=vl(e);if(!t||!n)return!0;let r=cl(n)-cl(t);return rr()+r>z.clientHeight-96},Al=e=>{if(tr()!==`anchor-top`||!Xs||Qs||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||!El(n.id))return;Zs=n.id,yl(n.id);return}},jl=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`||or())&&$c()&&(Us+=1,Xc(),tl(),yr(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)})},Ml=(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`)},Fl=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),Ml(n,t),n},Il=(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?Sr(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),Ss===t.id&&Cs){let e=Fl(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:Cs.element};return}let r=h&&Je(t),o=b&&t.variant===`approval`&&!!t.approval,f=!r&&t.role===`assistant`&&!t.variant&&y&&cu(t);!o&&xs.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),xs.delete(t.id)),!f&&vs.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),vs.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&&Cr(t),canQuote:T&&!t.variant&&(t.content?.trim().length??0)>0},O=`${D.canRegenerate?`r`:``}${D.canEdit?`e`:``}${D.canQuote?`q`:``}`,ee=no(t,Os)+S+`:${O}`,ne=r||o||f?null:io(hs,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){_s.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=_s.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=Fl(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(Fl(t.id,t.role));return}let r=g.find(e=>typeof e.renderApproval==`function`)??k,a=xs.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`),xs.delete(t.id),re=n.createApprovalBubble(t,c,p);else{let e=Fl(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:()=>cc(t,c,d),config:c})}else if(t.variant===`tool`&&t.toolCall&&ie.renderToolCall){if(!pt)return;re=ie.renderToolCall({message:t,defaultRenderer:()=>vc(t,c,u),config:c})}else ie.renderMessage&&(re=ie.renderMessage({message:t,defaultRenderer:()=>{let e=gs(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=lu(t);if(r){let a=vs.get(t.id),o=a!==ee,s=c.wrapComponentDirectiveInBubble!==!1&&Ee.getOptions(r.component)?.bubbleChrome!==!1,l=null;if(o){let i=ou(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&&Lc()?.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=Fl(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=cc(t,c,d)}else if(t.variant===`tool`&&t.toolCall){if(!pt)return;re=vc(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}):gs(t,n,e,c.messageActions,mn,{loadingIndicatorRenderer:a,widgetConfig:c,actionEligibility:D}),t.role!==`user`&&re&&_e(re,t,c,Q)}}let oe=Fl(t.id,t.role);oe.appendChild(re),ao(hs,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=Fl(`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),oo(hs,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(ms&&t.some(e=>e.role===`user`)&&!re&&!se){let e={config:c,streaming:!0,location:`standalone`,defaultRenderer:os},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=os()),n){let e=document.createElement(`div`),t=c.loadingIndicator?.showBubble!==!1,r=c.layout?.messages?.layout??`bubble`;e.className=t?us(`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=Fl(`typing-indicator`,`assistant`);a.appendChild(e),i.appendChild(a)}}if(!ms&&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=Fl(`idle-indicator`,`assistant`);t.appendChild(e),i.appendChild(t)}}if(Dn(i),Qa(e,i),On(e),E){let{messageId:t,element:n}=E,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(Ml(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&&(Ml(i,l.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())s.has(e)||_s.delete(e);if(v.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of v){let i=e.querySelector(`#wrapper-${t}`);i&&(Ml(i,l.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())s.has(e)||vs.delete(e);if(x.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of x){let i=e.querySelector(`#wrapper-${t}`);i&&(Ml(i,l.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),xs.set(t,n)))}if(xs.size>0)for(let e of xs.keys())s.has(e)||xs.delete(e)},Rl=!1,Bl=()=>{Rl||(Rl=!0,Mn().catch(()=>{}),we().catch(()=>{Rl=!1}))},Hl=(e,t,n)=>{t.length>0&&Bl(),Il(e,t,n),pa()},Ul=null,Wl=()=>{if(Ul)return;let e=e=>{let t=e.composedPath();t.includes(F)||Cn&&t.includes(Cn)||uu(!1,`user`)};Ul=e,(t.ownerDocument??document).addEventListener(`pointerdown`,e,!0)},Kl=()=>{Ul&&=((t.ownerDocument??document).removeEventListener(`pointerdown`,Ul,!0),null)};Z.push(()=>Kl());let ql=null,Jl=()=>{if(ql)return;let e=e=>{e.key===`Escape`&&(e.isComposing||uu(!1,`user`))};ql=e,(t.ownerDocument??document).addEventListener(`keydown`,e,!0)},Xl=()=>{ql&&=((t.ownerDocument??document).removeEventListener(`keydown`,ql,!0),null)};Z.push(()=>Xl());let Zl=!1,$l=/* @__PURE__ */ new Set,eu=()=>c.launcher?.composerBar?.peek?.streamAnimation||c.features?.streamAnimation,tu=()=>{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=eu(),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),Qa(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)}Qa(n,s),l.onAfterRender?.({container:n,bubble:e,messageId:i.id,message:i,speed:c.speed,duration:c.duration})}}let h=ms||Zl;e.classList.toggle(`persona-pill-peek--visible`,h)};if(N()){let e=L.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),uu(!0,`user`)};e.addEventListener(`pointerdown`,t),Z.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{Zl||(Zl=!0,tu())},n=()=>{Zl&&(Zl=!1,tu())};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 nu=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&&Bl(),!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`),nu(P),R.style.display=P?`flex`:`none`,_a(),P?(Wl(),Jl()):(Kl(),Xl()),tu();return}let e=go(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=vo(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`:``))},uu=(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=go(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=uo(n,c.launcher?.zIndex??1e5))}Ro||=mo(t.ownerDocument)}else P||(Lo?.(),Lo=null,Ro?.(),Ro=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()})},gu={inputDisabled:!1,sendDisabled:!1},Tu=()=>gu.inputDisabled,Du=()=>Sn(c.voiceRecognition?.provider)&&!!Q&&(Q.isBargeInActive()||[`listening`,`processing`,`speaking`].includes(Q.getVoiceStatus())),Ou=()=>gu.inputDisabled||gu.sendDisabled,ku=()=>(gu.inputDisabled?gu.inputReason:void 0)??(gu.sendDisabled?gu.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(mu,!!e)}else if(e)U.setAttribute(`role`,`status`),U.setAttribute(`aria-live`,`polite`),U.setAttribute(mu,``),U.removeAttribute(hu),U.textContent=e,i(U,c.statusIndicator??{},`idle`);else if(U.hasAttribute(mu)&&(U.removeAttribute(`role`),U.removeAttribute(`aria-live`),U.removeAttribute(mu),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);gu={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`)),qn&&(qn.disabled=r),Yn&&(Yn.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=Fs(e);if(n===Tr)return;Tr=n,t.setAttribute(`data-persona-conversation-state`,n);let r=Dr();Ar(),Bu&&(Vu?.cancel(),Vu=As(G,n===`active`?r:Dr(),n===`active`?`drop`:`rise`,wr().layout===`centered`?320:260)),bl()},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,bs({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,Ds(Nn,t.message,c));let i=e??(Q?Q.getMessages():c.initialMessages);Hu(i);let a=Lu,o=!a&&Is(t,i),s=o!==Ru;if(Ru=o,Ku){zu?.cancel(),zu=null,a!==qu&&(qu=a,a?Ts(z,An,null):ws(z,An,Ku)),ys(z,An,!a);return}if(s&&!o&&!a&&t.dismiss===`on-first-message`&&Bu){zu=ks(An,e=>{zu===e&&(zu=null),!Ru&&!Ku&&(ys(z,An,!1),bl()),e?.cancel()});return}if(zu){if(!o&&!a)return;zu.cancel(),zu=null}let l=!An.hidden;ys(z,An,o),!o&&l&&bl()},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=bo(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=wo({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(),Ts(z,An,Ku),Ku=null,qu=!1;let t=Q?Q.getMessages():c.initialMessages,n=Is(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,ws(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=Bi(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=>Yl(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&&!iu()?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&&!cu(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}Hl(B,e,ut),Lc()?.updateInlineArtifactBlocks(B,xa.artifacts,{suppressTransition:ms}),_d(),Ju(e),ds(e),il(!ms),jl(e),e.length===0&&(hl(),Ys=!0,Xs=!1,Zs=null,Qs=!1),!Ks||qs?(Ks=!0,Js=t?.id??null,ec=n?.id??null):t&&t.id!==Js?(Js=t.id,wl(t.id)):n&&n.id!==ec&&Tl(),n&&(ec=n.id),Al(e);let r=$.lastUserMessageId;t&&t.id!==r&&($.lastUserMessageId=t.id,be.emit(`user:message`,t)),$.lastUserMessageWasVoice=!!t?.viaVoice,Dd(e),tu()},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;ms&&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 Ur(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()),ms=e,Pu(e),fn(),Q&&Hl(B,Q.getMessages(),ut),e||(il(!0),ml(),cs=!0,Q&&ls(Q.getMessages(),Xe(c))),tl(),yr(e?`Responding…`:`Response complete.`),tu()},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(!uc){let e=Q.getVoiceDisclosure();e&&(uc=!0,N()?(dc=V.placeholder,V.placeholder=e,yr(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,uc=!1,dc!==null&&(V.placeholder=dc,dc=null),sp(),gc(`system`),hc||yc())}},onArtifactsState(e){xa=e,e.artifacts.length===0&&(Ta=!1),Lc()?.updateInlineArtifactBlocks(B,e.artifacts,{suppressTransition:ms}),So(),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||ms),Nd?.syncEarlierMessagesPill()},dn=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(hs.clear(),hl(),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 ms},jumpToBottomInstant:sl,get lastAppliedMessages(){return Sd},set lastAppliedMessages(e){Sd=e},get launcherEnabled(){return He},get launcherSurfaceInstance(){return Sp},maybeFocusInput:Fu,messageCache:hs,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:bl,resetAnchorState:hl,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:au,historyErrors:{HistoryClientError:Xn,HistoryProviderError:vt},isDockedMountMode:go,renderLucideIcon:M,loadHistoryView:Ql,createHeaderIconButton:Ao,attachTooltip:n},Kd=e=>(!Nd&&!Fd&&(Nd=e.createHistoryShell(Gd),Nd.railCollapseShortcut()&&zd()),Nd),qd=()=>{if(Nd)return Promise.resolve(Nd);let e=iu();return e?Promise.resolve(Kd(e)):(Pd??=ru().then(Kd,e=>{throw Pd=null,e}),Pd)},Jd=e=>{let t=iu(),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=xu(e.metadata),Ve.syncFromMetadata()),e.messages?.length){qs=!0;try{Q.hydrateMessages(e.messages)}finally{qs=!1}Bl()}e.artifacts?.length&&Q.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),Fc(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Bu=!0,ke(),rf()}):(Fc(Pe),rf());let af=()=>{N()&&(P||(c.launcher?.composerBar?.expandOnSubmit??!0)&&uu(!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),Eu(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){yr(e),!N()&&U&&(U.hasAttribute(mu)||(U.setAttribute(hu,``),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(hu)&&(U.removeAttribute(hu),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&&Hr(e.options.activeModeIds),e.options.quote&&Zr(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(!Qi({text:i,hasAttachments:(q?.hasAttachments()??!1)||(a?.length??0)>0,attachmentsReady:q?.isReady()??!0,hasMentions:Pr?.hasMentions()??!1,hasServerMentions:!!r,inputDisabled:Tu(),sendDisabled:Ou()}))return;let o=Q.isStreaming()?ei():`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=()=>{Es(),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=zi(d,c.composer?.modes);f.length!==d.length&&Hr(f),J.getState().quote&&Zr(void 0),Bc(),ea.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=ta(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(Zi({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&&Zr(void 0),Bc(),ea.release(),ra(),yr(`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&&Cr(t)&&Ss!==e&&(Es(),Ss=e,Cs=Wi({messageId:e,initialText:t.content,onSave:t=>bf(e,t),onCancel:()=>Es()}),hs.delete(e),Hl(B,Q.getMessages(),ut),Cs.focus())}function bf(e,t){let n=Cs;Ss=null,Cs=null,n?.destroy(),hs.delete(e),Q.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?bl():Hl(B,Q.getMessages(),ut)}function xf(e){if(Q.isStreaming())return;let t=xr(Q.getMessages(),e);t&&(Es(),Q.resubmitFrom(t,{reason:`retry`})&&bl())}ma={regenerate:xf,edit:yf,quote:e=>{let t=Q.getMessages().find(t=>t.id===e)?.content?.trim();t&&(Zr({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={...eo},Of=!1,kf=()=>{Df={...eo}},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&&!Tu()&&(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=to({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(),ei()===`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||Tu())return;let t=_u(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),gc(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,gc(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=Mr();n?t(n):jr().then(t,()=>{})},ip=()=>rp(e=>e.recording()),ap=()=>rp(e=>e.processing()),op=()=>rp(e=>e.speaking()),sp=()=>rp(e=>e.reset()),cp=()=>{if(!Tu()){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(),gc(`user`),sp()});return}Q.toggleVoice().then(()=>{$.active=mc(),$.manuallyDeactivated=!$.active,yc(),gc(`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`)}};oi=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(),gc(`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=()=>{uu(!P,`user`)},Sp=null,Cp=null;if(He&&!N()){let{instance:e,element:t}=nc({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()),bc(),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=br(),Dp=()=>{if(N()){Or(),su();return}let e=go(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){_a(),ya=xo();return}let t=!1;rt&&(rt=!1,_a(),t=!0);let r=xo();if(!t&&r!==ya&&(_a(),t=!0),ya=r,t&&Ha(),!He&&!e){I.style.height=``,I.style.width=``;return}if(!n&&!e){let e=Rs(c);I.style.width=e.width,I.style.maxWidth=e.maxWidth}ho(),Po()}finally{Or(),Ar();let e=br();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=go(c)&&r&&e,a=n||r&&e&&He||i;if(a&&!Ro){let e=t.getRootNode(),n=e instanceof ShadowRoot?e.host:t.closest(`.persona-host`);n&&!Lo&&(Lo=uo(n,c.launcher?.zIndex??1e5)),Ro=mo(t.ownerDocument)}else a||(Lo?.(),Lo=null,Ro?.(),Ro=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(()=>{Ar()}),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)),Ns=z.scrollTop;let kp=Dt(z),Ap=()=>{jo();let e=z.scrollTop,t=Dt(z),n=t<kp;if(kp=t,!nr()){Ns=e,tl();return}let{action:r,nextLastScrollTop:i}=Et({following:Ms.isFollowing(),currentScrollTop:e,lastScrollTop:Ns,nearBottom:Mt(z,24),userScrollThreshold:4,isAutoScrolling:zs||Hs||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});Ns=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()&&Ms.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)&&($s(),ar()&&nr()&&Ms.isFollowing()&&nl())},Fp=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&($s(),ar()&&nr()&&Ms.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&&$s(),!nr())return;let t=Ot({following:Ms.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`,$s,{passive:!0}),z.addEventListener(`pointerdown`,$s,{passive:!0}),Z.push(()=>{z.removeEventListener(`touchmove`,$s),z.removeEventListener(`pointerdown`,$s)}),Z.push(()=>z.removeEventListener(`wheel`,Ip)),dr.addEventListener(`click`,()=>{hl(),z.scrollTop=z.scrollHeight,Ns=z.scrollTop,rl(),il(!0),tl()}),Z.push(()=>dr.remove()),Z.push(()=>{Jc(),hl()});let Lp=()=>{W&&(Zo&&=(W.removeEventListener(`click`,Zo),null),at()?(W.style.display=``,Zo=()=>{uu(!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`),hs.clear(),rl(),Ke(L.composerOverlay);try{localStorage.removeItem(pu),c.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${pu}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(c.clearChatHistoryStorageKey&&c.clearChatHistoryStorageKey!==pu)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),Zr(void 0),Es(),qt?.clear(),Jt?.reset(),Qt?.update()})})();let Rp=[[`keydown`,Pf],[`input`,Mf],[`input`,Fr],[`input`,Ir],[`keyup`,Ir],[`paste`,If],[`focus`,Ci]],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()?Wo({config:c}):Ho({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(),Si(),wi(),Hp(),Pi(),Ii(),$i(),Vp();let s=Xo.indexOf(qo);if(qo.destroy(),qo=To(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`),_a(),Tp(),Or(),ra(),ju(),n&&V?.focus()}finally{Up=!1}}}let Gp=t.ownerDocument??document;Gp.addEventListener(`keydown`,Ff,!0);let Kp=()=>{Pc()},qp=()=>{Gp.visibilityState===`hidden`&&Pc()};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&&!Tu(),Qp=e=>{vu(e.dataTransfer)&&Zp()&&(Yp++,Yp===1&&R.classList.add(Jp))},$p=e=>{vu(e.dataTransfer)&&Zp()&&(Yp--,Yp<=0&&Xp())},em=e=>{vu(e.dataTransfer)&&Zp()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},tm=e=>{if(!vu(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(),Ei?.destroy(),Ei=null,qr?.destroy(),qr=null,Xr?.destroy(),Xr=null,ni?.destroy(),ni=null,Gr=null,Kr=null,Pc(),Mc.destroy(),df&&clearTimeout(df),Es(),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=Nl({...c,features:h},a),h=c.features,c=gl(c),m(),Co(),Ka(t,c),Gc(t,c),Kc(t,c),ln(),So(),c.colorScheme!==d&&Bo();let O=kl.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()&&(hl(),rl()),ic(),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=No.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}=nc({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?Vo(c,te,{showClose:at(),onClose:()=>uu(!1,`user`)}):Fo({config:c,showClose:at(),onClose:()=>uu(!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`),Or(),tl(),He===tt?We!==$e&&uu(We,`auto`):He?uu(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&&(Os++,Hl(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||No.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=``),ko(W,A.closeButtonIconName??`x`,{iconSize:N()?Bs: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||No.actionIconColor,ko(Se,e.iconName??`refresh-cw`,{iconSize:N()?Vs: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:[Ll],Te=c.actionHandlers&&c.actionHandlers.length?c.actionHandlers:[zl.message,zl.messageAndClick];Ve=Vl({parsers:we,handlers:Te,getSessionMetadata:Le,updateSessionMetadata:Re,emit:be.emit,documentRef:typeof document<`u`?document:null}),ut=Cu(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(()=>{}),Hl(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=Tu()||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=Tu()||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(!Jn||!qn){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)),Yn||(Yn=document.createElement(`input`),Yn.type=`file`,Yn.accept=(e.allowedTypes??lt).join(`,`),Yn.multiple=(e.maxFiles??4)>1,Yn.style.display=`none`,Yn.setAttribute(`aria-label`,`Attach files`),(V.parentElement??kn).insertBefore(Yn,V)),Jn=j(`div`,`persona-send-button-wrapper`),qn=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}`),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 r=M(t,24,`currentColor`,1.5);r?qn.appendChild(r):qn.textContent=`📎`,qn.addEventListener(`click`,e=>{e.preventDefault(),Yn?.click()}),Jn.appendChild(qn);let i=e.buttonTooltipText??`Attach file`;n({anchor:qn,trigger:Jn,text:()=>qn?.getAttribute(`aria-label`)??i}),Hn?Hn.append(Jn):kn.appendChild(Jn),Y&&(Y.attachmentButton=qn,Y.attachmentInput=Yn??void 0,Y.attachmentPreviews=Zn??void 0),!q&&Yn&&Zn&&(q=Yr.fromConfig(e,Rr),q.setPreviewsContainer(Zn),Y?.addListener(Yn,`change`,async()=>{q&&Yn?.files&&(await q.handleFileSelect(Yn.files),Yn.value=``)}))}else{Jn.style.display=``;let e=c.attachments??{};Yn&&(Yn.accept=(e.allowedTypes??lt).join(`,`),Yn.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(wu(c.attachments?.dropOverlay)),qn){let e=c.attachments??{},t=e.buttonTooltipText??`Attach file`;qn.setAttribute(`aria-label`,t),qn.textContent=``;let r=M(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);r?qn.appendChild(r):qn.textContent=`📎`,Jn&&n({anchor:qn,trigger:Jn,text:()=>qn?.getAttribute(`aria-label`)??t})}}else Jn&&(Jn.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(),Mo();let Ue=Ri(J.getState().activeModeIds,c.composer?.modes);J.setActiveModeIds(Ue),Br().length>0!=!!qr&&Ii(),qr?.render(Ue,Br());for(let e of[...Jr.keys()])Ni(e,c.composer?.modeGroups)||Jr.delete(e);Jr.forEach(e=>e.repaint()),Gr?.repaint(),Ei?.resolve();let Ge=Ja(c,N());if(Do(),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()&&uu(!0,`api`)},close(){at()&&uu(!1,`api`)},toggle(){at()&&uu(!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`),hs.clear(),rl();try{localStorage.removeItem(pu),c.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${pu}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(c.clearChatHistoryStorageKey&&c.clearChatHistoryStorageKey!==pu)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),Zr(void 0),Es(),qt?.clear(),Jt?.reset(),Qt?.update()},setMessage(e){return!V||Q.isStreaming()||Tu()?!1:(!P&&at()&&uu(!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()&&uu(!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&&Zr({...e,text:t})},clearQuote(){Zr(void 0)},startVoiceRecognition(){return Q.isStreaming()?!1:Sn(c.voiceRecognition?.provider)?(Q.isVoiceActive()||Q.isBargeInActive()||(!P&&at()&&uu(!0,`system`),$.manuallyDeactivated=!1,yc(),Q.toggleVoice().then(()=>{$.active=mc(),yc(),gc(`user`),$.active&&ip()})),!0):Rf?!0:$f()?(!P&&at()&&uu(!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(),gc(`user`),sp()}),!0):Rf?($.manuallyDeactivated=!0,yc(),tp(`user`),!0):!1},injectMessage(e){return!P&&at()&&uu(!0,`system`),Q.injectMessage(e)},injectAssistantMessage(e){!P&&at()&&uu(!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()&&uu(!0,`system`),Q.injectUserMessage(e)},injectSystemMessage(e){return!P&&at()&&uu(!0,`system`),Q.injectSystemMessage(e)},injectMessageBatch(e){return!P&&at()&&uu(!0,`system`),Q.injectMessageBatch(e)},injectComponentDirective(e){return!P&&at()&&uu(!0,`system`),Q.injectComponentDirective(e)},injectTestMessage(e){!P&&at()&&uu(!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(){zc(c)&&(Sa=!1,Ta=!0,So(),X?.setMobileOpen(!0))},hideArtifacts(){zc(c)&&(Sa=!0,So())},upsertArtifact(e){return zc(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){zc(c)&&Q.selectArtifact(e)},clearArtifacts(){zc(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){ps(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()&&uu(!0,`system`);let t=B.querySelector(`.persona-feedback-container`);t&&t.remove();let n=du({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()&&uu(!0,`system`);let t=B.querySelector(`.persona-feedback-container`);t&&t.remove();let n=fu({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=yu(c.persistState);if(om&&at()){let e=bu(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)),tu(),!js){let e=Se(()=>{Q&&(Os++,hs.clear(),Hl(B,Q.getMessages(),ut))});Z.push(e)}oe=()=>{Q&&(Os++,hs.clear(),Hl(B,Q.getMessages(),ut))},Q.getMessages().length>0&&Bl(),he=()=>{Q&&(Os++,hs.clear(),Hl(B,Q.getMessages(),ut))};let sm=ge(()=>{Q&&(Os++,hs.clear(),Hl(B,Q.getMessages(),ut))});Z.push(sm);let cm=Rc(()=>{Q&&(Os++,hs.clear(),Hl(B,Q.getMessages(),ut),Lc()?.updateInlineArtifactBlocks(B,xa.artifacts,{suppressTransition:!0}),So())});return Z.push(cm),am},Ou=(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},ku=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},Au=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},ju=(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.")},Mu=(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`},Nu=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=``},Pu=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,Nu(e)},Fu=e=>{e.style.transition=``},Iu=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=``},Lu=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},Ru=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},zu=(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))},Bu=(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)},Vu=e=>{let t=Wa(e),n=t.components?.panel,r=(e,n)=>e==null||e===``?n:va(t,e)??e;return{inset:r(n?.inset,ia),canvasBackground:r(n?.canvasBackground,aa)}},Hu=(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=``)},Uu=(e,t,n,r,i,a,o,s)=>{let c=vo(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;zu(e,t,n,r,l),Bu(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`),Iu(t),Fu(r),Pu(r),Lu(n),Ru(i,r),Hu(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`),Pu(r),ku(r,c.maxHeight),Hu(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`,Iu(t),Fu(r),Lu(n),Ru(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`,Fu(r),Nu(r),Ru(i,r);let a=Ou(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=``,Iu(t),Nu(r),Lu(n),Ru(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`,Au(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(${Ou(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`}}},Wu=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return Mu(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){Mu(n,e)},destroy(){n.remove()}}},Gu=(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?Vu(t):null};h();let g=()=>{Uu(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=qa(()=>{h(),g()}))},y=()=>{p(),vo(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,ju(o,vo(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),vo(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()}}},Ku=(e,t)=>go(t)?Gu(e,t):Wu(e,t),qu={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Ju=`persona-preview-shell-theme`,Yu={load:()=>null,save:()=>{},clear:()=>{}},Xu=[`How do I get started?`,`Pricing & plans`,`Talk to support`];function Zu(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function Qu(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 $u(e){let t=Qu(e);return`* { box-sizing: border-box; }
|
|
121
|
+
${j?`background: transparent !important;`:``}
|
|
122
|
+
`)}if(!o&&!n){let e=r?``:`padding-top: 1.25em !important;`,t=r?``:`z-index: ${i.launcher?.zIndex??1e5} !important;`;L.style.cssText+=`max-height: -moz-available !important; max-height: stretch !important;`+e+t}Or(),_e()},bo=()=>{t.style.setProperty(`--persona-content-max-width`,$a(i,F()))},So=!1;function Eo(){i.layout?.topFade&&V.scrollTop>1?V.setAttribute(`data-persona-top-fade`,`true`):V.removeAttribute(`data-persona-top-fade`)}let Oo=()=>{Eo();let e=eo(i,F());F()&&i.composer?.placement&&i.debug===!0&&!So&&(So=!0,console.warn(`[persona] composer.placement is ignored in composer-bar mount mode.`));let n=br();t.setAttribute(`data-persona-composer-placement`,e),t.setAttribute(`data-persona-conversation-state`,xr),t.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`),t.style.setProperty(`--persona-composer-anchor-gap`,n.composerGap??`24px`),kr()},ko=()=>{if(F())return;let e=Co(i),n=i.launcher?.sidebarMode??!1;if(e||n||(i.launcher?.fullHeight??!1)||!ze)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=Gs(i);R.style.height=s.height,R.style.maxHeight=s.maxHeight};yo(),Za(t,i),Qc(t,i),$c(t,i),bo(),Oo(),va=()=>{yo(),ko(),Za(t,i),Qc(t,i),$c(t,i),bo(),Oo(),ba?t.style.setProperty(`--persona-artifact-welded-outer-radius`,ba):t.style.removeProperty(`--persona-artifact-welded-outer-radius`),cn(),sn()};let Z=[];Z.push(()=>{ga=!0}),Z.push(()=>{m.forEach(e=>e()),p.destroy()}),Z.push(()=>{document.removeEventListener(`keydown`,La)}),Z.push(()=>{gr!==null&&clearTimeout(gr)});let No=null,Po=null;Z.push(()=>{No?.(),No=null,Po?.(),Po=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()}),dt&&Z.push(()=>{Dt=!0,Tt=null,Qt!==null&&(cancelAnimationFrame(Qt),Qt=null),Yt?.destroy(),Yt=null,xt?.destroy(),xt=null,vt=null});let Lo=null,Ro=()=>{Lo&&=(Lo(),null),i.colorScheme===`auto`&&(Lo=Qa(()=>{Za(t,i)}))};Ro(),Z.push(()=>{Lo&&=(Lo(),null)}),Z.push(()=>{E=!0,T?.()}),Z.push(()=>{re=!0});let Bo=!1;Z.push(()=>{Bo=!0});let Vo=(e,n)=>{let r=Vt(e,n);return r||!Kt.includes(e)?r:(_o().then(r=>{if(Bo)return;Gt(r.wipe),Gt(r.glyphCycle);let i=Vt(e,n);i&&Ut(i,t)}).catch(()=>{}),null)},Wo=i.features?.streamAnimation;if(Wo?.type&&Wo.type!==`none`){let e=Vo(Wo.type,Wo.plugins);e&&Ut(e,t),Z.push(()=>Rt(t))}let Go=jo(Tn),Ko=jo(Cn),qo=jo(wn),Xo=[Go,Ko,qo];Z.push(()=>{Xo.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(tt(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(tt)||(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,U,t)},r=e=>{Xo.forEach(t=>{t!==e&&n(t)})};$o&&(rs(t)>ts||is(t)!==ns)&&($o=null);let a=$e(i);ls(t,a);let o=a.enabled?et(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`?F()?`composer`:`after-message`:n)===`after-message`?qo:Go;r(a),a.render(s,Q,U,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:wf});return}if(t.some(e=>e.role===`user`)){Xo.forEach(n);return}let l=i.future?.v5Defaults===!0,u=yr(),d=i.suggestions?.starters??(l?{}:void 0);if(d){let e=Us(br(),t),a=d.placement??`auto`,o=a===`auto`?e?`welcome`:`composer`:a;if(o===`welcome`&&!e){os(),Xo.forEach(n);return}let s=o===`welcome`?Ko:Go;r(s),s.render(d.items??i.suggestionChips,Q,U,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:wf})}else r(Go),Go.render(i.suggestionChips,Q,U,t,i.suggestionChipsConfig,{surface:`starter`,variant:`chip`,behavior:`send`,overflow:`wrap`,maxItems:4,config:i,plugins:f,submitPrompt:wf})},ds=()=>{$o&&($o=null,us())},fs=e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length){ds();return}let n=Q?Q.getMessages():[];$o=t,es=!0,ts=rs(n),ns=is(n),us(n)},ms=!1,hs=uo(),gs=/* @__PURE__ */ new Set,vs=/* @__PURE__ */ new Map,ys=/* @__PURE__ */ new Map,bs=/* @__PURE__ */ new Map,xs=/* @__PURE__ */ new Map,Ss=null,ws=null;function Ts(){if(!Ss)return;let e=Ss;Ss=null,ws?.destroy(),ws=null,hs.delete(e),B.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),Q&&Hl(H,Q.getMessages(),ct)}let Os=0,ks=Le()!==null,As=Ft(),Ns=0,Fs=null,Rs=!1,zs=!1,Bs=0,Ws=null,Ks=null,Ys=!1,Xs=!1,Zs=null,Qs=!0,$s=!1,ec=null,tc=!1,nc=()=>{tc=!0,oc()},rc=null,ic=null,ac=()=>{t.setAttribute(`data-persona-scrollbar`,sr()),sr()!==`on-scroll`&&(ic!==null&&clearTimeout(ic),ic=null,V.removeAttribute(`data-persona-scrollbar-visible`))},oc=()=>{sr()===`on-scroll`&&(V.setAttribute(`data-persona-scrollbar-visible`,``),ic!==null&&clearTimeout(ic),ic=setTimeout(()=>{ic=null,It(V,24)&&V.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};ac(),Z.push(()=>{ic!==null&&clearTimeout(ic)});let sc=/* @__PURE__ */ new Map,uc=!1,dc=null,$={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Vi();let hc=i.voiceRecognition?.autoResume??!1,gc=()=>Q.isVoiceActive()||Q.isBargeInActive(),_c=!1,vc=e=>{k.emit(`voice:state`,{active:$.active,source:e,timestamp:Date.now()})},bc=()=>{Me(e=>({...e,voiceState:{active:$.active,timestamp:Date.now(),manuallyDeactivated:$.manuallyDeactivated}}))},xc=()=>{if(i.voiceRecognition?.enabled===!1)return;let e=ku(de.voiceState),t=!!e.active,n=Number(e.timestamp??0);$.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-n<3e4&&setTimeout(()=>{$.active||($.manuallyDeactivated=!1,Sn(i.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=gc(),vc(`restore`),$.active?ap():(bc(),pf(`Tap the mic to resume your voice call`,1e4))}):tp(`restore`))},Sn(i.voiceRecognition?.provider)?0:1e3)},Sc=e=>{_c=!e.persisted,$.active&&bc()};typeof window<`u`&&(window.addEventListener(`pagehide`,Sc),Z.push(()=>window.removeEventListener(`pagehide`,Sc)));let Cc=()=>Q?Au(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(!ue?.save)return;let t=e?Au(e):Q?Cc():[],n=j&&Q?.getResumableHandle();n&&(de={...de,durableResume:{executionId:n.executionId,after:n.lastEventId}});let r={messages:t,metadata:de,artifacts:xa.artifacts,selectedArtifactId:xa.selectedId,...Mc?{draft:Mc}:{}};Oc(()=>ue.save(r),`[AgentWidget] Failed to persist state:`)}let Mc,Nc=()=>!ue?.save||i.persistState===!1?!1:typeof i.persistState!=`object`||i.persistState.persist?.draft!==!1,Fc=Qi({write:()=>{if(!Nc())return;let e=Y.getState(),t=Xi({text:e.text,mentionRefs:e.mentionRefs,contentSegments:cf(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(Mc)&&(Mc=t,kc())}});function Ic(){Nc()&&Fc.schedule()}function Lc(){Fc.flush()}function Rc(e){if(!Nc())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&&(Mc=e,U&&!U.value&&(U.value=t.text,U.dispatchEvent(new Event(`input`,{bubbles:!0})),Fr()),t.selectedModelId&&(Y.setSelectedModelId(t.selectedModelId),Wr?.repaint()),Hr(t.activeModeIds??[]),t.quote&&Xr(t.quote),Fc.cancel())}function zc(){Fc.cancel(),Mc&&(Mc=void 0,Nc()&&kc())}let Bc=null,Vc=()=>L.querySelector(`#persona-scroll-container`)||V,Hc=()=>{Bc!==null&&(cancelAnimationFrame(Bc),Bc=null),Rs=!1},qc=()=>{Fs!==null&&(cancelAnimationFrame(Fs),Fs=null),zs=!1,Hc()},Jc=()=>ms&&nl()&&(er()!==`anchor-top`||ar()),Yc=()=>{let e=Xn()||`Jump to latest`,t=Jc();cr.toggleAttribute(`data-persona-scroll-to-bottom-streaming`,t),Bs>0?(pr.textContent=String(Bs),pr.style.display=``,cr.setAttribute(`aria-label`,`${e} (${Bs} new)`)):(pr.textContent=``,pr.style.display=`none`,cr.setAttribute(`aria-label`,t?`${e} (response streaming below)`:e))},Xc=()=>{Bs!==0&&(Bs=0,Yc())},tl=()=>{let e=Ws?.spacerHeight??0;return e<=0?It(V,24):gl(e)-V.scrollTop-V.clientHeight<=24},nl=()=>tr()?!As.isFollowing():!tl(),rl=()=>!!Q&&Q.getMessages().length>0,il=()=>{if(!$n()||fn()){cr.parentNode&&cr.remove(),cr.style.display=`none`;return}cr.parentNode!==B&&B.appendChild(cr),Dr();let e=jt(V)>0&&nl()&&rl();e?Yc():Xc(),cr.style.display=e?``:`none`},al=()=>{As.pause()&&(qc(),il())},ol=()=>{As.resume(),Xc(),il()},sl=(e=!1)=>{tr()&&rl()&&As.isFollowing()&&(e||ms)&&(Fs!==null&&(cancelAnimationFrame(Fs),Fs=null),zs=!0,Fs=requestAnimationFrame(()=>{Fs=null,zs=!1,As.isFollowing()&&ll(Vc(),e?220:140)}))},cl=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(Hc(),Math.abs(o)<1){Rs=!0,e.scrollTop=a,Ns=e.scrollTop,Rs=!1;return}let s=performance.now();Rs=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){Hc();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,Ns=e.scrollTop,p<1?Bc=requestAnimationFrame(l):(e.scrollTop=a,Ns=e.scrollTop,Bc=null,Rs=!1)};Bc=requestAnimationFrame(l)},ll=(e,t=500)=>{let n=jt(e)-e.scrollTop;Math.abs(n)<1?Ns=e.scrollTop:Math.abs(n)>=80?(Hc(),Rs=!0,e.scrollTop=jt(e),Ns=e.scrollTop,Rs=!1):cl(e,()=>jt(e),t,()=>As.isFollowing())},ul=()=>{if(!rl()){il();return}let e=Vc();Rs=!0,e.scrollTop=jt(e),Ns=e.scrollTop,Rs=!1,il()},dl=e=>{let t=0,n=e;for(;n&&n!==V;)t+=n.offsetTop,n=n.offsetParent;return t},fl=()=>{let e=V.getRootNode();return(typeof e.getSelection==`function`?e.getSelection():null)??V.ownerDocument.getSelection()},pl=()=>kt(fl(),V),ml=()=>{if(rr()!==`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=V.querySelector(`[data-message-id="${n}"]`);if(!r)return!1;let i=Math.min(Math.max(0,dl(r)-nr()),jt(V));return Rs=!0,V.scrollTop=i,Ns=V.scrollTop,Rs=!1,er()===`follow`&&!It(V,24)&&As.pause(),il(),!0},hl=e=>{let t=Math.max(0,Math.round(e));mr.style.height=`${t}px`,mr.style.display=t>0?``:`none`,Ws&&(Ws.spacerHeight=Math.max(0,e))},gl=e=>{let t=parseFloat(getComputedStyle(V).paddingBottom)||0,n=0;for(let e of Array.from(V.children)){if(e===mr||e.offsetHeight===0)continue;let t=dl(e)+e.offsetHeight;t>n&&(n=t)}let r=V.scrollHeight-e;return n>0?Math.min(n+t,r):r},_l=()=>{if(!Ws||Ws.spacerHeight<=0)return;let e=gl(Ws.spacerHeight),t=Math.max(0,Math.round(V.scrollTop)+V.clientHeight-e+24);t<Ws.spacerHeight&&(hl(t),il())},vl=()=>{Ks!==null&&(cancelAnimationFrame(Ks),Ks=null),Hc(),Ws=null,mr.style.height=`0px`,mr.style.display=`none`},yl=e=>typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),bl=e=>V.querySelector(`[data-message-id="${yl(e)}"]`),xl=e=>{Ks!==null&&cancelAnimationFrame(Ks),Ks=requestAnimationFrame(()=>{Ks=null;let t=yl(e),n=V.querySelector(`[data-message-id="${t}"]`);if(!n)return;let r=dl(n),i=Ws?.spacerHeight??0,a=gl(i),{targetScrollTop:o,spacerHeight:s}=Lt({anchorOffsetTop:r,topOffset:nr(),viewportHeight:V.clientHeight,contentHeight:a,slack:24});Ws={initialSpacerHeight:s,contentHeightAtAnchor:a,spacerHeight:s},hl(s),cl(V,()=>n.isConnected?Math.max(0,dl(n)-nr()):o,220)})},Sl=()=>{if(er()!==`anchor-top`||!Ws||!ec)return;let e=bl(ec);if(!e)return;Hc();let t=Ws.spacerHeight,n=gl(t),{targetScrollTop:r,spacerHeight:i}=Lt({anchorOffsetTop:dl(e),topOffset:nr(),viewportHeight:V.clientHeight,contentHeight:n,slack:24});Ws={initialSpacerHeight:i,contentHeightAtAnchor:n,spacerHeight:i},hl(i),Rs=!0,V.scrollTop=r,Ns=V.scrollTop,Rs=!1,il()},wl=()=>{if(tr()){if(!As.isFollowing()||It(V,1))return;sl(!ms)}else{if(Ws&&Ws.initialSpacerHeight>0){let e=V.scrollHeight-Ws.spacerHeight,t=Nt({initialSpacerHeight:Ws.initialSpacerHeight,contentHeightAtAnchor:Ws.contentHeightAtAnchor,currentContentHeight:e});t!==Ws.spacerHeight&&hl(t)}il()}},Tl=e=>{let t=er();t===`follow`?(ol(),sl(!0)):t===`anchor-top`&&(Qs=!1,$s=!0,tc=!1,ec=e,xl(e))},El=()=>{er()===`anchor-top`&&($s?Qs=!1:(Qs=!0,vl(),ol(),sl(!0)))},Dl=e=>{if(Zs===null)return!0;let t=bl(Zs),n=bl(e);if(!t||!n)return!0;let r=dl(n)-dl(t);return nr()+r>V.clientHeight-96},Al=e=>{if(er()!==`anchor-top`||!$s||tc||pl())return;let t=Zs===null;for(let n of e)if(!t)n.id===Zs&&(t=!0);else if(Pt(n)){if(n.id===ec||!Dl(n.id))return;ec=n.id,xl(n.id);return}},jl=e=>{let t=/* @__PURE__ */ new Map;e.forEach(e=>{let n=sc.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!n&&e.role===`assistant`&&(k.emit(`assistant:message`,e),!Xs&&(er()!==`anchor-top`||ar())&&nl()&&(Bs+=1,Yc(),il(),vr(Bs===1?`1 new message below.`:`${Bs} new messages below.`))),e.role===`assistant`&&(n?.streaming||gs.has(e.id))&&e.streaming===!1&&k.emit(`assistant:complete`,e),e.variant===`approval`&&e.approval&&(n?e.approval.status!==`pending`&&k.emit(`approval:resolved`,{approval:e.approval,decision:e.approval.status}):k.emit(`approval:requested`,{approval:e.approval,message:e}))}),sc.clear(),t.forEach((e,t)=>{sc.set(t,e)}),gs.clear()},Ml=(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`)},Nl=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),Ml(n,t),n},Ll=(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||vn(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=!i.features?.toolCallDisplay?.grouped,p=/* @__PURE__ */ new Set;if(d)for(let t of Array.from(e.children)){let e=t.getAttribute(`data-wrapper-id`);e&&p.add(e)}let m=/* @__PURE__ */ new Map,h=(()=>{let e=f.find(e=>e.renderLoadingIndicator);if(e?.renderLoadingIndicator)return e.renderLoadingIndicator;if(i.loadingIndicator?.render)return i.loadingIndicator.render})(),g=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),_=/* @__PURE__ */ new Set,y=/* @__PURE__ */ new Map,b=/* @__PURE__ */ new Set,S=f.some(e=>e.renderAskUserQuestion),C=[],w=[],T=i.enableComponentStreaming!==!1,E=i.approval!==!1,D=[],O=i.messageActions,ee=O?.showRegenerate===!0&&O.enabled!==!1&&ka.current?.isStreaming()!==!0?Tr(t):null,te=O?.showEdit===!0&&O.enabled!==!1,re=O?.showQuote===!0&&O.enabled!==!1,ie=null,ae=i.features?.reasoningDisplay?.completedVisibility,k=e=>ae===`removed`||ae===`removed-when-short`&&a(e,i.features?.reasoningDisplay?.shortThinkThreshold),se=i.features?.toolCallDisplay?.completedVisibility===`removed`,ce=e=>e.variant===`reasoning`&&e.reasoning?.status===`complete`?k(e.reasoning):se&&e.variant===`tool`&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;if(t.forEach(t=>{if(ce(t))return;if(_.add(t.id),y.set(t.id,t.role),Ss===t.id&&ws){let e=Nl(t.id,t.role);e.setAttribute(`data-persona-message-edit-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(e),ie={messageId:t.id,element:ws.element};return}let r=S&&Ze(t),a=E&&t.variant===`approval`&&!!t.approval,c=!r&&t.role===`assistant`&&!t.variant&&T&&gu(t);!a&&xs.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),xs.delete(t.id)),!c&&bs.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),bs.delete(t.id));let g=Ze(t)?`:${t.agentMetadata?.askUserQuestionAnswered?`a`:`u`}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:``,O={canRegenerate:ee===t.id,canEdit:te&&Er(t),canQuote:re&&!t.variant&&(t.content?.trim().length??0)>0},ae=`${O.canRegenerate?`r`:``}${O.canEdit?`e`:``}${O.canQuote?`q`:``}`,k=lo(t,Os)+g+`:${ae}`,se=r||a||c?null:fo(hs,t.id,k);if(se){if(p.has(t.id)&&vs.get(t.id)===k){let e=document.createElement(`div`);e.id=`wrapper-${t.id}`,e.setAttribute(`data-wrapper-id`,t.id),e.setAttribute(`data-persona-reuse`,`true`),u.appendChild(e)}else u.appendChild(se.cloneNode(!0));d&&m.set(t.id,k),Ze(t)&&t.toolCall?.id&&t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(b.add(t.toolCall.id),Ma(t));return}let A=null,le=f.find(e=>!!(t.variant===`reasoning`&&e.renderReasoning||t.variant===`tool`&&e.renderToolCall||!t.variant&&e.renderMessage)),ue=i.layout?.messages;if(Ze(t)&&t.agentMetadata?.askUserQuestionAnswered===!0){ys.delete(t.id),e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`);return}if(tt(t)&&$e(i).enabled)return;if(Ze(t)&&i.features?.askUserQuestion?.enabled!==!1){let e=f.find(e=>typeof e.renderAskUserQuestion==`function`);if(e&&ka.current){let n=ys.get(t.id),r=n!==k,a=null;if(r){let{payload:n,complete:r}=Qe(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&&(b.add(t.toolCall.id),Ma(t));return}let o=Nl(t.id,t.role);o.setAttribute(`data-ask-plugin-stub`,`true`),o.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(o),C.push({messageId:t.id,fingerprint:k,bubble:a});return}t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(b.add(t.toolCall.id),Ma(t));return}if(a){let n=ne();if(!n){u.appendChild(Nl(t.id,t.role));return}let r=f.find(e=>typeof e.renderApproval==`function`)??x,a=xs.get(t.id)!==k,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`),xs.delete(t.id),A=n.createApprovalBubble(t,i,l);else{let e=Nl(t.id,t.role);e.setAttribute(`data-approval-plugin-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(e),D.push({messageId:t.id,fingerprint:k,bubble:o});return}}else if(le){if(t.variant===`reasoning`&&t.reasoning&&le.renderReasoning){if(!lt)return;A=le.renderReasoning({message:t,defaultRenderer:()=>mc(t,i,s),config:i})}else if(t.variant===`tool`&&t.toolCall&&le.renderToolCall){if(!ut)return;A=le.renderToolCall({message:t,defaultRenderer:()=>Tc(t,i,o),config:i})}else le.renderMessage&&(A=le.renderMessage({message:t,defaultRenderer:()=>{let e=Cs(t,n,ue,i.messageActions,pn,{loadingIndicatorRenderer:h,widgetConfig:i,actionEligibility:O});return t.role!==`user`&&oe(e,t,i,Q),e},config:i}))}if(!A&&c){let r=_u(t);if(r){let a=bs.get(t.id),o=a!==k,s=i.wrapComponentDirectiveInBubble!==!1&&We.getOptions(r.component)?.bubbleChrome!==!1,c=null;if(o){let a=mu(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&&Wc()?.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=Nl(t.id,t.role);e.setAttribute(`data-component-directive-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(e),w.push({messageId:t.id,fingerprint:k,bubble:c});return}}}if(!A){if(t.variant===`reasoning`&&t.reasoning){if(!lt)return;A=mc(t,i,s)}else if(t.variant===`tool`&&t.toolCall){if(!ut)return;A=Tc(t,i,o)}else if(t.variant===`approval`&&t.approval){if(i.approval===!1)return;let e=ne();if(!e)return;A=e.createApprovalBubble(t,i,l)}else{let e=i.layout?.messages;A=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}):Cs(t,n,e,i.messageActions,pn,{loadingIndicatorRenderer:h,widgetConfig:i,actionEligibility:O}),t.role!==`user`&&A&&oe(A,t,i,Q)}}let j=Nl(t.id,t.role);j.appendChild(A),po(hs,t.id,k,j),u.appendChild(j),d&&m.set(t.id,k)}),z.composerOverlay&&z.composerOverlay.querySelectorAll(`[data-persona-ask-sheet-for]`).forEach(e=>{let t=e.getAttribute(`data-persona-ask-sheet-for`);t&&!b.has(t)&&Ye(z.composerOverlay,t)}),i.features?.toolCallDisplay?.grouped){let e=[],n=[],a=i.features.toolCallDisplay.groupedMode===`summary`;t.forEach(t=>{if(t.variant===`tool`&&t.toolCall&&ut){if(se&&t.toolCall.status===`complete`&&!t.toolCall.interrupted)return;n.push(t)}else(t.variant!==`reasoning`||lt&&(t.reasoning?.status!==`complete`||!k(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=Nl(`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=xn(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}`,p=i.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:f,config:i});g(l,p)||(l.textContent=f);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)})})}c.prune(r),mo(hs,_);let A=e=>e.variant===`tool`&&!ut||e.variant===`reasoning`&&!lt||ce(e),le=t.some(e=>e.role===`assistant`&&e.streaming&&!A(e)),ue=t.length-1;for(;ue>=0&&A(t[ue]);)ue--;let j=ue>=0?t[ue]:void 0,de=ue<t.length-1,fe=j?.role===`assistant`&&!j.streaming&&j.variant!==`approval`&&!de;if(ms&&t.some(e=>e.role===`user`)&&!le&&!fe){let e={config:i,streaming:!0,location:`standalone`,defaultRenderer:ps},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=ps()),n){let e=document.createElement(`div`),t=i.loadingIndicator?.showBubble!==!1,r=i.layout?.messages?.layout??`bubble`;e.className=t?_s(`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=Nl(`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=Nl(`idle-indicator`,`assistant`);t.appendChild(e),u.appendChild(t)}}kn(u),ro(e,u),vs=m;for(let t of Array.from(e.querySelectorAll(`:scope > [data-persona-reuse]`))){let e=hs.get(t.getAttribute(`data-wrapper-id`)??``);e?t.replaceWith(e.wrapper.cloneNode(!0)):t.remove()}if(jn(e),ie){let{messageId:t,element:n}=ie,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(Ml(r,y.get(t)??`user`),r.replaceChildren(n))}if(C.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of C){let i=e.querySelector(`#wrapper-${t}`);i&&(Ml(i,y.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())_.has(e)||ys.delete(e);if(w.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of w){let i=e.querySelector(`#wrapper-${t}`);i&&(Ml(i,y.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())_.has(e)||bs.delete(e);if(D.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of D){let i=e.querySelector(`#wrapper-${t}`);i&&(Ml(i,y.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),xs.set(t,n)))}if(xs.size>0)for(let e of xs.keys())_.has(e)||xs.delete(e)},Rl=!1,zl=()=>{Rl||(Rl=!0,Fn().catch(()=>{}),He().catch(()=>{Rl=!1}))},Hl=(e,t,n)=>{t.length>0&&zl(),Ll(e,t,n),ma()},Ul=null,Gl=()=>{if(Ul)return;let e=e=>{let t=e.composedPath();t.includes(L)||_n&&t.includes(_n)||cu(!1,`user`)};Ul=e,(t.ownerDocument??document).addEventListener(`pointerdown`,e,!0)},ql=()=>{Ul&&=((t.ownerDocument??document).removeEventListener(`pointerdown`,Ul,!0),null)};Z.push(()=>ql());let Yl=null,Xl=()=>{if(Yl)return;let e=e=>{e.key===`Escape`&&(e.isComposing||cu(!1,`user`))};Yl=e,(t.ownerDocument??document).addEventListener(`keydown`,e,!0)},Zl=()=>{Yl&&=((t.ownerDocument??document).removeEventListener(`keydown`,Yl,!0),null)};Z.push(()=>Zl());let eu=!1,tu=/* @__PURE__ */ new Set,nu=()=>i.launcher?.composerBar?.peek?.streamAnimation||i.features?.streamAnimation,iu=()=>{if(!F())return;let e=z.peekBanner,n=z.peekTextNode;if(!e||!n)return;if(I){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=nu(),c=zt(s),l=c.type===`none`?null:Vo(c.type,s?.plugins),u=l?.isAnimating?.(i)===!0,d=l!==null&&(o||u);d&&l&&!tu.has(l.name)&&(Ut(l,t),tu.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?Ht(a,c.buffer,l,i,o):a;if(d&&c.placeholder===`skeleton`&&o&&(!m||!m.trim())){let e=document.createElement(`div`),t=Wt();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=Ie(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=qt(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=Bt(),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||eu;e.classList.toggle(`persona-pill-peek--visible`,h)};if(F()){let e=z.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),cu(!0,`user`)};e.addEventListener(`pointerdown`,t),Z.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{eu||(eu=!0,iu())},n=()=>{eu&&(eu=!1,iu())};R.addEventListener(`pointerenter`,t),R.addEventListener(`pointerleave`,n),Z.push(()=>{R.removeEventListener(`pointerenter`,t),R.removeEventListener(`pointerleave`,n)}),_n&&(_n.addEventListener(`pointerenter`,t),_n.addEventListener(`pointerleave`,n),Z.push(()=>{_n.removeEventListener(`pointerenter`,t),_n.removeEventListener(`pointerleave`,n)}))}let au=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=L.style;if(d.left=``,d.right=``,d.top=``,d.bottom=``,d.transform=``,d.width=``,d.maxWidth=``,d.height=``,d.maxHeight=``,_n){let e=_n.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))},su=()=>{if(I&&zl(),!rt())return;if(F()){let e=(i.launcher?.composerBar??{}).expandedSize??`anchored`,t=I?`expanded`:`collapsed`;L.dataset.state=t,L.dataset.expandedSize=e,_n&&(_n.dataset.state=t,_n.dataset.expandedSize=e),L.style.removeProperty(`display`),L.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),R.classList.remove(`persona-scale-95`,`persona-opacity-0`,`persona-scale-100`,`persona-opacity-100`),au(I),B.style.display=I?`flex`:`none`,va(),I?(Gl(),Xl()):(ql(),Zl()),iu();return}let e=Co(i),n=t.ownerDocument.defaultView??window,r=i.launcher?.mobileBreakpoint??640,a=i.launcher?.mobileFullscreen??!0,o=n.innerWidth<=r,s=a&&o&&ze,c=To(i).reveal;I?(L.style.removeProperty(`display`),L.style.display=e?`flex`:``,L.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),R.classList.remove(`persona-scale-95`,`persona-opacity-0`),R.classList.add(`persona-scale-100`,`persona-opacity-100`),Cp?(Cp.setPanelOpen(!0),Cp.element.style.display=`none`):wp&&(wp.style.display=`none`)):(e?e&&(c===`overlay`||c===`push`)&&!s?(L.style.removeProperty(`display`),L.style.display=`flex`,L.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),R.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(L.style.setProperty(`display`,`none`,`important`),L.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),R.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(L.style.display=``,L.classList.add(`persona-pointer-events-none`,`persona-opacity-0`),R.classList.remove(`persona-scale-100`,`persona-opacity-100`),R.classList.add(`persona-scale-95`,`persona-opacity-0`)),Cp?(Cp.setPanelOpen(!1),Cp.element.style.display=e?`none`:``):wp&&(wp.style.display=e?`none`:``))},cu=(e,n=`user`)=>{if(!rt()||I===e)return;let r=I;I=e,su();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=Co(i)&&r&&o,c=F()&&(i.launcher?.composerBar?.expandedSize??`fullscreen`)===`fullscreen`;return e||r&&o&&ze||s||c})();if(I&&a){if(!No){let e=t.getRootNode(),n=e instanceof ShadowRoot?e.host:t.closest(`.persona-host`);n&&(No=vo(n,i.launcher?.zIndex??1e5))}Po||=xo(t.ownerDocument)}else I||(No?.(),No=null,Po?.(),Po=null);I&&(Op(),ml()||(er()===`follow`?sl(!0):ul()));let o={open:I,source:n,timestamp:Date.now()};I&&!r?k.emit(`widget:opened`,o):!I&&r&&k.emit(`widget:closed`,o),k.emit(`widget:state`,{open:I,launcherEnabled:ze,voiceActive:$.active,streaming:Q.isStreaming()})},lu={inputDisabled:!1,sendDisabled:!1},uu=()=>lu.inputDisabled,hu=()=>Sn(i.voiceRecognition?.provider)&&!!Q&&(Q.isBargeInActive()||[`listening`,`processing`,`speaking`].includes(Q.getVoiceStatus())),vu=()=>lu.inputDisabled||lu.sendDisabled,wu=()=>(lu.inputDisabled?lu.inputReason:void 0)??(lu.sendDisabled?lu.sendReason:void 0);function Nu(){if(!W)return;if(Y.getState().phase===`streaming`){W.disabled=!1;return}let e=jr?!jr.isReady():!1;W.disabled=vu()||e}function Fu(){if(!Un)return;let e=Y.getState(),t=i.sendButton?.visibility===`when-text`&&e.phase!==`streaming`&&e.text.trim().length===0&&e.attachments.length===0;Un.toggleAttribute(`data-persona-send-hidden`,t)}function Iu(){let e=wu();if(F()){let t=En??q;e?t.setAttribute(`title`,e):t.removeAttribute(`title`),q.toggleAttribute(Su,!!e)}else if(e)G.setAttribute(`role`,`status`),G.setAttribute(`aria-live`,`polite`),G.setAttribute(Su,``),G.removeAttribute(Cu),G.textContent=e,w(G,i.statusIndicator??{},`idle`);else if(G.hasAttribute(Su)&&(G.removeAttribute(`role`),G.removeAttribute(`aria-live`),G.removeAttribute(Su),g)){let e=Q.getStatus();hn(G,mn(e),i.statusIndicator??{},e)}}function Lu(){let e=le(i.composer?.inputDisabled),t=le(i.composer?.sendDisabled);lu={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Y.setInputDisabled(e.disabled),Y.setSendDisabled(t.disabled);let n=Y.getState().phase===`streaming`,r=e.disabled,a=n||r;U&&(U instanceof HTMLTextAreaElement?U.disabled=r:U.setAttribute(`contenteditable`,r?`false`:`true`),U.setAttribute(`aria-disabled`,r?`true`:`false`)),Kn&&(Kn.disabled=r),Jn&&(Jn.disabled=r);for(let e of Mr?.affordanceButtons??[])e.querySelectorAll(`button`).forEach(e=>{e.disabled=r});J&&(J.disabled=r||n&&!hu()),Xo.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})}),ed.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})}),q.dataset.personaComposerStreaming=n?`true`:`false`,q.dataset.personaComposerInputDisabled=r?`true`:`false`,q.dataset.personaComposerSendDisabled=vu()?`true`:`false`,q.querySelectorAll(`[data-persona-composer-disable-when-streaming]`).forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=n)}),Nu(),Iu()}let Ru=e=>{Y.setStreaming(e),Wn(e?`stop`:`send`),Lu()},zu=()=>{$.active||U&&U.focus()};k.on(`widget:opened`,()=>{i.autoFocusInput&&setTimeout(()=>zu(),200)});let Bu=null,Vu=!1,Hu=!Dn.hidden,Uu=null,Wu=!he,Gu=null;Z.push(()=>{Gu?.cancel(),Gu=null});let Ku=e=>{let n=Hs(e);if(n===xr)return;xr=n,t.setAttribute(`data-persona-conversation-state`,n);let r=Cr();kr(),Wu&&(Gu?.cancel(),Gu=Ls(q,n===`active`?r:Cr(),n===`active`?`drop`:`rise`,br().layout===`centered`?320:260)),Sl()},qu=null,Ju,Yu=null,Xu=null,Zu=!1,Qu=e=>{let t=br(),n=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??`bottom`}|${t.align??``}|${t.iconPlacement}|${t.kicker??``}|${t.title}|${t.subtitle}`;(n!==qu||t.icon!==Ju)&&(qu=n,Ju=t.icon,Ds({host:Dn,iconHolder:On,kicker:Mn,title:Nn,subtitle:Pn,starterSuggestions:Cn},t));let r=t.message===void 0?null:`${i.layout?.messages?.layout??`bubble`}|${t.message}`;r!==Yu&&(Yu=r,Ps(An,t.message,i));let a=e??(Q?Q.getMessages():i.initialMessages);Ku(a);let o=Vu,s=!o&&Us(t,a),c=s!==Hu;if(Hu=s,Xu){Uu?.cancel(),Uu=null,o!==Zu&&(Zu=o,o?Ms(V,Dn,null):js(V,Dn,Xu)),Es(V,Dn,!o);return}if(c&&!s&&!o&&t.dismiss===`on-first-message`&&Wu){Uu=Is(Dn,e=>{Uu===e&&(Uu=null),!Hu&&!Xu&&(Es(V,Dn,!1),Sl()),e?.cancel()});return}if(Uu){if(!s&&!o)return;Uu.cancel(),Uu=null}let l=!Dn.hidden;Es(V,Dn,s),!s&&l&&Sl()},$u=[],ed=[],td=!1,nd=null,rd,id=()=>{ed.length=0;let e=$u.splice(0,$u.length);for(let t of e)try{t()}catch(e){console.warn(`[persona] renderWelcome cleanup threw`,e)}};Z.push(id);let ad=(e,t)=>{let n=Do(e,t);if(!n)return i.debug===!0&&console.warn(`[persona] renderStarter received a suggestion with no label`),N(`span`);let r=i.suggestions?.starters,a=Ao({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:()=>U,eventTarget:Dn,submitPrompt:wf});return ed.push(a),a},od=()=>{if(td)return;td=!0;let e=br();nd=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`,rd=e.icon;try{id(),Ms(V,Dn,Xu),Xu=null,Zu=!1;let t=Q?Q.getMessages():i.initialMessages,n=Us(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:()=>Dn,sendMessage:e=>{if(!Q||Q.isStreaming())return;let t=e.trim();t&&Q.sendMessage(t)},requestRender:()=>od(),renderStarter:e=>ad(e,r++),storage:_(t.id),onCleanup:e=>{$u.push(e)}}),a))break;a&&a!==Dn&&(Xu=a,js(V,Dn,a))}finally{td=!1}Qu()},sd=()=>{let e=br();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`!==nd||e.icon!==rd)&&od()},cd=()=>{Qu(),mi||(U.placeholder=Gi(Y.getState().activeModeIds,i.composer?.modes)??i.copy?.inputPlaceholder??`How can I help...`,!(i.sendButton?.useIcon??!1)&&!Q?.isStreaming()&&(W.textContent=i.copy?.sendButtonLabel??`Send`)),U.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,U.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`},ld=!!i.setStoredConversationId,ud=e=>Me(t=>{let n={...t};return delete n[e],n}),dd=e=>{let t=de[e];return typeof t==`string`?t:null},fd=()=>{let e=de.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:()=>dd(`sessionId`),setStoredSessionId:e=>{Me(t=>({...t,sessionId:e}))},clearStoredSessionId:i.clearStoredSessionId??(()=>ud(`sessionId`)),getStoredConversationId:i.getStoredConversationId??(()=>dd(`conversationId`)),setStoredConversationId:i.setStoredConversationId??(e=>{Me(t=>({...t,conversationId:e}))}),clearStoredConversationId:i.clearStoredConversationId??(()=>ud(`conversationId`))});let pd=()=>i.clientToken??null,md=e=>ru(e,gt(),i.persistState===!1),hd=pd(),gd=hd?md(hd):null,_d=()=>{let e=de.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`)}},vd={...gd?{visitorStore:gd}:{},historyBootstrapReady:i.features?.history?.enabled===!0&&!fu()?Promise.all([_e,xe]).then(()=>{}):_e,getStoredMessageCursor:()=>dd(`historyMessageCursor`),setStoredMessageCursor:e=>{e===null?ud(`historyMessageCursor`):Me(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:_d,setPendingDisplayProjections:e=>{e?Me(t=>({...t,pendingDisplayProjections:e})):ud(`pendingDisplayProjections`)},getStoredResumableHandle:fd,setStoredResumableHandle:e=>{e?Me(t=>({...t,durableResume:e})):ud(`durableResume`)},shouldResumeDurableConversation:()=>j&&fd()!==null,...ld?{}:{getStoredConversationRevision:()=>dd(`conversationRevision`),setStoredConversationRevision:e=>{e===null?ud(`conversationRevision`):Me(t=>({...t,conversationRevision:e}))}}};if(j){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)&&vd.setStoredResumableHandle?.(t?{executionId:t.executionId,after:t.lastEventId}:null),e?.(t)}}}let yd=()=>{let e=pd();if(e&&gd?.matches(e,gt(),i.persistState===!1)||!e&&!gd)return;gd?.destroy(),gd=e?md(e):null;let t={...vd};gd?t.visitorStore=gd:delete t.visitorStore,vd=t,Q.setHistoryInternals(vd)},bd=null,xd=()=>{bd??=setInterval(()=>{let e=H.querySelectorAll(`[data-tool-elapsed]`);if(e.length===0){clearInterval(bd),bd=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`)?yn(t-n):h(t-n))})},100)},Sd=e=>e.role===`user`||e.variant===`approval`||e.agentMetadata?.awaitingLocalTool===!0||Ze(e),Cd=(e,t)=>{if(t.length<e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n];if(r!==e[n]){if(Sd(r))return!1;r.role===`assistant`&&r.streaming&&gs.add(r.id)}}return!0},wd=null,Td=null,Ed=null,Dd=null,Od=e=>{if(!j)return kc(e);Dd=e,queueMicrotask(()=>{Dd===e&&(Dd=null,kc(Td??e))})},kd=e=>{wd=e;let t,n;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),t&&n)break}Hl(H,e,ct),Wc()?.updateInlineArtifactBlocks(H,xa.artifacts,{suppressTransition:ms}),xd(),Qu(e),us(e),sl(!ms),jl(e),e.length===0&&(vl(),Qs=!0,$s=!1,ec=null,tc=!1),!Ys||Xs?(Ys=!0,Zs=t?.id??null,rc=n?.id??null):t&&t.id!==Zs?(Zs=t.id,Tl(t.id)):n&&n.id!==rc&&El(),n&&(rc=n.id),Al(e);let r=$.lastUserMessageId;t&&t.id!==r&&($.lastUserMessageId=t.id,k.emit(`user:message`,t)),$.lastUserMessageWasVoice=!!t?.viaVoice,Od(e),iu()},Ad=()=>{Ed!==null&&(cancelAnimationFrame(Ed),Ed=null);let e=Td;Td=null,e&&kd(e)},jd=()=>{Ed!==null&&cancelAnimationFrame(Ed),Ed=null,Td=null},Md=e=>{if(e.length===0){jd(),kd(e);return}let t=Td??wd;ms&&t&&Cd(t,e)?(Td=e,Ed===null&&(Ed=requestAnimationFrame(()=>{Ed=null;let e=Td;Td=null,e&&kd(e)}))):(Ad(),kd(e))};Q=new qr(i,{onMessagesChanged(e){Md(e)},onStatusChanged(e){let t=i.statusIndicator??{};hn(G,(e=>e===`idle`?t.idleText??bt.idle:e===`connecting`?t.connectingText??bt.connecting:e===`connected`?t.connectedText??bt.connected:e===`error`?t.errorText??bt.error:e===`paused`?t.pausedText??bt.paused:e===`resuming`?t.resumingText??bt.resuming:bt[e])(e),t,e),dn()},onStreamingChanged(e){e||(Q?.getMessages().length===0?jd():Ad()),ms=e,Ru(e),dn(),Q&&Hl(H,Q.getMessages(),ct),e||(sl(!0),_l(),cs=!0,Q&&ls(Q.getMessages(),$e(i))),il(),vr(e?`Responding…`:`Response complete.`),iu()},onVoiceStatusChanged(e){if(k.emit(`voice:status`,{status:e,timestamp:Date.now()}),e!==`disconnected`&&!Sn(i.voiceRecognition?.provider))return;let t=Q.getVoiceNotice();switch(t&&pf(t,1e4),e){case`listening`:if(!uc){let e=Q.getVoiceDisclosure();e&&(uc=!0,F()?(dc=U.placeholder,U.placeholder=e,vr(e)):pf(e,1e4))}cp(),ap();break;case`processing`:cp(),op();break;case`speaking`:cp(),sp();break;default:e===`idle`&&Q.isBargeInActive()?(cp(),ap(),J?.setAttribute(`aria-label`,`End voice session`)):($.active=!1,uc=!1,dc!==null&&(U.placeholder=dc,dc=null),cp(),vc(`system`),_c||bc())}},onArtifactsState(e){xa=e,e.artifacts.length===0&&(Ea=!1),Wc()?.updateInlineArtifactBlocks(H,e.artifacts,{suppressTransition:ms}),go(),kc()},onHistoryStateChanged(e){ln(e)},onHistoryNotice(e){un(e)},onReconnect(e){let{executionId:t,lastEventId:n}=e.handle;e.phase===`paused`?k.emit(`stream:paused`,{executionId:t,after:n}):e.phase===`resuming`?k.emit(`stream:resuming`,{executionId:t,after:n,attempt:e.attempt??1}):k.emit(`stream:resumed`,{executionId:t,after:n})}},vd),ka.current=Q,Z.push(()=>Q.cancel()),Z.push(()=>{Q.destroy(),gd?.destroy(),gd=null});let Nd=null;if(Q.onReadAloudChange((e,t)=>{ua=e,da=t,ma();let n=e??Nd;e&&(Nd=e);let r=n?Q.getMessages().find(e=>e.id===n)??null:null;k.emit(`message:read-aloud`,{messageId:n,message:r,state:t,timestamp:Date.now()}),t===`idle`&&(Nd=null)}),g=!0,Ys=!0,i.voiceRecognition?.enabled===!0&&Sn(i.voiceRecognition.provider))try{Q.setupVoice()}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Runtype voice setup failed:`,e)}let Pd=null,Fd=null,Id=!1,Ld=Q.getHistoryState(),Rd=()=>i.features?.history?.enabled===!0,zd=e=>{e&&(hr.textContent=``,hr.textContent=e)},Bd=()=>{m.forEach(e=>e()),m=[];let e=Pd,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:()=>an&&on===`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}`}))};Bd();let Vd=null,Hd=!1,Ud=()=>{if(!Ln)return;let e=i.layout?.header?.titleSource===`conversation`,t=e&&Vd?.trim()||null;Ln.textContent=t??i.launcher?.title??`Chat Assistant`;let n=Ln.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`)},Wd=e=>{e!==Vd&&(Vd=e,Ud())},Gd=e=>{Hd=e?.starred===!0,Wd(e&&e.title.trim()||null),Ud()};Ud(),B.addEventListener(`persona:title-menu-builtin`,e=>{let t=e.detail?.actionId,n=Q.getActiveConversationId();n&&(t===`delete`?Yd(e=>e.requestDeleteConversation(n)):t===`star`&&Q.canUpdateConversations()&&Yd(e=>e.updateHistoryConversation(n,{starred:!Hd})).catch(()=>{}))}),ln=e=>{Ld=e,Pd?.historySurface?.view.setNewConversationRequired(e.recovery===`new_conversation_required`),Ru(e.sendBlocked||ms),Pd?.syncEarlierMessagesPill()},un=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(hs.clear(),vl(),ol()),zd(e.message),Pd?.historySurface?.view.refresh()};let Kd={get actionManager(){return Re},get activeConversationTitle(){return Vd},announceHistory:zd,get applyRailChrome(){return cn},set applyRailChrome(e){cn=e},get artifactSplitRoot(){return Ra},get body(){return V},get config(){return i},get container(){return B},get conversationOpenPendingEl(){return Bu},set conversationOpenPendingEl(e){Bu=e},get conversationOpenTakeover(){return Vu},set conversationOpenTakeover(e){Vu=e},currentKeyPrefix:gt,destroyCallbacks:Z,eventBus:k,get footer(){return q},get header(){return zn},get historyChromeSync(){return dn},set historyChromeSync(e){dn=e},historyFeatureEnabled:Rd,get historyInternals(){return vd},set historyInternals(e){vd=e},get historyPresentation(){return on},set historyPresentation(e){on=e},get historySessionState(){return Ld},get historyVisible(){return an},set historyVisible(e){an=e},get isStreaming(){return ms},jumpToBottomInstant:ul,get lastAppliedMessages(){return wd},set lastAppliedMessages(e){wd=e},get launcherEnabled(){return ze},get launcherSurfaceInstance(){return Cp},maybeFocusInput:zu,messageCache:hs,get messagesWrapper(){return H},mount:t,get open(){return I},panel:R,panelElements:z,get persistentMetadata(){return de},set persistentMetadata(e){de=e},plugins:f,get reapplyHistoryHostChrome(){return sn},set reapplyHistoryHostChrome(e){sn=e},repinAnchoredMessage:Sl,resetAnchorState:vl,restoreScrollPosition:ml,resumeAutoScroll:ol,runStorageMutation:Oc,get session(){return Q},setActiveConversationSummary:Gd,storageAdapter:ue,get suppressScrollSend(){return Xs},set suppressScrollSend(e){Xs=e},syncScrollToBottomButton:il,updateWelcome:Qu,getHistoryProviderFactory:pu,historyErrors:{HistoryClientError:Zn,HistoryProviderError:St},isDockedMountMode:Co,renderLucideIcon:P,loadHistoryView:ou,createHeaderIconButton:Io,attachTooltip:S},qd=e=>(!Pd&&!Id&&(Pd=e.createHistoryShell(Kd),Pd.railCollapseShortcut()&&Bd()),Pd),Jd=()=>{if(Pd)return Promise.resolve(Pd);let e=fu();return e?Promise.resolve(qd(e)):(Fd??=du().then(qd,e=>{throw Fd=null,e}),Fd)},Yd=e=>{let t=fu(),n=Pd??(t?qd(t):null);return n?e(n):Jd().then(t=>{if(!t)throw Error(`[AgentWidget] The widget was destroyed`);return e(t)})},Xd=()=>{Pd?.syncHistoryPresentation()};Z.push(()=>{Id=!0}),Rd()&&Jd().catch(()=>{}).finally(ve),i.clientToken&&(i.features?.history?.enabled===!0||i.sessionInit===`mount`)&&Q.initClientSession().then(()=>{let e=Pd;if(e?.historyAvailable())return Q.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Pd?.syncEarlierMessagesPill()}).catch(e=>{i.debug&&console.warn(`[AgentWidget] Pre-init client session failed:`,e)});let Zd=()=>Q.warmClientSession(),Qd=e=>{let t=i.sessionInit??`input`,n=_i?.input??U,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`:(_i?.form??En)?.contains(r)))&&Zd()},$d=[`input`,`pointerdown`,`keyup`];$d.forEach(e=>t.addEventListener(e,Qd));let ef,tf,nf=()=>{let e=tf;tf=void 0;try{typeof e==`function`&&e()}catch{}},rf=()=>{let e=i.clientToken&&typeof i.sessionInit==`function`?i.sessionInit:void 0;if(e!==ef){nf(),ef=e;try{tf=e?.({warm:Zd,mount:t})}catch{}}};rf(),Z.push(()=>{$d.forEach(e=>t.removeEventListener(e,Qd)),nf()}),(dt||i.onSSEEvent)&&Q.setSSEEventCallback((e,t)=>{i.onSSEEvent?.(e,t),nn(e,t)});let af=()=>{let e=i.resume??(j?vd.getStoredResumableHandle?.():null);e&&typeof i.reconnectStream==`function`&&Q.resumeFromHandle(e)};he?he.then(e=>{if(e){if(e.metadata&&(de=ku(e.metadata),Re.syncFromMetadata()),e.messages?.length){Xs=!0;try{Q.hydrateMessages(e.messages)}finally{Xs=!1}zl()}e.artifacts?.length&&Q.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),Rc(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Wu=!0,ge(),af()}):(Rc(we),af());let of=()=>{F()&&(I||(i.launcher?.composerBar?.expandOnSubmit??!0)&&cu(!0,`auto`))},sf=(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),Pu(i)}}:e:t,cf=()=>{let e=U.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>e.kind===`mention`)?e.contentSegments:void 0},lf=!1,uf=null,df=()=>{U.value=``,U.style.height=`auto`,Fr(),Af()},ff=null;function pf(e,t=4e3){vr(e),!F()&&G&&(G.hasAttribute(Su)||(G.setAttribute(Cu,``),G.setAttribute(`role`,`status`),G.setAttribute(`aria-live`,`polite`),G.textContent=e,w(G,i.statusIndicator??{},`idle`),ff&&clearTimeout(ff),ff=setTimeout(()=>{if(ff=null,G?.hasAttribute(Cu)&&(G.removeAttribute(Cu),G.removeAttribute(`role`),G.removeAttribute(`aria-live`),g)){let e=Q.getStatus();hn(G,mn(e),i.statusIndicator??{},e)}},t)))}function mf(){let e=Y.getState().pendingSubmission;e&&(ti(void 0),U&&(U.value=e.text,U.dispatchEvent(new Event(`input`,{bubbles:!0})),Fr()),e.options.selectedModelId&&(Y.setSelectedModelId(e.options.selectedModelId),Wr?.repaint()),e.options.activeModeIds?.length&&Hr(e.options.activeModeIds),e.options.quote&&Xr(e.options.quote),U?.focus())}let hf=e=>{typeof console<`u`&&console.error(`[AgentWidget] composer.onBeforeSend failed; the draft was preserved:`,e)},gf=(e={})=>{let t=(e.overrideText??U?.value??``).trim();return e.resolveInlineCommand&&t?(Mr?.takeInlineCommand(t)??Promise.resolve(null)).then(n=>_f(e,t,n)):_f(e,t,null)},_f=(e,t,n)=>{if(n?.kind===`action`){df(),Mr?.clear(),Ir();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:(jr?.hasAttachments()??!1)||(o?.length??0)>0,attachmentsReady:jr?.isReady()??!0,hasMentions:Mr?.hasMentions()??!1,hasServerMentions:!!r,inputDisabled:uu(),sendDisabled:vu()}))return;let s=Q.isStreaming()?Qr():`block`;if(s===`defer-one`&&!e.pending){if(Y.getState().pendingSubmission){pf(`One message is already queued. Edit or remove it first.`);return}vf({intent:e,sendText:a,serverMentions:r});return}let c={text:a,mentionRefs:[...Mr?.getMentionRefs()??[],...r?.refs??[]],contentSegments:n?.kind===`prompt`?void 0:cf(),options:{...Y.getState().selectedModelId&&{selectedModelId:Y.getState().selectedModelId},...Y.getState().activeModeIds.length>0&&{activeModeIds:[...Y.getState().activeModeIds]},...Y.getState().quote&&{quote:{...Y.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(!jr?.hasAttachments())return;let e=[...jr.getContentParts()];return c.text&&e.push(ot(c.text)),e};c.contentParts=l();let u=()=>{Ts(),of();let t=Mr?.collectForSubmit()??null,n=sf(t,r),a=l();e.consumeDraft!==!1&&df();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}}),jr?.hasAttachments()&&jr.clearAttachments(),t&&Mr?.clear(),Ir();let d=Y.getState().activeModeIds,f=Wi(d,i.composer?.modes);f.length!==d.length&&Hr(f),Y.getState().quote&&Xr(void 0),zc(),Li.release(),Vi()},d=i.composer?.onBeforeSend;if(!d){u();return}let f=new AbortController;uf=f;let p=e=>{uf=null,e.status===`error`?hf(e.error):e.status===`proceed`&&u()},m=oa(d,c,f.signal);if(!(m instanceof Promise))p(m);else return Y.setPreparing(!0),m.then(p).finally(()=>Y.setPreparing(!1))};function vf(e){let t=Y.getState(),n=jr?.hasAttachments()??!1,r=n?[...jr.getContentParts()]:[];n&&e.sendText&&r.push(ot(e.sendText)),ti(na({text:e.sendText,contentParts:r.length?r:void 0,mentionRefs:[...Mr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:cf(),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&&df(),n&&jr.clearAttachments(),Mr?.clear(),Ir(),t.quote&&Xr(void 0),zc(),Li.release(),Vi(),vr(`Message queued. It sends when the response finishes.`)}function yf(){let e=Y.getState().pendingSubmission;e&&(ti(void 0),Tf(e.text,{consumeDraft:!1,pending:e}))}function bf(e){if(i.messageActions?.showEdit!==!0)return;let t=Q.getMessages().find(t=>t.id===e);t&&Er(t)&&Ss!==e&&(Ts(),Ss=e,ws=Yi({messageId:e,initialText:t.content,onSave:t=>xf(e,t),onCancel:()=>Ts()}),hs.delete(e),Hl(H,Q.getMessages(),ct),ws.focus())}function xf(e,t){let n=ws;Ss=null,ws=null,n?.destroy(),hs.delete(e),Q.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?Sl():Hl(H,Q.getMessages(),ct)}function Sf(e){if(Q.isStreaming())return;let t=wr(Q.getMessages(),e);t&&(Ts(),Q.resubmitFrom(t,{reason:`retry`})&&Sl())}ha={regenerate:Sf,edit:bf,quote:e=>{let t=Q.getMessages().find(t=>t.id===e)?.content?.trim();t&&(Xr({text:t,messageId:e}),U?.focus())}};let Cf=async e=>{if(!lf){lf=!0;try{await gf({resolveInlineCommand:!0,...e})}finally{lf=!1}}};function wf(e){vu()||(df(),Tf(e,{consumeDraft:!1}))}let Tf=(e,t)=>{if(lf)return;lf=!0;let n=()=>{lf=!1};try{let r=gf({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},Ef=e=>{e.preventDefault(),Q.isStreaming()?(Q.cancel(),Ct?.reset(),Yt?.update()):lf||Cf()},Df=()=>i.features?.composerHistory!==!1,Of={...ao},kf=!1,Af=()=>{Of={...ao}},jf=()=>Q.getMessages().filter(e=>e.role===`user`).map(e=>e.content??``).filter(e=>e.length>0),Mf=e=>{if(!U)return;kf=!0,U.value=e,U.dispatchEvent(new Event(`input`,{bubbles:!0})),kf=!1;let t=U.value.length;U.setSelectionRange(t,t)},Nf=e=>{kf||(e.isComposing||Mr?.handleInput(e.inputType??void 0),Af())},Pf=()=>({submitKey:i.composer?.submitKey,insertNewlineOnTouchEnter:i.composer?.insertNewlineOnTouchEnter,coarsePointer:Ee(U)}),Ff=e=>{if(U&&!uu()&&(e.isComposing||!Mr?.handleKeydown(e))){if(Df()&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.isComposing){let t=U.selectionStart===0&&U.selectionEnd===0,n=oo({direction:e.key===`ArrowUp`?`up`:`down`,history:jf(),currentValue:U.value,atStart:t,state:Of});if(Of=n.state,n.handled){e.preventDefault(),n.value!==void 0&&Mf(n.value);return}}if(ke(e,Pf())){if(Q.isStreaming()){if(e.preventDefault(),Qr()===`block`||lf||vu())return;Af(),Cf()}else lf||vu()?e.preventDefault():(Af(),e.preventDefault(),W.click())}}},If=e=>{e.key!==`Escape`||e.isComposing||e.composedPath().includes(B)&&(uf?(uf.abort(),uf=null,e.preventDefault(),e.stopImmediatePropagation()):Q.isStreaming()&&(Q.cancel(),Ct?.reset(),Yt?.update(),Af(),e.preventDefault(),e.stopImmediatePropagation()))},Lf=async e=>{if(i.attachments?.enabled!==!0||!jr||uu())return;let t=Tu(e.clipboardData);t.length!==0&&(e.preventDefault(),await jr.handleFiles(t))},Rf=null,zf=!1,Bf=null,Vf=null,Hf=()=>i.voiceRecognition?.completionBehavior===`review`;function Uf(e){J?.setAttribute(`data-state`,e),e===`recording`?Qf():$f()}let Wf=`--persona-voice-level`,Gf=.5,Kf=null,qf=-1,Jf=0,Yf=()=>{let e=[],t=Gn??J?.parentElement??null;return t&&e.push(t),q&&e.push(q),e},Xf=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*100)/100;if(t!==qf){qf=t;for(let e of Yf())e.style.setProperty(Wf,String(t))}},Zf=()=>{qf=-1,Jf=0;for(let e of Yf())e.style.removeProperty(Wf)};function Qf(){if(Kf!==null)return;if(typeof requestAnimationFrame!=`function`){Xf(g?Q.getVoiceLevel()??Gf:Gf);return}let e=()=>{Kf=requestAnimationFrame(e);let t=g?Q.getVoiceLevel():null;t===null?Xf(Gf):(Jf+=(t-Jf)*.3,Xf(Jf))};Kf=requestAnimationFrame(e)}function $f(){Kf!==null&&(cancelAnimationFrame(Kf),Kf=null),Zf()}let ep=()=>typeof window>`u`?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,tp=(e=`user`)=>{if(zf||Q.isStreaming())return;let t=ep();if(!t)return;Rf=new t;let n=i.voiceRecognition??{},r=n.pauseDuration??2e3;Rf.continuous=n.provider?.browser?.continuous??!0,Rf.interimResults=!0,Rf.lang=n.provider?.browser?.language??`en-US`;let a=U.value;Rf.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;U.value=i,Fr(),Bf&&clearTimeout(Bf),(t||n)&&(Bf=window.setTimeout(()=>{if(U.value.trim()&&Rf&&zf){if(np(),Hf())return;Cf({viaVoice:!0})}},r))},Rf.onerror=e=>{e.error!==`no-speech`&&np()},Rf.onend=()=>{if(zf){let e=U.value.trim();!Hf()&&e&&e!==a.trim()&&Cf({viaVoice:!0}),np()}};try{if(Rf.start(),zf=!0,$.active=!0,e!==`system`&&($.manuallyDeactivated=!1),vc(e),bc(),Vi(),J){let e=i.voiceRecognition??{};Vf={backgroundColor:J.style.backgroundColor,color:J.style.color,borderColor:J.style.borderColor,iconName:e.iconName??`mic`,iconSize:parseFloat(e.iconSize??``)||24};let t=e.recordingBackgroundColor,n=e.recordingIconColor,r=e.recordingBorderColor;if(J.classList.add(`persona-voice-recording`),Uf(`recording`),J.style.backgroundColor=t??`var(--persona-voice-recording-bg, #ef4444)`,J.style.color=n??`var(--persona-voice-recording-indicator, #ffffff)`,n){let e=J.querySelector(`svg`);e&&e.setAttribute(`stroke`,n)}r&&(J.style.borderColor=r),J.setAttribute(`aria-label`,`Stop voice recognition`)}}catch{np(`system`)}},np=(e=`user`)=>{if(zf){if(zf=!1,Bf&&=(clearTimeout(Bf),null),Rf){try{Rf.stop()}catch{}Rf=null}if($.active=!1,vc(e),bc(),Vi(),J){if(J.classList.remove(`persona-voice-recording`),Uf(`idle`),Vf){J.style.backgroundColor=Vf.backgroundColor,J.style.color=Vf.color,J.style.borderColor=Vf.borderColor;let e=J.querySelector(`svg`);e&&e.setAttribute(`stroke`,Vf.color||`currentColor`),Vf=null}J.setAttribute(`aria-label`,`Start voice recognition`)}}},rp=null,ip=e=>{let t=t=>{rp??=t.createMicStateStyles({mic:()=>J,config:()=>i,session:()=>Q,get original(){return Vf},set original(e){Vf=e},setMicState:Uf,renderIcon:P,iconFallbackPx:24}),e(rp)},n=Pr();n?t(n):Nr().then(t,()=>{})},ap=()=>ip(e=>e.recording()),op=()=>ip(e=>e.processing()),sp=()=>ip(e=>e.speaking()),cp=()=>ip(e=>e.reset()),lp=()=>{if(!uu()){if(Sn(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,bc(),vc(`user`),cp()});return}Q.toggleVoice().then(()=>{$.active=gc(),$.manuallyDeactivated=!$.active,bc(),vc(`user`),$.active?ap():cp()})}else if(zf){let e=U.value.trim();$.manuallyDeactivated=!0,bc(),np(`user`),e&&!Hf()&&Cf()}else $.manuallyDeactivated=!1,bc(),tp(`user`)}};oi=lp;let up=()=>Q.prewarmVoice(),dp=()=>{let e=i.voiceRecognition;return e?.enabled===!0?e.prewarm??(i.clientToken?`hover`:!1):!1},fp=e=>{dp()===`hover`&&J?.contains(e.target)&&up()},pp=[`pointerover`,`pointerdown`,`focusin`];pp.forEach(e=>t.addEventListener(e,fp));let mp,hp=null,gp,_p=()=>{let e=gp;gp=void 0;try{typeof e==`function`&&e()}catch{}},vp=()=>{let e=dp(),n=typeof e==`function`&&J?e:void 0,r=n?J:null;if((n!==mp||r!==hp)&&(_p(),mp=n,hp=r,n&&r))try{gp=n({warm:up,micButton:r,mount:t})}catch{}};vp(),Z.push(()=>{pp.forEach(e=>t.removeEventListener(e,fp)),_p()}),J&&Z.push(()=>{Sn(i.voiceRecognition?.provider)?(Q.isVoiceActive()&&Q.toggleVoice(),cp()):np(`system`)});let yp=k.on(`assistant:complete`,()=>{Y.getState().pendingSubmission&&setTimeout(()=>{Q.isStreaming()||yf()},0)});Z.push(yp);let bp=k.on(`assistant:complete`,()=>{hc&&($.active||$.manuallyDeactivated||(hc!==`assistant`||$.lastUserMessageWasVoice)&&setTimeout(()=>{!$.active&&!$.manuallyDeactivated&&(Sn(i.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=Q.isVoiceActive(),vc(`auto`),Q.isVoiceActive()&&ap()}):tp(`auto`))},600))});Z.push(bp);let xp=k.on(`action:resubmit`,()=>{setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)});Z.push(xp);let Sp=()=>{cu(!I,`user`)},Cp=null,wp=null;if(ze&&!F()){let{instance:e,element:t}=lc({config:i,plugins:f,onToggle:Sp});Cp=e,e||(wp=t)}Cp?t.appendChild(Cp.element):wp&&t.appendChild(wp),su(),us(),cd(),od(),Ru(Q.isStreaming()),ml()||(er()===`follow`?sl(!0):ul()),xc(),Ue&&(!ze||F()?setTimeout(()=>zu(),0):I&&setTimeout(()=>zu(),200));let Tp=null,Ep=()=>{Tp&&(Tp.disconnect(),Tp.observe(q),Tp.observe(B),Tp.observe(Dn))},Dp=yr(),Op=()=>{if(F()){Dr(),su();return}let e=Co(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&&ze;try{if(c){va(),ya=ho();return}let t=!1;Je&&(Je=!1,va(),t=!0);let r=ho();if(!t&&r!==ya&&(va(),t=!0),ya=r,t&&Ha(),!ze&&!e){R.style.height=``,R.style.width=``;return}if(!n&&!e){let e=Gs(i);R.style.width=e.width,R.style.maxWidth=e.maxWidth}so(),ko()}finally{Dr(),kr();let e=yr();if(e!==Dp&&(Dp=e,Qu(),us()),su(),I&&ze){let e=(t.ownerDocument.defaultView??window).innerWidth<=(i.launcher?.mobileBreakpoint??640),n=i.launcher?.sidebarMode??!1,r=i.launcher?.mobileFullscreen??!0,a=Co(i)&&r&&e,o=n||r&&e&&ze||a;if(o&&!Po){let e=t.getRootNode(),n=e instanceof ShadowRoot?e.host:t.closest(`.persona-host`);n&&!No&&(No=vo(n,i.launcher?.zIndex??1e5)),Po=xo(t.ownerDocument)}else o||(No?.(),No=null,Po?.(),Po=null)}}};Op();let kp=t.ownerDocument.defaultView??window;if(kp.addEventListener(`resize`,Op),Z.push(()=>kp.removeEventListener(`resize`,Op)),typeof ResizeObserver<`u`){Tp=new ResizeObserver(()=>{kr()}),Ep(),Z.push(()=>{Tp?.disconnect(),Tp=null});let e=new ResizeObserver(()=>{Xd()});e.observe(B),Z.push(()=>e.disconnect())}kp.addEventListener(`resize`,Xd),Z.push(()=>kp.removeEventListener(`resize`,Xd)),Ns=V.scrollTop;let Ap=jt(V),jp=()=>{Eo();let e=V.scrollTop,t=jt(V),n=t<Ap;if(Ap=t,!tr()){Ns=e,il();return}let{action:r,nextLastScrollTop:i}=At({following:As.isFollowing(),currentScrollTop:e,lastScrollTop:Ns,nearBottom:It(V,24),userScrollThreshold:4,isAutoScrolling:Rs||zs||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});Ns=i,r===`resume`?pl()||ol():r===`pause`&&al()};if(V.addEventListener(`scroll`,jp,{passive:!0}),Z.push(()=>V.removeEventListener(`scroll`,jp)),typeof ResizeObserver<`u`){let e=new ResizeObserver(()=>{wl(),jn(H)});e.observe(H),e.observe(V),Z.push(()=>e.disconnect())}let Mp=()=>{tr()&&As.isFollowing()&&pl()&&al()},Np=V.ownerDocument;Np.addEventListener(`selectionchange`,Mp),Z.push(()=>{Np.removeEventListener(`selectionchange`,Mp)});let Pp=/* @__PURE__ */ new Set([`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`]),Fp=e=>{Pp.has(e.key)&&(nc(),ir()&&tr()&&As.isFollowing()&&al())},Ip=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&(nc(),ir()&&tr()&&As.isFollowing()&&al())};V.addEventListener(`keydown`,Fp),V.addEventListener(`focusin`,Ip),Z.push(()=>{V.removeEventListener(`keydown`,Fp),V.removeEventListener(`focusin`,Ip)});let Lp=e=>{if(e.deltaY!==0&&nc(),!tr())return;let t=Mt({following:As.isFollowing(),deltaY:e.deltaY,nearBottom:It(V,24),resumeWhenNearBottom:!0});t===`pause`?al():t===`resume`&&!pl()&&ol()};V.addEventListener(`wheel`,Lp,{passive:!0}),V.addEventListener(`touchmove`,nc,{passive:!0}),V.addEventListener(`pointerdown`,nc,{passive:!0}),Z.push(()=>{V.removeEventListener(`touchmove`,nc),V.removeEventListener(`pointerdown`,nc)}),Z.push(()=>V.removeEventListener(`wheel`,Lp)),cr.addEventListener(`click`,()=>{vl(),V.scrollTop=V.scrollHeight,Ns=V.scrollTop,ol(),sl(!0),il()}),Z.push(()=>cr.remove()),Z.push(()=>{qc(),vl()});let Rp=()=>{K&&(Qo&&=(K.removeEventListener(`click`,Qo),null),rt()?(K.style.display=``,Qo=()=>{cu(!1,`user`)},K.addEventListener(`click`,Qo)):K.style.display=`none`)};Rp(),(()=>{let{clearChatButton:e}=z;e&&e.addEventListener(`click`,()=>{let e=Pd;if(e?.historyAvailable()){e.startNewConversation({focusComposer:!0}).catch(e=>{i.debug&&console.warn(`[AgentWidget] New conversation failed:`,e)});return}Q.clearMessages(),i.layout?.topFade&&(V.scrollTop=0),V.removeAttribute(`data-persona-top-fade`),hs.clear(),ol(),Ye(z.composerOverlay);try{localStorage.removeItem(xu),i.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xu}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(i.clearChatHistoryStorageKey&&i.clearChatHistoryStorageKey!==xu)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),ue?.clear&&Oc(()=>ue.clear(),`[AgentWidget] Failed to clear storage adapter:`),de={},Re.syncFromMetadata(),jr?.clearAttachments(),zc(),ti(void 0),Xr(void 0),Ts(),xt?.clear(),Ct?.reset(),Yt?.update()})})();let zp=[[`keydown`,Ff],[`input`,Nf],[`input`,Fr],[`input`,Ir],[`keyup`,Ir],[`paste`,Lf],[`focus`,wi]],Bp=e=>{if(e)for(let[t,n]of zp)_i?.addListener(e,t,n)},Vp=e=>{if(e)for(let[t,n]of zp)_i?.removeListener(e,t,n)},Hp=()=>{_i&&(_i.addListener(_i.form,`submit`,Ef),_i.addListener(_i.footer,`click`,Ir),Bp(U),J&&_i.addListener(J,`click`,lp),vp())};Hp();let Up=()=>{Mr?.onComposerSwap((e,t)=>{Vp(t),U=e,_i&&(_i.input=e),Bp(e),yi(),Lu(),Fr()})};Up();let Wp=!1;function Gp(){if(!Wp){Wp=!0;try{let e=U?.value??``,t=q.ownerDocument??document,n=U?t.activeElement===U:!1;$f(),_i?.destroy(),_i=null,Mr?.destroy(),Mr=null;let r=null,a=()=>(r=F()?Zo({config:i}):Yo({config:i}),r.footer),o=hi(a)??a();gn.replaceComposer(o),q=gn.composer.footer;let s=r!==null&&o===r.footer;mi=!s,Wn=s?r.setSendButtonMode:()=>{},pi(q),bi(q),Si(),Ci(),Ti(),Up(),ki(),ji(),Mi(),Hp();let c=Xo.indexOf(Go);if(Go.destroy(),Go=jo(Tn),c>=0&&(Xo[c]=Go),U&&(U.value=e),Fr(),Ir(),cd(),us(),Ru(Q.isStreaming()),i.statusIndicator?.mode===`transient`&&!F()){let e=Q.getStatus();hn(G,mn(e),i.statusIndicator,e)}$.active&&Uf(`recording`),va(),Ep(),Dr(),Vi(),Fu(),n&&U?.focus()}finally{Wp=!1}}}let Kp=t.ownerDocument??document;Kp.addEventListener(`keydown`,If,!0);let qp=()=>{Lc()},Jp=()=>{Kp.visibilityState===`hidden`&&Lc()};typeof window<`u`&&(window.addEventListener(`pagehide`,qp),Kp.addEventListener(`visibilitychange`,Jp),Z.push(()=>{window.removeEventListener(`pagehide`,qp),Kp.removeEventListener(`visibilitychange`,Jp)}));let Yp=`persona-attachment-drop-active`,Xp=0,Zp=()=>{Xp=0,B.classList.remove(Yp)},Qp=()=>i.attachments?.enabled===!0&&jr!==null&&!uu(),$p=e=>{Eu(e.dataTransfer)&&Qp()&&(Xp++,Xp===1&&B.classList.add(Yp))},em=e=>{Eu(e.dataTransfer)&&Qp()&&(Xp--,Xp<=0&&Zp())},tm=e=>{Eu(e.dataTransfer)&&Qp()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},nm=e=>{if(!Eu(e.dataTransfer)||!Qp())return;e.preventDefault(),e.stopPropagation(),Zp();let t=Array.from(e.dataTransfer.files??[]);t.length!==0&&jr.handleFiles(t)};B.addEventListener(`dragenter`,$p,!0),B.addEventListener(`dragleave`,em,!0),t.addEventListener(`dragover`,tm,!0),t.addEventListener(`drop`,nm,!0);let rm=t.ownerDocument,im=e=>{Qp()&&e.preventDefault()},am=e=>{Qp()&&e.preventDefault()};rm.addEventListener(`dragover`,im),rm.addEventListener(`drop`,am),Z.push(()=>{_i?.destroy(),_i=null,$f(),Ei?.destroy(),Ei=null,Kr?.destroy(),Kr=null,Yr?.destroy(),Yr=null,ei?.destroy(),ei=null,Wr=null,Gr=null,Lc(),Fc.destroy(),ff&&clearTimeout(ff),Ts(),uf?.abort(),uf=null,jr?.destroy(),jr=null,Y.destroy(),Kp.removeEventListener(`keydown`,If,!0),Mr?.destroy()}),Z.push(()=>{B.removeEventListener(`dragenter`,$p,!0),B.removeEventListener(`dragleave`,em,!0),t.removeEventListener(`dragover`,tm,!0),t.removeEventListener(`drop`,nm,!0),rm.removeEventListener(`dragover`,im),rm.removeEventListener(`drop`,am),Zp()}),Z.push(()=>{Q.cancel()}),Cp?Z.push(()=>{Cp?.destroy()}):wp&&Z.push(()=>{wp?.remove()});let om={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=Bl({...i,features:d},e),d=i.features,i=Cl(i),u(),yo(),Za(t,i),Qc(t,i),$c(t,i),cn(),go(),i.colorScheme!==s&&Ro();let D=Il.getForInstance(i.plugins);f.length=0,f.push(...D),Bd(),ze=i.launcher?.enabled??!0,Ve=i.launcher?.autoExpand??!1,lt=i.features?.showReasoning??!0,ut=i.features?.showToolCalls??!0,pt=i.features?.scrollToBottom??{};let O=er();mt=i.features?.scrollBehavior??{},O!==er()&&(vl(),ol()),ac(),Ar(),il();let ee=dt;if(dt=i.features?.showEventStreamToggle??!1,dt&&!ee){if(xt||(rn(),Q.setSSEEventCallback((e,t)=>{i.onSSEEvent?.(e,t),nn(e,t)})),!di&&zn){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:``);di=N(`button`,t),di.style.width=`28px`,di.style.height=`28px`,di.style.color=zo.actionIconColor,di.type=`button`,di.setAttribute(`aria-label`,`Event Stream`),di.title=`Event Stream`;let n=b(Jt,`18px`,`currentColor`,1.5);n&&di.appendChild(n);let r=z.clearChatButtonWrapper,a=z.closeButtonWrapper,o=r||a;o&&o.parentNode===zn?zn.insertBefore(di,o):zn.appendChild(di),di.addEventListener(`click`,()=>{Zt?ui():li()})}}else!dt&&ee&&(ui(),di&&=(di.remove(),null),xt?.clear(),vt?.destroy(),xt=null,vt=null,Ct?.reset(),Ct=null,Tt=null);if(i.launcher?.enabled===!1&&Cp&&(Cp.destroy(),Cp=null),i.launcher?.enabled===!1&&wp&&(wp.remove(),wp=null),i.launcher?.enabled!==!1&&!Cp&&!wp){let{instance:e,element:n}=lc({config:i,plugins:f,onToggle:Sp});Cp=e,e||(wp=n),t.appendChild(n)}Cp&&Cp.update(i),Ud(),Rn&&i.launcher?.subtitle!==void 0&&(Rn.textContent=i.launcher.subtitle);let te=i.layout?.header;if(te?.layout!==qe&&zn){let e=te?Jo(i,te,{showClose:rt(),onClose:()=>cu(!1,`user`)}):Ho({config:i,showClose:rt(),onClose:()=>cu(!1,`user`)});gn.replaceHeader(e),zn=gn.header.element,In=gn.header.iconHolder,Ln=gn.header.headerTitle,Rn=gn.header.headerSubtitle,K=gn.header.closeButton,qe=te?.layout,Ud()}else if(te){if(In&&(In.style.display=te.showIcon===!1?`none`:``),Ln&&(Ln.style.display=te.showTitle===!1?`none`:``),Rn&&(Rn.style.display=te.showSubtitle===!1?`none`:``),K){let e=rt()&&te.showCloseButton!==!1;K.style.display=e?``:`none`}if(z.clearChatButtonWrapper){let e=te.showClearChat;if(e!==void 0){z.clearChatButtonWrapper.style.display=e?``:`none`;let{closeButtonWrapper:t}=z;t&&!t.classList.contains(`persona-absolute`)&&(e?t.classList.remove(`persona-ml-auto`):t.classList.add(`persona-ml-auto`))}}}let ne=i.layout?.showHeader!==!1;zn&&(zn.style.display=ne?``:`none`);let re=i.layout?.showFooter!==!1;q&&(q.style.display=re?``:`none`),Dr(),il(),ze===Ke?Ve!==Ge&&cu(Ve,`auto`):ze?cu(Ve,`auto`):(I=!0,su()),Ge=Ve,Ke=ze,Op(),Rp();let ie=JSON.stringify(i.toolCall)!==JSON.stringify(r),ae=JSON.stringify(i.messageActions)!==JSON.stringify(a),oe=JSON.stringify(i.layout?.messages)!==JSON.stringify(o),se=i.loadingIndicator?.render!==c?.render||i.loadingIndicator?.renderIdle!==c?.renderIdle||i.loadingIndicator?.showBubble!==c?.showBubble,ce=i.iterationDisplay!==l,le=(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||ie||ae||oe||se||ce||le)&&Q&&(Os++,Hl(H,Q.getMessages(),ct));let ue=i.features?.streamAnimation?.type;if(ue!==_&&ue&&ue!==`none`){let e=Vo(ue,i.features?.streamAnimation?.plugins);e&&Ut(e,t)}let j=i.launcher??{},de=j.headerIconHidden??!1,fe=i.layout?.header?.showIcon,pe=de||fe===!1,me=j.headerIconName,he=j.headerIconSize??`40px`;if(In){let e=zn,t=e?.querySelector(`.persona-flex-col`);if(pe)In.style.display=`none`,e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(In.style.display=``,In.style.height=he,In.style.width=he,e&&t&&(e.contains(In)?In.nextSibling!==t&&(In.remove(),e.insertBefore(In,t)):e.insertBefore(In,t)),me){let e=parseFloat(he)||24,t=P(me,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))`,In.replaceChildren(t)):In.textContent=j.agentIconText??`💬`}else if(j.iconUrl){let e=In.querySelector(`img`);if(e)e.src=j.iconUrl,e.style.height=he,e.style.width=he;else{let e=document.createElement(`img`);e.src=j.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=he,e.style.width=he,In.replaceChildren(e)}}else{let e=In.querySelector(`svg`),t=In.querySelector(`img`);(e||t)&&In.replaceChildren(),In.textContent=j.agentIconText??`💬`}let n=In.querySelector(`img`);n&&(n.style.height=he,n.style.width=he)}}let ge=i.layout?.header?.showTitle,_e=i.layout?.header?.showSubtitle;if(Ln&&(Ln.style.display=ge===!1?`none`:``),Rn&&(Rn.style.display=_e===!1?`none`:``),K){let e=rt()&&i.layout?.header?.showCloseButton!==!1;if(K.style.display=e?``:`none`,!F()){let e=j.closeButtonSize??``;K.style.height=e,K.style.width=e,K.style.minWidth=e,K.style.minHeight=e}let t=j.closeButtonPlacement??`inline`,{closeButtonWrapper:n}=z,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=Pd?.railColumn??B;e.style.position=`relative`,e.appendChild(n)}else{let e=j.clearChat?.placement??`inline`;n.className=(j.clearChat?.enabled??!0)&&e===`inline`?``:`persona-ml-auto`,zn&&zn.appendChild(n)}}if(K.style.color=j.closeButtonColor||zo.actionIconColor,j.closeButtonBackgroundColor?(K.style.backgroundColor=j.closeButtonBackgroundColor,K.classList.remove(`hover:persona-bg-gray-100`)):(K.style.backgroundColor=``,K.classList.add(`hover:persona-bg-gray-100`)),j.closeButtonBorderWidth||j.closeButtonBorderColor){let e=j.closeButtonBorderWidth||`0px`,t=j.closeButtonBorderColor||`transparent`;K.style.border=`${e} solid ${t}`,K.classList.remove(`persona-border-none`)}else K.style.border=``,K.classList.add(`persona-border-none`);j.closeButtonBorderRadius?(K.style.borderRadius=j.closeButtonBorderRadius,K.classList.remove(`persona-rounded-full`)):(K.style.borderRadius=``,K.classList.add(`persona-rounded-full`)),j.closeButtonPaddingX?(K.style.paddingLeft=j.closeButtonPaddingX,K.style.paddingRight=j.closeButtonPaddingX):(K.style.paddingLeft=``,K.style.paddingRight=``),j.closeButtonPaddingY?(K.style.paddingTop=j.closeButtonPaddingY,K.style.paddingBottom=j.closeButtonPaddingY):(K.style.paddingTop=``,K.style.paddingBottom=``),Fo(K,j.closeButtonIconName??`x`,{iconSize:F()?qs:void 0,iconText:j.closeButtonIconText??`×`});let o=j.closeButtonTooltipText??`Close chat`,s=j.closeButtonShowTooltip??!0;K.setAttribute(`aria-label`,o),n&&S({anchor:K,trigger:n,text:()=>K?.getAttribute(`aria-label`)??o,enabled:s})}let{clearChatButton:ve,clearChatButtonWrapper:ye}=z;if(ve){let e=j.clearChat??{},t=e.enabled??!0,n=i.layout?.header?.showClearChat,r=n===void 0?t:n,a=e.placement??`inline`;if(ye){ye.style.display=r?``:`none`;let{closeButtonWrapper:e}=z;!F()&&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=ye.classList.contains(`persona-absolute`);if(!F()&&t!==n&&r){if(ye.remove(),t){ye.className=`persona-absolute persona-top-4 persona-z-50`,ye.style.right=`48px`;let e=Pd?.railColumn??B;e.style.position=`relative`,e.appendChild(ye)}else{ye.className=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,ye.style.right=``;let e=z.closeButtonWrapper;zn&&e&&e.parentElement===zn?zn.insertBefore(ye,e):zn&&zn.appendChild(ye)}let e=z.closeButtonWrapper;e&&!e.classList.contains(`persona-absolute`)&&(t?e.classList.add(`persona-ml-auto`):e.classList.remove(`persona-ml-auto`))}}if(r){if(!F()){let t=e.size??``;ve.style.height=t,ve.style.width=t,ve.style.minWidth=t,ve.style.minHeight=t}let t=e.iconColor??``;if(ve.style.color=t||zo.actionIconColor,Fo(ve,e.iconName??`refresh-cw`,{iconSize:F()?Js:void 0}),e.backgroundColor?(ve.style.backgroundColor=e.backgroundColor,ve.classList.remove(`hover:persona-bg-gray-100`)):(ve.style.backgroundColor=``,ve.classList.add(`hover:persona-bg-gray-100`)),e.borderWidth||e.borderColor){let t=e.borderWidth||`0px`,n=e.borderColor||`transparent`;ve.style.border=`${t} solid ${n}`,ve.classList.remove(`persona-border-none`)}else ve.style.border=``,ve.classList.add(`persona-border-none`);e.borderRadius?(ve.style.borderRadius=e.borderRadius,ve.classList.remove(`persona-rounded-full`)):(ve.style.borderRadius=``,ve.classList.add(`persona-rounded-full`)),e.paddingX?(ve.style.paddingLeft=e.paddingX,ve.style.paddingRight=e.paddingX):(ve.style.paddingLeft=``,ve.style.paddingRight=``),e.paddingY?(ve.style.paddingTop=e.paddingY,ve.style.paddingBottom=e.paddingY):(ve.style.paddingTop=``,ve.style.paddingBottom=``);let n=e.tooltipText??`Clear chat`,r=e.showTooltip??!0;ve.setAttribute(`aria-label`,n),ye&&S({anchor:ve,trigger:ye,text:()=>ve?.getAttribute(`aria-label`)??n,enabled:r})}}let xe=i.actionParsers&&i.actionParsers.length?i.actionParsers:[Wl],Se=i.actionHandlers&&i.actionHandlers.length?i.actionHandlers:[Kl.message,Kl.messageAndClick];Re=Jl({parsers:xe,handlers:Se,getSessionMetadata:M,updateSessionMetadata:Me,emit:k.emit,documentRef:typeof document<`u`?document:null}),ct=ju(i,Re,st),yd(),Q.updateConfig(i),rf(),(i.features?.history?.enabled===!0!==v||i.features?.history?.provider!==y||i.getIdentityProof!==x||i.clientToken!==T)&&(Pd?.closeHistory({restoreFocus:!1}),Pd?.installHistoryProvider()),Pd?.syncHistoryChromeImpl(),Xd(),Rd()&&!Pd&&Jd().catch(()=>{}),Hl(H,Q.getMessages(),ct),us(),cd(),sd(),Ru(Q.isStreaming()),E!==i.contextMentions&&Gp();let we=i.voiceRecognition?.enabled===!0,Ee=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),De=Sn(i.voiceRecognition?.provider);if(we&&(Ee||De)){if(!J||!Gn){let e=Te(i);if(e){J=e.button,Gn=e.wrapper;let t=Un&&Un.parentElement===Hn?Un:null;Hn?Hn.insertBefore(Gn,t):En?.appendChild(Gn),_i&&(_i.micButton=J),_i?.addListener(J,`click`,lp),J.disabled=uu()||Q.isStreaming()&&!hu()}}else{let e=i.voiceRecognition??{},t=i.sendButton??{},n=e.iconName??`mic`,r=e.iconSize,a=parseFloat(r??``)||24;J.classList.add(A),J.classList.toggle(be,!r),J.style.width=r??``,J.style.height=r??``,J.style.minWidth=r??``,J.style.minHeight=r??``;let o=e.iconColor??t.textColor;J.innerHTML=``;let s=P(n,a,o||`currentColor`,1.5);s?J.appendChild(s):J.textContent=`🎤`;let c=e.backgroundColor??t.backgroundColor;c?J.style.backgroundColor=c:J.style.backgroundColor=``,o?J.style.color=o:J.style.color=`var(--persona-text, #111827)`,e.borderWidth?(J.style.borderWidth=e.borderWidth,J.style.borderStyle=`solid`):(J.style.borderWidth=``,J.style.borderStyle=``),e.borderColor?J.style.borderColor=e.borderColor:J.style.borderColor=``,e.paddingX?(J.style.paddingLeft=e.paddingX,J.style.paddingRight=e.paddingX):(J.style.paddingLeft=``,J.style.paddingRight=``),e.paddingY?(J.style.paddingTop=e.paddingY,J.style.paddingBottom=e.paddingY):(J.style.paddingTop=``,J.style.paddingBottom=``);let l=e.tooltipText??`Start voice recognition`,u=e.showTooltip??!1;J.setAttribute(`aria-label`,l),Gn&&S({anchor:J,trigger:Gn,text:()=>J?.getAttribute(`aria-label`)??l,enabled:u}),Gn.style.display=``,J.disabled=uu()||Q.isStreaming()&&!hu()}}else J&&Gn&&(Gn.style.display=`none`,Sn(i.voiceRecognition?.provider)?Q.isVoiceActive()&&Q.toggleVoice():zf&&np());if(vp(),i.attachments?.enabled===!0){if(!qn||!Kn){let e=i.attachments??{};Yn||(Yn=N(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),Yn.style.display=`none`,(U.parentElement??En).insertBefore(Yn,U)),Jn||(Jn=document.createElement(`input`),Jn.type=`file`,Jn.accept=(e.allowedTypes??ft).join(`,`),Jn.multiple=(e.maxFiles??4)>1,Jn.style.display=`none`,Jn.setAttribute(`aria-label`,`Attach files`),(U.parentElement??En).insertBefore(Jn,U)),qn=N(`div`,`persona-send-button-wrapper`),Kn=N(`button`,`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${A} ${be}`),Kn.type=`button`,Kn.setAttribute(`aria-label`,e.buttonTooltipText??`Attach file`);let t=e.buttonIconName??`paperclip`;Kn.style.fontSize=`18px`,Kn.style.lineHeight=`1`;let n=P(t,24,`currentColor`,1.5);n?Kn.appendChild(n):Kn.textContent=`📎`,Kn.addEventListener(`click`,e=>{e.preventDefault(),Jn?.click()}),qn.appendChild(Kn);let r=e.buttonTooltipText??`Attach file`;S({anchor:Kn,trigger:qn,text:()=>Kn?.getAttribute(`aria-label`)??r}),Vn?Vn.append(qn):En.appendChild(qn),_i&&(_i.attachmentButton=Kn,_i.attachmentInput=Jn??void 0,_i.attachmentPreviews=Yn??void 0),!jr&&Jn&&Yn&&(jr=$r.fromConfig(e,Rr),jr.setPreviewsContainer(Yn),_i?.addListener(Jn,`change`,async()=>{jr&&Jn?.files&&(await jr.handleFileSelect(Jn.files),Jn.value=``)}))}else{qn.style.display=``;let e=i.attachments??{};Jn&&(Jn.accept=(e.allowedTypes??ft).join(`,`),Jn.multiple=(e.maxFiles??4)>1),jr&&jr.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}if(B.querySelector(`.persona-attachment-drop-overlay`)?.remove(),B.appendChild(Mu(i.attachments?.dropOverlay)),Kn){let e=i.attachments??{},t=e.buttonTooltipText??`Attach file`;Kn.setAttribute(`aria-label`,t),Kn.textContent=``;let n=P(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);n?Kn.appendChild(n):Kn.textContent=`📎`,qn&&S({anchor:Kn,trigger:qn,text:()=>Kn?.getAttribute(`aria-label`)??t})}}else qn&&(qn.style.display=`none`),jr&&jr.clearAttachments(),B.querySelector(`.persona-attachment-drop-overlay`)?.remove();let Oe=i.sendButton??{},ke=Oe.useIcon??!1,Ae=Oe.iconText??`↑`,je=Oe.iconName,Ne=Oe.tooltipText??`Send message`,Pe=Oe.showTooltip??!1,Fe=Oe.size,Ie=parseFloat(Fe??``)||40,Le=Oe.backgroundColor,Be=Oe.textColor;if(ke){if(W.style.width=Fe??``,W.style.height=Fe??``,W.style.minWidth=Fe??``,W.style.minHeight=Fe??``,W.style.fontSize=`18px`,W.style.lineHeight=`1`,Be?W.style.color=Be:W.style.color=`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`,!Q.isStreaming()){if(W.innerHTML=``,je){let e=parseFloat(Oe.iconSize??``)||Math.round(Ie*.5),t=Be?.trim()||`currentColor`,n=Oe.iconStrokeWidth??2,r=P(je,e,t,n),i=P(Oe.stopIconName??`square`,e,t,n);r&&i?W.appendChild(Ce(r,i)):r?W.appendChild(r):W.textContent=Ae}else W.textContent=Ae}W.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${A}`,Le?(W.style.backgroundColor=Le,W.classList.remove(`persona-bg-persona-primary`)):(W.style.backgroundColor=``,W.classList.add(`persona-bg-persona-primary`))}else W.textContent=i.copy?.sendButtonLabel??`Send`,W.style.width=``,W.style.height=``,W.style.minWidth=``,W.style.minHeight=``,W.style.fontSize=``,W.style.lineHeight=``,W.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`,Le?(W.style.backgroundColor=Le,W.classList.remove(`persona-bg-persona-accent`)):W.classList.add(`persona-bg-persona-accent`),Be?W.style.color=Be:W.classList.add(`persona-text-white`);Oe.borderWidth?(W.style.borderWidth=Oe.borderWidth,W.style.borderStyle=`solid`):(W.style.borderWidth=``,W.style.borderStyle=``),Oe.borderColor?W.style.borderColor=Oe.borderColor:W.style.borderColor=``,Oe.paddingX?(W.style.paddingLeft=Oe.paddingX,W.style.paddingRight=Oe.paddingX):(W.style.paddingLeft=``,W.style.paddingRight=``),Oe.paddingY?(W.style.paddingTop=Oe.paddingY,W.style.paddingBottom=Oe.paddingY):(W.style.paddingTop=``,W.style.paddingBottom=``),Q.isStreaming()||W.setAttribute(`aria-label`,Ne),Fu(),Un&&S({anchor:W,trigger:Un,text:()=>W.getAttribute(`aria-label`)??Ne,enabled:Pe}),ia(),Oo();let He=Ui(Y.getState().activeModeIds,i.composer?.modes);Y.setActiveModeIds(He),Br().length>0!=!!Kr&&ji(),Kr?.render(He,Br());for(let e of[...Jr.keys()])Ri(e,i.composer?.modeGroups)||Jr.delete(e);Jr.forEach(e=>e.repaint()),Wr?.repaint(),Ei?.resolve();let Ue=$a(i,F());if(bo(),Ue){H.style.maxWidth=Ue,H.style.marginLeft=`auto`,H.style.marginRight=`auto`,H.style.width=`100%`,An.style.maxWidth=Ue,An.style.marginLeft=`auto`,An.style.marginRight=`auto`,An.style.width=`100%`;for(let e of[En,Tn,Yn,G])e&&(e.style.maxWidth=Ue,e.style.marginLeft=`auto`,e.style.marginRight=`auto`,e.style.width=`100%`)}else{H.style.maxWidth=``,H.style.marginLeft=``,H.style.marginRight=``,H.style.width=``,An.style.maxWidth=``,An.style.marginLeft=``,An.style.marginRight=``,An.style.width=``;for(let e of[En,Tn,Yn,G])e&&(e.style.maxWidth=``,e.style.marginLeft=``,e.style.marginRight=``,e.style.width=``)}let We=i.statusIndicator??{};if(C(G,En,We),w(G,We,Q?.getStatus()??`idle`),Q){let e=Q.getStatus();hn(G,(e=>e===`idle`?We.idleText??bt.idle:e===`connecting`?We.connectingText??bt.connecting:e===`connected`?We.connectedText??bt.connected:e===`error`?We.errorText??bt.error:e===`paused`?We.pausedText??bt.paused:e===`resuming`?We.resumingText??bt.resuming:bt[e])(e),We,e)}G.classList.remove(`persona-text-left`,`persona-text-center`,`persona-text-right`);let Je=We.align===`left`?`persona-text-left`:We.align===`center`?`persona-text-center`:`persona-text-right`;G.classList.add(Je),yi(),Lu(),Vi(),sn()},open(){rt()&&cu(!0,`api`)},close(){rt()&&cu(!1,`api`)},toggle(){rt()&&cu(!I,`api`)},reconnect(){Q.reconnectNow()},clearChat(){Sa=!1,c.clear(),o.clear(),s.clear(),l.clear(),Q.clearMessages(),i.layout?.topFade&&(V.scrollTop=0),V.removeAttribute(`data-persona-top-fade`),hs.clear(),ol();try{localStorage.removeItem(xu),i.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xu}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(i.clearChatHistoryStorageKey&&i.clearChatHistoryStorageKey!==xu)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),ue?.clear&&Oc(()=>ue.clear(),`[AgentWidget] Failed to clear storage adapter:`),de={},Re.syncFromMetadata(),jr?.clearAttachments(),zc(),ti(void 0),Xr(void 0),Ts(),xt?.clear(),Ct?.reset(),Yt?.update()},setMessage(e){return!U||Q.isStreaming()||uu()?!1:(!I&&rt()&&cu(!0,`system`),U.value=e,U.dispatchEvent(new Event(`input`,{bubbles:!0})),!0)},submitMessage(e){if(Q.isStreaming()||vu())return!1;let t=e?.trim()||U.value.trim();return t?(!I&&rt()&&cu(!0,`system`),U.value=``,U.style.height=`auto`,Fr(),Tf(t,{consumeDraft:!1}),!0):!1},getComposerState(){return Y.getState()},setQuote(e){let t=e?.text?.trim();t&&Xr({...e,text:t})},clearQuote(){Xr(void 0)},startVoiceRecognition(){return Q.isStreaming()?!1:Sn(i.voiceRecognition?.provider)?(Q.isVoiceActive()||Q.isBargeInActive()||(!I&&rt()&&cu(!0,`system`),$.manuallyDeactivated=!1,bc(),Q.toggleVoice().then(()=>{$.active=gc(),bc(),vc(`user`),$.active&&ap()})),!0):zf?!0:ep()?(!I&&rt()&&cu(!0,`system`),$.manuallyDeactivated=!1,bc(),tp(`user`),!0):!1},stopVoiceRecognition(){return Sn(i.voiceRecognition?.provider)?!Q.isVoiceActive()&&!Q.isBargeInActive()?!1:((Q.isBargeInActive()?Q.deactivateBargeIn():Q.toggleVoice()).then(()=>{$.active=!1,$.manuallyDeactivated=!0,bc(),vc(`user`),cp()}),!0):zf?($.manuallyDeactivated=!0,bc(),np(`user`),!0):!1},injectMessage(e){return!I&&rt()&&cu(!0,`system`),Q.injectMessage(e)},injectAssistantMessage(e){!I&&rt()&&cu(!0,`system`);let t=Q.injectAssistantMessage(e);return it&&(it=!1,at&&=(clearTimeout(at),null),setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)),t},injectUserMessage(e){return!I&&rt()&&cu(!0,`system`),Q.injectUserMessage(e)},injectSystemMessage(e){return!I&&rt()&&cu(!0,`system`),Q.injectSystemMessage(e)},injectMessageBatch(e){return!I&&rt()&&cu(!0,`system`),Q.injectMessageBatch(e)},injectComponentDirective(e){return!I&&rt()&&cu(!0,`system`),Q.injectComponentDirective(e)},injectTestMessage(e){!I&&rt()&&cu(!0,`system`),Q.injectTestEvent(e)},async connectStream(e,t){return Q.connectStream(e,t)},__pushEventStreamEvent(e){dt&&(rn(),nn(e.type,e.payload))},showEventStream(){dt&&li()},hideEventStream(){Zt&&ui()},isEventStreamVisible(){return Zt},listConversations(e){return Q.listConversations(e)},getActiveConversationId(){return Q.getActiveConversationId()},openConversation(e,t){return Yd(n=>n.openHistoryConversation(e,{focusComposer:t?.focus===!0}))},startNewConversation(e){return Yd(t=>t.startNewConversation({focusComposer:e?.focus===!0}))},warmSession(){Zd()},deleteConversation(e){return Yd(t=>t.deleteHistoryConversation(e))},renameConversation(e,t){return Yd(n=>n.updateHistoryConversation(e,{title:t}))},setConversationStarred(e,t){return Yd(n=>n.updateHistoryConversation(e,{starred:t}))},clearConversationHistory(e){return Yd(t=>t.clearConversationHistory(e))},resetHistoryIdentity(){return Yd(e=>e.resetHistoryIdentity())},async getVisitorToken(){let e=gd;if(!e)return null;let t=await e.get();return e===gd?t:null},getHistoryIdentityStatus(){let e=Pd?.historyProvider;return e?e.getIdentityStatus():Rd()?{state:`unavailable`,reason:`ineligible_mode`}:{state:`unavailable`,reason:`history_disabled`}},showHistory(e){return Rd()?Yd(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...e?.focus===void 0?{}:{focus:e.focus}})):Promise.resolve()},hideHistory(e){Pd?.closeHistory(e?.restoreFocus===void 0?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible(){return an},showArtifacts(){Kc(i)&&(Sa=!1,Ea=!0,go(),X?.setMobileOpen(!0))},hideArtifacts(){Kc(i)&&(Sa=!0,go())},upsertArtifact(e){return Kc(i)?(nt(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){Kc(i)&&Q.selectArtifact(e)},clearArtifacts(){Kc(i)&&Q.clearArtifacts()},getArtifacts(){return Q?.getArtifacts()??[]},getSelectedArtifactId(){return Q?.getSelectedArtifactId()??null},focusInput(){return ze&&!I&&!F()||!U?!1:(U.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){fs(e)},clearFollowUpSuggestions(){ds()},getMessages(){return Q.getMessages()},getStatus(){return Q.getStatus()},getPersistentMetadata(){return{...de}},updatePersistentMetadata(e){Me(e)},on(e,t){return k.on(e,t)},off(e,t){k.off(e,t)},isOpen(){return rt()&&I},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:rt()&&I,launcherEnabled:ze,voiceActive:$.active,streaming:Q.isStreaming()}},showCSATFeedback(e){!I&&rt()&&cu(!0,`system`);let t=H.querySelector(`.persona-feedback-container`);t&&t.remove();let n=yu({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitCSATFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});H.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},showNPSFeedback(e){!I&&rt()&&cu(!0,`system`);let t=H.querySelector(`.persona-feedback-container`);t&&t.remove();let n=bu({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitNPSFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});H.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(){Ad(),bd!=null&&(clearInterval(bd),bd=null),c.clear(),o.clear(),s.clear(),l.clear(),Z.forEach(e=>e()),L.remove(),_n?.remove(),Cp?.destroy(),wp?.remove(),Qo&&K.removeEventListener(`click`,Qo)}};if(((r?.debugTools??!1)||i.debug)&&typeof window<`u`){let e=window.AgentWidgetBrowser,t={controller:om,getMessages:om.getMessages,getStatus:om.getStatus,getMetadata:om.getPersistentMetadata,updateMetadata:om.updatePersistentMetadata,clearHistory:()=>om.clearChat(),setVoiceActive:e=>e?om.startVoiceRecognition():om.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)&&om.focusInput()};if(window.addEventListener(`persona:focusInput`,n),Z.push(()=>{window.removeEventListener(`persona:focusInput`,n)}),dt){let t=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&om.showEventStream()},n=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&om.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)&&om.showHistory()},i=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&om.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)&&om.showArtifacts()},o=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&om.hideArtifacts()},s=t=>{let n=t.detail;n?.instanceId&&n.instanceId!==e||n?.artifact&&om.upsertArtifact(n.artifact)},c=t=>{let n=t.detail;n?.instanceId&&n.instanceId!==e||typeof n?.id==`string`&&om.selectArtifact(n.id)},l=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&om.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 sm=Du(i.persistState);if(sm&&rt()){let e=Ou(sm.storage),n=`${sm.keyPrefix}widget-open`,r=`${sm.keyPrefix}widget-voice`,i=`${sm.keyPrefix}widget-voice-mode`;if(e){let a=sm.persist?.openState&&e.getItem(n)===`true`,o=sm.persist?.voiceState&&e.getItem(r)===`true`,s=sm.persist?.voiceState&&e.getItem(i)===`true`;if(a&&(Cp?.setPanelOpen(!0,`auto`),setTimeout(()=>{om.open(),setTimeout(()=>{if(o||s)om.startVoiceRecognition();else if(sm.persist?.focusInput){let e=t.querySelector(`textarea`);e&&e.focus()}},100)},0)),sm.persist?.openState&&(k.on(`widget:opened`,()=>{e.setItem(n,`true`)}),k.on(`widget:closed`,()=>{e.setItem(n,`false`)})),sm.persist?.voiceState&&(k.on(`voice:state`,t=>{e.setItem(r,t.active?`true`:`false`)}),k.on(`user:message`,t=>{e.setItem(i,t.viaVoice?`true`:`false`)})),sm.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(Ae&&rt()&&(Cp?.setPanelOpen(!0,`auto`),setTimeout(()=>{om.open()},0)),iu(),!ks){let e=Be(()=>{Q&&(Os++,hs.clear(),Hl(H,Q.getMessages(),ct))});Z.push(e)}O=()=>{Q&&(Os++,hs.clear(),Hl(H,Q.getMessages(),ct))},Q.getMessages().length>0&&zl(),ae=()=>{Q&&(Os++,hs.clear(),Hl(H,Q.getMessages(),ct))};let cm=Pe(()=>{Q&&(Os++,hs.clear(),Hl(H,Q.getMessages(),ct))});Z.push(cm);let lm=Gc(()=>{Q&&(Os++,hs.clear(),Hl(H,Q.getMessages(),ct),Wc()?.updateInlineArtifactBlocks(H,xa.artifacts,{suppressTransition:!0}),go())});return Z.push(lm),om},Iu=(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},Lu=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},Ru=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},zu=(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.")},Bu=(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`},Vu=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=``},Hu=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,Vu(e)},Uu=e=>{e.style.transition=``},Wu=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=``},Gu=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},Ku=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},qu=(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))},Ju=(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)},Yu=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)}},Xu=(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=``)},Zu=(e,t,n,r,i,a,o,s)=>{let c=To(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;qu(e,t,n,r,l),Ju(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`),Wu(t),Uu(r),Hu(r),Gu(n),Ku(i,r),Xu(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`),Hu(r),Lu(r,c.maxHeight),Xu(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`,Wu(t),Uu(r),Gu(n),Ku(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`,Uu(r),Vu(r),Ku(i,r);let a=Iu(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=``,Wu(t),Vu(r),Gu(n),Ku(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`,Ru(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(${Iu(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`}}},Qu=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return Bu(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){Bu(n,e)},destroy(){n.remove()}}},$u=(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?Yu(t):null};h();let g=()=>{Zu(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=Qa(()=>{h(),g()}))},y=()=>{p(),To(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,zu(o,To(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),To(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()}}},ed=(e,t)=>Co(t)?$u(e,t):Qu(e,t),td={desktop:{w:1280,h:800},mobile:{w:390,h:844}},nd=`persona-preview-shell-theme`,rd={load:()=>null,save:()=>{},clear:()=>{}},id=[`How do I get started?`,`Pricing & plans`,`Talk to support`];function ad(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function od(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 sd(e){let t=od(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 cd(e,t){let n=e.contentDocument;if(!n?.documentElement)return;let r=n.getElementById(nd);r||(r=n.createElement(`style`),r.id=nd,n.head.appendChild(r)),r.textContent=sd(t)}function ld(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="${ad(r)}">
|
|
200
|
+
<style id="${nd}">${sd(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 ud=()=>[{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()}],dd=e=>!!(e?.features?.toolCallDisplay?.activePreview||e?.features?.toolCallDisplay?.grouped||e?.features?.toolCallDisplay?.collapsedMode&&e.features.toolCallDisplay.collapsedMode!==`tool-call`||e?.features?.reasoningDisplay?.activePreview);function fd(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`&&dd(t)?[...ud(),...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 pd(e,t,n=[]){let r={...e.launcher,enabled:!0,autoExpand:t!==`minimized`},i={...e,launcher:r,suggestionChips:t===`home`?e.suggestionChips?.length?e.suggestionChips:id:e.suggestionChips,initialMessages:fd(t,e,n),storageAdapter:rd};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 md(e,t){let n=ne(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 hd(e,t){let n=e.scene??`conversation`;return pd(md(e,t),n,e.appendedMessages??[])}function gd(e){let t=e.compareMode??`off`,n=e.shellMode??`light`;return t===`themes`?[{mountId:`preview-light`,label:`Light`,config:hd(e,`light`),shellMode:`light`},{mountId:`preview-dark`,label:`Dark`,config:hd(e,`dark`),shellMode:`dark`}]:t===`baseline`&&(e.baselineConfig||e.baselineTheme)?[{mountId:`preview-baseline`,label:`Baseline`,config:hd({...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:hd(e,n),shellMode:n}]:[{mountId:`preview-current`,label:`Current`,config:hd(e,n),shellMode:n}]}function _d(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=td[u()]??td.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=td[n]??td.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=gd(n),s=u(),c=(n.compareMode??`off`)!==`off`,d=(n.scene??`conversation`)===`minimized`,f=n.widgetCssPath??`/widget-dist/widget.css`,g=n.buildSrcdoc??ld,_=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">${ad(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=Co(n.config),c=s?(()=>{let r=e.contentDocument?.getElementById(`preview-content-${t}`);if(!r)return null;let i=ed(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=Fu(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,Co(n.config),f))}S===0&&C()}function _(){if(o)return;let t=gd(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&&cd(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{_d as createThemePreview};
|