@runtypelabs/persona 4.29.1 → 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.d.cts +1 -1
- package/dist/approval-ui.d.ts +1 -1
- package/dist/artifacts-ui.d.cts +2 -2
- package/dist/artifacts-ui.d.ts +2 -2
- package/dist/{chunk-DGlFKA0r.js → chunk-B2HCRERn.js} +1 -1
- package/dist/{chunk-BcLIgi1h.js → chunk-Car1mORT.js} +1 -1
- package/dist/chunk-DrpuvY5W.js +1 -0
- package/dist/client-history.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/{composer-input-B0P4OtNi.d.cts → composer-input-C3Xh1Qzj.d.cts} +1 -1
- package/dist/{composer-input-B0P4OtNi.d.ts → composer-input-C3Xh1Qzj.d.ts} +1 -1
- package/dist/{context-mention-manager-DmLI_RM6.d.cts → context-mention-manager-BsEiGObk.d.cts} +1 -1
- package/dist/{context-mention-manager-DmLI_RM6.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-DVo1wbZs.d.cts → defaults-DN-L67ak.d.cts} +1 -1
- package/dist/{defaults-DVo1wbZs.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-BMnlmKnY.d.cts → fallback-speech-engine-Cph8FTux.d.cts} +1 -1
- package/dist/{fallback-speech-engine-BMnlmKnY.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 +51 -51
- 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 +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +37 -37
- package/dist/index.js.map +1 -1
- package/dist/{markdown-parsers-loader-CeovcyYf.d.cts → markdown-parsers-loader-C4Xze-Jw.d.cts} +1 -1
- package/dist/{markdown-parsers-loader-CeovcyYf.d.ts → markdown-parsers-loader-C4Xze-Jw.d.ts} +1 -1
- package/dist/{preview-Bkb4UrQC.d.cts → preview-m9QlqsZi.d.cts} +2 -2
- package/dist/{preview-Bkb4UrQC.d.ts → preview-m9QlqsZi.d.ts} +2 -2
- package/dist/{session-iLyKipoM.d.cts → session-BtvvmWnw.d.cts} +6 -6
- package/dist/{session-iLyKipoM.d.ts → session-BtvvmWnw.d.ts} +6 -6
- package/dist/session-reconnect.d.cts +2 -2
- package/dist/session-reconnect.d.ts +2 -2
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +54 -54
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +35 -35
- 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-BuDirJkQ.d.cts → types-DL-oBHE1.d.cts} +6 -0
- package/dist/{types-BuDirJkQ.d.ts → types-DL-oBHE1.d.ts} +6 -0
- package/dist/voice-client-tools.d.cts +1 -1
- package/dist/voice-client-tools.d.ts +1 -1
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.d.cts +2 -2
- package/dist/voice-runtime.d.ts +2 -2
- package/dist/voice-runtime.js +1 -1
- package/dist/voice-worklet-player.d.cts +2 -2
- package/dist/voice-worklet-player.d.ts +2 -2
- package/dist/{webmcp-runtime-entry-CXLjRt1k.d.cts → webmcp-runtime-entry-T6SU_TlL.d.cts} +1 -1
- package/dist/{webmcp-runtime-entry-CXLjRt1k.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/package.json +1 -1
- package/src/generated/runtype-openapi-contract.ts +6 -0
- package/src/session.test.ts +23 -0
- package/src/session.ts +35 -17
- 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 +120 -106
- package/src/ui.typing-indicator.test.ts +21 -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/dist/chunk-Csks3Qw1.js +0 -1
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{_ as e,a as t,b as n,c as r,d as i,f as a,g as o,i as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h,v as g,y as _}from"./chunk-DtmtfIkd.js";import{n as v,r as y}from"./chunk-D5B629Mj.js";import{t as b}from"./chunk-BtTP1Wgi.js";import{B as x,C as S,D as C,E as w,F as T,H as E,L as D,M as ee,N as te,O as ne,P as re,R as ie,S as ae,T as oe,U as se,V as O,W as ce,_ as le,a as ue,b as de,c as fe,d as k,f as pe,g as me,h as he,i as ge,j as _e,k as ve,l as ye,m as A,n as be,o as xe,p as Se,r as Ce,s as we,t as Te,u as Ee,v as De,w as Oe,x as ke,y as Ae,z as je}from"./chunk-BIhTjsVQ.js";import{i as Me,r as j,t as M}from"./chunk-D5BxWOFB.js";import{a as Ne,n as N,r as Pe,t as Fe}from"./chunk-BypiAEpx.js";import{c as Ie,d as Le,f as Re,i as ze,l as Be,m as Ve,n as He,p as Ue,r as We,t as Ge,u as Ke}from"./chunk-SE7Q9NmG.js";import{n as qe,r as Je,t as Ye}from"./chunk-BvhTpG6k.js";import{f as Xe,r as Ze,s as Qe,u as $e}from"./chunk-CD4-AYdH.js";import{a as et,i as tt,r as nt}from"./chunk-CfNME4R9.js";import{a as P,i as rt,n as it,r as F,t as at}from"./chunk-CPdEltCR.js";import{t as ot}from"./chunk-Csks3Qw1.js";import{a as st,c as ct,d as lt,l as ut,n as dt,o as ft,t as pt,u as mt}from"./chunk-BlTD-Wgn.js";import{a as ht,n as gt,r as _t,s as vt,t as yt}from"./chunk-DpyghsEW.js";import{n as bt}from"./chunk-DTDHeUsG.js";import{i as xt,n as St}from"./chunk-Bb41bKyp.js";import{t as Ct}from"./chunk-C8560fIY.js";import{i as wt,n as Tt,r as Et,t as Dt}from"./chunk-lwPt6bL9.js";import{t as Ot}from"./chunk-CQw6A6rt.js";import{n as kt}from"./chunk-py2YB6PV.js";import{a as At,c as jt,i as Mt,l as Nt,n as Pt,o as Ft,r as It,s as Lt,t as Rt}from"./chunk-CVMIncEY.js";import{a as zt,c as Bt,i as Vt,l as Ht,n as Ut,o as Wt,r as Gt,s as Kt,t as qt,u as Jt}from"./chunk-BExOAPZb.js";import{Activity as Yt,ArrowRight as Xt,Check as Zt,ChevronDown as Qt,ChevronUp as $t,Circle as en,Clock as tn,Copy as nn,File as rn,FileCode as an,FileSpreadsheet as on,FileText as sn,MessageSquare as cn,X as ln}from"lucide";import"partial-json";import{Idiomorph as un}from"idiomorph";const dn=[`persona-w-full`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-primary`,`persona-shadow-sm`,`persona-overflow-hidden`,`persona-px-0`,`persona-py-0`],fn=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),pn=(e,t)=>{let n=M(`div`,[`persona-message-bubble`,e,...dn].join(` `));return n.id=`bubble-${t}`,n.setAttribute(`data-message-id`,t),n},mn=e=>{let t=M(`button`,e.expandable?`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none`:`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none`);return t.type=`button`,e.expandable&&(t.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),t.setAttribute(`data-expand-header`,`true`)),t.setAttribute(`data-bubble-type`,e.bubbleType),t},hn=(e,t,n)=>{e.innerHTML=``;let r=b(t?$t:Qt,16,n,2);r?e.appendChild(r):e.textContent=t?`Hide`:`Show`},gn=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let r=M(`div`,`persona-flex persona-items-center`);hn(r,n.expanded,n.iconColor);let i=M(`div`,n.metaGap?`persona-flex persona-items-center persona-gap-2 persona-ml-auto`:`persona-flex persona-items-center persona-ml-auto`);return i.append(r),e.append(t,i),r},_n=e=>{let t=M(`div`,`persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted`);if(t.setAttribute(`data-persona-collapsed-preview`,e.previewKind),t.style.display=`none`,t.style.whiteSpace=`pre-wrap`,!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();fn(t,n)||(t.textContent=e.previewText),t.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},I=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&hn(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?``:`none`,e.collapsedPreview.style.display=e.expanded?`none`:e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?``:`none`},L=(e,t,n)=>{let r=n.stateSet.has(e),i=t.querySelector(`button[data-expand-header="true"]`),a=t.querySelector(`.persona-border-t`),o=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!i||!a)return;i.setAttribute(`aria-expanded`,r?`true`:`false`);let s=i.querySelector(`.persona-ml-auto`)?.querySelector(`:scope > .persona-flex.persona-items-center`);s&&hn(s,r,n.iconColor),a.style.display=r?``:`none`,o&&(o.style.display=r?`none`:o.textContent||o.childNodes.length?``:`none`)};function vn(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[n]:{...t===`tool`?ee:_e,...e?.future?.v5Defaults===!0?ne.features?.[n]:{},...e?.features?.[n]}}}}function yn(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[n]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function bn(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?`a moment`:t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function R(e,t,n,r){if(yn(n,r)!==`row`)return e;e.className=`persona-message-bubble persona-${r}-bubble persona-activity-row`,e.dataset.activityKind=r,r===`tool`&&n.toolCall?.shadow===void 0&&(e.style.boxShadow=`var(--persona-tool-bubble-shadow, none)`);let i=e.querySelector(`:scope > button`);if(!i)return e;i.className=`persona-activity-header`;let a=r===`tool`?t.toolCall:t.reasoning,o=a?.status!==`complete`,s=t.approval?.status??t.toolCall?.approvalStatus,c=t.toolCall?.interrupted?`interrupted`:s===`denied`?`denied`:s===`pending`?`awaiting-approval`:t.toolCall?.success===!1?`error`:o?a?.status===`pending`?`pending`:`running`:`done`;e.dataset.activityState=c;let l=M(`span`,`persona-activity-icon`);l.dataset.activityIcon=c;let u={pending:`circle`,running:`loader-circle`,done:`check`,error:`x`,denied:`x`,interrupted:`x`,"awaiting-approval":`clock`},d=r===`reasoning`?n.features?.reasoningDisplay?.iconName:void 0,f=d?N(d,16,`currentColor`,2):c===`pending`?b(en,16,`currentColor`,2):c===`awaiting-approval`?b(tn,16,`currentColor`,2):N(u[c],16,`currentColor`,2);f&&l.appendChild(f),i.querySelector(`.persona-reasoning-header-icon`)?.remove();let p=r===`tool`?`toolCallDisplay`:`reasoningDisplay`,m=n.features?.[p]?.iconVisibility??(n.future?.v5Defaults?`active`:`always`);if((m===`always`||m===`active`&&c!==`done`)&&i.prepend(l),r===`tool`&&a){let e=M(`span`,`persona-activity-duration`);o&&a.startedAt&&e.setAttribute(`data-tool-elapsed`,String(a.startedAt));let n=(r===`tool`?t.toolCall?.duration:void 0)??a.durationMs??(a.completedAt!==void 0&&a.startedAt!==void 0?a.completedAt-a.startedAt:void 0);e.textContent=n===void 0?``:bn(n),i.appendChild(e)}i.querySelector(`:scope > div:not(.persona-ml-auto)`)?.classList.add(`persona-activity-label`),i.querySelector(`.persona-ml-auto`)?.classList.add(`persona-activity-chevron`);let h=e.querySelector(`:scope > .persona-border-t`);return h?.classList.add(`persona-activity-body`),h&&(h.id=`activity-details-${t.id}`,i.setAttribute(`aria-controls`,h.id)),e}function xn(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{clearTimeout(i.get(e)),i.delete(e)};return{observe(a,o,s,c={}){let l=o===`tool`?a.toolCall:a.reasoning;if(l&&!n.has(a.id)&&(!t.has(a.id)&&l.status!==`complete`&&l.chunks?.some(Boolean)&&(t.add(a.id),c.autoExpand!==!1&&s.add(a.id)),t.has(a.id)&&l.status===`complete`&&!r.has(a.id))){if(r.add(a.id),c.autoCollapseDelay===!1)return;i.set(a.id,setTimeout(()=>{i.delete(a.id),s.delete(a.id),e(a.id,o)},c.autoCollapseDelay??1e3))}},manual(e){n.add(e),a(e)},prune(e){for(let i of/* @__PURE__ */ new Set([...t,...n,...r]))e.has(i)||(a(i),t.delete(i),n.delete(i),r.delete(i))},clear(){for(let e of i.keys())a(e);t.clear(),n.clear(),r.clear()}}}function Sn(e,t,n,r){let i=M(`div`,``);i.id=`bubble-${e.id}`,i.dataset.messageId=e.id;let a=M(`button`,``);a.type=`button`,a.dataset.expandHeader=`true`,a.dataset.bubbleType=`tool`,a.setAttribute(`aria-expanded`,String(n));let o=M(`div`,``);typeof r==`string`?o.textContent=r:o.appendChild(r),gn(a,o,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||`currentColor`,metaGap:!0});let s=M(`div`,`persona-border-t`);return s.id=`activity-details-${e.id}`,s.style.display=n?``:`none`,a.setAttribute(`aria-controls`,s.id),i.append(a,s),R(i,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:`row`}}},`tool`),i.dataset.personaToolGroup=`true`,t.features?.toolCallDisplay?.loadingAnimation===`shimmer`&&(i.dataset.activityGroupShimmer=`true`),{bubble:i,body:s}}function z(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Cn(e){return e?.type===`runtype`||e?.type===`custom`}const B=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function V(e){try{if(e?.type===`custom`&&e.custom){let t=e.custom,n=typeof t==`function`?t():t;return!!n&&typeof n.startListening==`function`}return e?.type===`runtype`&&e.runtype?!0:B()}catch{return!1}}const wn=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Tn=e=>e.includes(`|`),En=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},H=e=>`| ${e.join(` | `)} |`,U=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,Dn=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),W=e=>{if(!e||!e.includes(`|`))return e;let t=e.split(`
|
|
2
|
-
`),n=!1;for(let e=0;e<t.length-1;e++){let r=t[e],i=t[e+1];if(!
|
|
3
|
-
`):e},On=`var(--persona-md-table-scroll-fade, 24px)`,kn=/* @__PURE__ */ new WeakSet;function An(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(`persona-table-scroll`))return;let t=document.createElement(`div`);t.className=`persona-table-scroll`,e.replaceWith(t),t.appendChild(e)})}function jn(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute(`data-persona-scroll-x`);return}e.setAttribute(`data-persona-scroll-x`,``);let n=getComputedStyle(e).direction===`rtl`?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty(`--persona-fade-l`,n<=1?`0px`:On),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:On)}function Mn(e){kn.has(e)||(kn.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&jn(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(jn)}const{setLoader:Nn,load:Pn,provide:Fn,getSync:G}=Ne({fallbackImport:()=>import(`./chunk-B1-_pp-Y.js`)}),In=Pn,Ln=G,{setLoader:Rn,load:zn}=Ne({fallbackImport:()=>import(`./chunk-BkW8s3fj.js`)}),Bn=zn,{setLoader:K,load:Vn}=Ne({fallbackImport:()=>import(`./chunk-lA5CJCgK.js`)}),Hn=Vn;function Un(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function Wn(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=Un(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=Un(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}const Gn=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),q=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Kn=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=Gn(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:q(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},qn=(e,t)=>{let n=[],r=[],i=[],a=``,o,s=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let c of e){let e=Kn(c);if(e){let t=c.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&s(),r.length===0&&(a=c.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let l=t(c);l&&(s(),n.push(l))}return s(),n},{setLoader:Jn,load:Yn,provide:Xn}=Ne({fallbackImport:()=>import(`./chunk-BcLIgi1h.js`)}),Zn=Yn;var Qn=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const $n=e=>`reason`in e?e.reason:void 0,er=(e,t)=>e instanceof Qn&&e.code===t,tr=e=>e.voiceCaption||bt(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),nr=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),rr=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function ir(e){switch(e){case`json`:return f;case`regex-json`:return t;case`xml`:return u;default:return s}}var ar=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#l=null,this.clientSession=null,this.#u=null,this.#d=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null,this.#p=!1,this.#m=!1,this.#h=!1,this.#g=null,this.#_=/* @__PURE__ */ new Set,this.#v=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#y=null,this.#H=null,this.#W=null,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":ot,...e.headers},this.debug=!!e.debug,this.#n=e.streamParser??ir(e.parserType),this.#r=e.contextProviders??[],this.#i=e.requestMiddleware,this.#a=e.customFetch,this.#o=e.parseSSEEvent,this.#s=e.getHeaders,e.webmcp?.enabled===!0&&(this.#y=this.#x(e.webmcp))}#x(t){return Bn().then(r=>{let i=new r.WebMcpBridge(t,{recordToolDisplayTitles:n,getToolDisplayTitle:e,loadPolyfill:_});return this.#b!==void 0&&i.setConfirmHandler(this.#b),this.webMcpBridge=i,i}).catch(e=>(this.#y=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#S(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled===!0?(this.#y||=this.#x(this.config.webmcp),this.#y):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#b=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}getVoiceClientTools(){if(this.config.webmcp?.enabled!==!0)return null;let e=()=>this.#S(),t={open:async e=>(await Hn()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:o(t)}},onChange:t=>{let n=null,r=!1;return e().then(e=>{e&&!r&&(n=e.watchToolChanges(t))}),()=>{r=!0,n?.()}},execute:async(t,n,r)=>{let i=await e();return i?i.executeVoiceToolCall(t,n,r):{status:`failed`,error:{message:`WebMCP runtime failed to load.`}}}};return t}executeWebMcpToolCall(e,t,n){return this.config.webmcp?.enabled===!0?this.#S().then(r=>r?r.executeToolCall(e,t,n):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.config;if(!n)return{agentId:e,flowId:t};let i=Wn(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#w(){return this.config.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#T(e){return`${this.#w()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new Qn(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#w()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":ot,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await Zn();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await Zn()).historyErrorFor(this.#G(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#u||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#d===e?null:(this.#d=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#u)return this.#u;let e=this.#u=this.#N().then(t=>this.#u===e?(this.clientSession=t,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#u===e&&(this.#u=null)});return e}#E(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#p}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#D(){if(!this.#p){this.#j({state:`unavailable`,reason:`history_disabled`}),this.#p=!0,!this.#m&&typeof console<`u`&&(this.#m=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#v])e(!1)}}getHistoryIdentityStatus(){return this.#g??this.#O()}subscribeHistoryIdentityStatus(e){return this.#_.add(e),()=>{this.#_.delete(e)}}subscribeHistoryAvailability(e){return this.#v.add(e),this.#p&&e(!1),()=>{this.#v.delete(e)}}#O(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#p?{state:`unavailable`,reason:`history_disabled`}:this.#k():{state:`unavailable`,reason:`ineligible_mode`}}#k(){let e=this.#g;return e?.state===`browser_only`?e:this.#A()}#A(){return this.config.features?.history?.scope===`browser`?{state:`browser_only`,reason:`configured_browser_scope`}:this.config.getIdentityProof?{state:`browser_only`,reason:`proof_unavailable_before_binding`}:{state:`browser_only`,reason:`no_identity_provider`}}#j(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&$n(t)===$n(e);if(this.#g=e,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#_])t(e)}}async#M(e){let t=this.#E()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let i=this.#C(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.#T(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":ot},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.#D(),o)throw new Qn(`history_disabled`,`Visitor history is disabled for this surface`);return this.#M({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new Qn(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new Qn(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new Qn(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async#N(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#E()&&!t)return this.#P(e,!1);let n=await this.readVisitorToken();if(e&&n)try{let n=await this.#M({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#R(n,e,!1)}catch(n){if(!er(n,`not_found`)&&!er(n,`visitor_required`)&&!er(n,`history_disabled`))throw n;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#P(e,!0)}return this.#P(e,!1)}async#P(e,t){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let n=this.config.getStoredSessionId?.()||null,r=await this.#M({storedSessionId:n}),i=await this.#L(r);return this.#R(i,e,t)}async#I(e){let t=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.#M({storedSessionId:t,identityProof:e}),i=this.#R(r,n,!1);return this.clientSession=i,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint(),i}async#L(e){if(!e.visitor?.token||this.#h||!this.#E()&&e.durableRecovery?.enabled!==!0)return e;this.#h=!0;try{return await this.#M({storedSessionId:e.sessionId})}catch{return e}finally{this.#h=!1}}#R(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#z(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#d=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#E())throw new Qn(`history_disabled`,`Visitor history is disabled for this surface`);await this.historyInternals.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new Qn(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#M({conversationId:e,identityProof:n});return this.#z(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.historyInternals.historyBootstrapReady;let e=await this.#M({});return this.#z(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#E()&&this.#j(this.#A())}clearClientSession(){this.clientSession=null,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null}#B(){return`${this.#w()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},n=await fetch(this.#B(),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":ot},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.clientSession=null,this.#d=!1,this.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#V(e){e?.throwIfAborted();let t=this.config.identityProvider;if(t===void 0)return;let n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#H;#U(){let e=this;return this.#H??={get config(){return e.config},headers:this.#t,getHeaders:this.#s,debug:this.debug,clientApiBase:()=>e.#w(),getClientApiUrl:t=>e.#T(t),getWebMcpBridge:()=>e.#S(),sendWithClientToolsDiff:(t,n,r,i)=>e.#Y(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#W;#G(){let e=this;return this.#W??={HistoryClientError:Qn,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#w(),setHistoryIdentityStatus:t=>e.#j(t),browserOnlyStatus:()=>e.#k(),derivedBrowserOnly:()=>e.#A(),reinitWithProof:t=>e.#I(t),isHistoryCapable:()=>e.#E(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await Zn()).listConversations(this.#G(),e)}async getConversation(e,t){return(await Zn()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await Zn()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await Zn()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await Zn()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await Zn()).resetVisitor(this.#G())}async dispatch(e,t){return e.signal?.throwIfAborted(),In().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#q(e,t)}async#K(e,t){let n=qe();this.#l=n;let r=()=>this.#l===n,i=e=>{r()&&t(e)};t({type:`status`,status:`connecting`});try{let t=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException(`Turn superseded`,`AbortError`)},a=this.clientSession??await this.initSession();t();let o=async()=>{t();let n=a,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.#M({...r||this.#E()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);a=this.#R(i,n.conversationId??null,!1),this.clientSession=a,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await o();let s=await this.#te(e.messages),c=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,l=this.#E(),u={sessionId:a.sessionId,messages:e.messages.filter(tr).map(e=>{let t=l?ht(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},d=async()=>{t();let n=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return t(),this.#Y(a.sessionId,s.clientTools,async r=>{t();let i=await this.#V(e.signal);t();let o={...u,sessionId:a.sessionId,...r,...i&&{identityProof:i}};return this.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.#T(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":ot,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},f=await d();if(t(),f.response.status===401){let e=await f.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await o(),f=await d(),t())}let{response:p,commit:m}=f;if(!p.ok){let e=await p.json().catch(()=>({error:`Chat request failed`}));if(p.status===401&&e.error===`invalid_identity_proof`){let e=new Qn(`invalid_identity_proof`,`The identity proof was rejected`);throw i({type:`error`,error:e}),e}if(p.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw i({type:`error`,error:e}),e}if(p.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw i({type:`error`,error:t}),t}if(p.status===410&&e.error===`conversation_deleted`){let e=new Qn(`conversation_deleted`,`This conversation was deleted`);throw i({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw i({type:`error`,error:t}),t}if(!p.body){let e=/* @__PURE__ */ Error(`No response body received`);throw i({type:`error`,error:e}),e}m(),i({type:`status`,status:`connected`});try{await this.#ne(p.body,i,e.assistantMessageId)}finally{i({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof Qn)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&i({type:`error`,error:t}),t}}async#q(e,t){t({type:`status`,status:`connecting`});let n=await this.#te(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t)}finally{t({type:`status`,status:`idle`})}}async#J(e,t){t({type:`status`,status:`connecting`});let n=await this.#ee(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t,e.assistantMessageId)}finally{t({type:`status`,status:`idle`})}}async processStream(e,t,n,r){t({type:`status`,status:`connected`});try{await this.#ne(e,t,n,r)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t,n){return(await In()).resolveApproval(this.#U(),e,t,n)}async#Y(e,t,n,r){let i=!!(t&&t.length>0),a=i?o(t):void 0,s=this.clientToolsFingerprintSessionId===e,c=i&&s&&this.lastSentClientToolsFingerprint===a,l=!i&&r?.emptyMeansReplace===!0&&this.#f===e,u=!1,d;for(let e=0;d=await n({...i&&(u||!c)&&t?{clientTools:t}:{},...l?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),d.status===409&&e===0&&i&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,i?this.#f=e:l&&(this.#f=null)}}}async resumeFlow(e,t,n){return(await In()).resumeFlow(this.#U(),e,t,n)}#X(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#Z(e){let t={};this.#r.length&&await Promise.all(this.#r.map(async n=>{try{let r=await n({messages:e,config:this.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#X(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#Q(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#$(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#ee(e,t){let n=this.#C().agentId;if(!this.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=qn(nr(e),e=>tr(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?rr(e):null),i=this.#Q(t),a={agent:this.#$(this.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.config.agentOptions}};i&&(a.composerOptions=i);let o=[...P(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#Z(e);return s&&(a.context=s),a}async#te(e,t){let n=qn(nr(e),e=>tr(e)?rr(e):null),r=this.#C(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...P(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#Z(e);o&&(i.context=o);let s=this.#Q(t);if(s&&(i.composerOptions=s),this.#i)try{let e=await this.#i({payload:{...i},config:this.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}async#ne(e,t,n,r){let{streamResponse:i}=Ln()??await In();return i({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#o,onSSEEvent:(e,t)=>this.#c?.(e,t)},e,t,n,r)}};const{setLoader:or,load:sr,provide:cr,getSync:lr}=Ne({fallbackImport:()=>import(`./chunk-U_UTkSiO.js`)}),ur=sr,dr=lr,{setLoader:fr,load:pr,provide:mr,getSync:hr}=Ne({fallbackImport:()=>import(`./chunk-DjFpGFGA.js`)}),gr=pr,_r=hr,vr=e=>typeof e==`object`&&!!e&&!Array.isArray(e),yr=(e,t)=>{let n=/* @__PURE__ */ new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!vr(e))return[];let{toolCallId:r,name:i}=e;if(typeof r!=`string`||!r||typeof i!=`string`||!i||n.has(r))return[];n.add(r);let a=vr(e.arguments)?e.arguments:{},o=e.result??null;return[{id:`voice-tool-${r}`,role:`assistant`,variant:`tool`,content:``,createdAt:t,streaming:!1,toolCall:{id:r,name:i,status:`complete`,args:a,result:o},agentMetadata:{clientToolAnswer:{toolCallId:r,toolName:i,args:a,result:o}}}]})},br=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function xr(e){let t=e?.text?.trim()??``;return t?wt(br(e),t):``}function Sr(e){let t=xr(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[st(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
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 zr=()=>import(`./chunk-59UOGW9N.js`),{setLoader:Br,load:Vr}=Ne({fallbackImport:()=>import(`./chunk-DO9_WSpy.js`)}),Hr=Vr,Ur=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function Wr(e,t){return Ur.some(n=>e[n]!==t[n])}var Gr=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function Kr(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.`;return n.message?`${r}\n\n_Details: ${n.message}_`:r}const qr=e=>g(e)||e===`suggest_replies`;var Jr=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.streaming=!1,this.#e=/* @__PURE__ */ new Map,this.abortController=null,this.#n=Date.now(),this.clientSession=null,this.agentExecution=null,this.#r=null,this.#i=null,this.#a=!1,this.#o=null,this.#s=null,this.#c=null,this.artifacts=/* @__PURE__ */ new Map,this.#l=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#u=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#d=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#f=null,this.#p=null,this.#m=0,this.#h=0,this.#g=!1,this.#_=`disconnected`,this.#v=null,this.#y=null,this.#b=null,this.#x=0,this.#S=!1,this.#C=null,this.#w=!1,this.#T=null,this.#E=/* @__PURE__ */ new Map,this.#D=null,this.#O=/* @__PURE__ */ new Map,this.#k=null,this.#A=null,this.#j=!1,this.#M=null,this.#N=null,this.#P=!1,this.#F=null,this.#R=null,this.#z=null,this.#B=new jr,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Ar(()=>this.#W()),this.#Ie=null,this.#Le=0,this.handleEvent=e=>{let t=this.#U,n=!1;if(t&&(e.type===`error`||e.type===`status`&&e.status===`error`?t.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),n=!0)),e.type===`message`){this.upsertMessage(e.message),n&&t.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#e.set(e.message.id,this.#t),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&gr().catch(()=>{});let r=e.message.toolCall,i=!!r?.name&&(g(r.name)||r.name===`suggest_replies`&&et(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&i&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#ze(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type===`cursor`)this.#Je(e.id);else if(e.type===`status`){if(e.status===`idle`&&!e.terminal&&this.#Ye()){this.#Ze();return}if(this.#st(e.status),e.status===`connecting`)this.#ct(!0);else if(e.status===`idle`||e.status===`error`){this.#Xe()||this.#at(),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null,this.#Oe(),this.#Ce());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#Be()}}else e.type===`error`?(this.#st(`error`),this.#at(),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#qe(e)},this.historyInternals=this.#X(n),this.messages=[...e.initialMessages??[]].map(e=>({...y(e),sequence:e.sequence??this.#mt()})),this.messages=this.#ht(this.messages),this.client=new ar(e,this.historyInternals),this.#me(),this.#Fe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#l=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ke(),this.callbacks.onStatusChanged(this.status),this.#L(),this.#I()}#I(){this.config.voiceRecognition?.provider&&Pr().catch(()=>{})}#L(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&zr().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return V(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#g}getVoiceStatus(){return this.#_}getVoiceNotice(){return this.#f?.takeNotice?.()??null}getVoiceDisclosure(){return this.#f?.getDisclosure?.()??null}getVoiceLevel(){return this.#f?.onLevel?this.#h:null}getVoiceInterruptionMode(){return this.#f?.getInterruptionMode?this.#f.getInterruptionMode():`none`}stopVoicePlayback(){this.#f?.stopPlayback&&(this.#B.cancel(),this.#H?.cancel(),this.#f.stopPlayback())}isBargeInActive(){return this.#f?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#f?.deactivateBargeIn&&await this.#f.deactivateBargeIn()}#R;#z;#B;#V;#H;#U;#W(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=kr.isSupported()?new kr({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return zr().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#V,r=++this.#m;this.#p=Pr().then(async e=>{await n,r===this.#m&&this.#G(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#m&&(this.#p=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#G(e,t){this.#f=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#f,generation:()=>n.#m,get keyed(){return n.#H},set keyed(e){n.#H=e},get pendingUser(){return n.#R},set pendingUser(e){n.#R=e},get pendingAssistant(){return n.#z},set pendingAssistant(e){n.#z=e},turns:()=>n.#B,busy:()=>n.#K(),setStreaming:e=>n.#ct(e),setDelegation:e=>{n.#U=e},setLevel:e=>{n.#h=e},setStatus:e=>{n.#_=e,n.#g=e===`listening`},settlePending:e=>n.#J(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#f&&this.#p&&await this.#p,!this.#f)console.error(`Voice not configured`);else if(this.#g)await this.#f.stopListening();else{this.stopSpeaking();try{await this.#f.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}prewarmVoice(){if(!Cn(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#m,t=()=>{let t=this.#f;t?.prewarm&&e===this.#m&&(this.#g||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#f&&this.#p?this.#p.then(t,()=>{}):t()}#K(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||this.status===`resuming`}cleanupVoice(){let e=this.#f!==null;if(this.#m++,this.#p=null,this.#f){let e=this.#f;this.#f=null,this.#V=this.#q(e)}this.#g=!1,this.#_=`disconnected`,this.#J(!0),this.#H?.settle(),this.#H=null,this.#B=new jr,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#q(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#J(e){let t=e?this.#R:null,n=this.#z;(t||n)&&(n&&this.#B.cancel(),e&&(this.#R=null),this.#z=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#ct(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#A=this.historyInternals.getStoredConversationRevision?.()??null,this.#j=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#Y(e,t)}#Y(e,t=!this.messages.length){if(this.#S||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#mt()};this.#ft(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#X(e),this.client.setHistoryInternals(this.historyInternals),this.#me()}destroy(){this.cleanupVoice(),this.#M?.(),this.#M=null,this.#N=null}#X(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#pe(e),t?.(e)}}}get#Z(){return this.historyInternals.historyProvider??null}#Q(){let e=this.#Z;if(!e)throw new Gr(`history_unavailable`,`No conversation history provider is installed`);return e}#$(e){let t=this.#Q(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new Ct(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#v,conversationRevision:this.#y,nextMessageCursor:this.#b,recovery:this.#C,sendBlocked:this.#w}}getActiveConversationId(){return this.#v}#ee(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#te(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#T;e&&await e.catch(()=>{});let t=this.#D;t&&await t.catch(()=>{})}#ne(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new Gr(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#Q().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#$(e?.scope)})}async openConversation(e,t){let n=this.#Q();this.#ne();let r=this.#$(t?.scope);await this.awaitHistorySettled();let i=++this.#x,a=await n.getPage(e,{context:r});if(i!==this.#x)throw new Gr(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new Gr(`superseded`,`A later selection won`);this.#S=!0;try{await this.#le(o)}finally{this.#S=!1}this.#v=o.conversationId||e,this.#y=o.conversationRevision||a.conversationRevision||null,this.#b=a.nextCursor,this.#C=null,this.#w=!1,this.#de();for(let e of a.messages)this.#O.set(e.id,e.content);return this.#ue(),this.hydrateMessages(a.messages),this.#ee(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,n){let r=this.#Q(),i=this.#$(n?.scope),a=t??this.#b;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#E.get(o);if(s)return s;let c=this.#re(r,e,a,i).finally(()=>{this.#E.delete(o)});return this.#E.set(o,c),c}async#re(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#v&&this.#v!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ie(a.messages),s=vt(this.messages,o);this.messages=this.#ht(s.map(e=>this.#pt(e))),this.#b=a.nextCursor;for(let e of a.messages)this.#O.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#ee(),{messages:o,nextMessageCursor:a.nextCursor}}#ie(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&v(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return y(e)})}async startNewConversation(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=++this.#x,i=await t.prepareStartNew({context:n});if(r!==this.#x)throw i.discard(),new Gr(`superseded`,`A later action won`);await this.#ae(i)}async#ae(e){this.#fe(),await this.#le(e),this.#v=e.conversationId||null,this.#y=e.conversationRevision||null,this.#b=null,this.#C=null,this.#w=!1,this.#ue(),this.#ee()}async deleteConversation(e,t){let n=this.#Q(),r=this.#$(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),e===this.#v&&await this.#oe(r)}async updateConversation(e,t,n){let r=this.#Q();if(!r.update)throw new Gr(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#$(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#Z?.update==`function`}async clearConversationHistory(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return await this.#oe(n),r}async resetHistoryDevice(){let e=this.#Q();if(!e.resetDevice)throw new Gr(`history_unavailable`,`This history provider cannot reset the device`);this.#x+=1,this.#D=null;try{return await e.resetDevice()}finally{this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#w=!1,this.#ee()}}async#oe(e){this.#x+=1,this.#D=null,this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#w=!0,this.#C=null,this.#ee(),await this.#se(e)}async#se(e){let t=this.#Z;if(!t)this.#w=!1,this.#ee();else try{let n=await t.prepareStartNew({context:e});await this.#ae(n)}catch{this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#ce(){if(this.#C===`new_conversation_required`&&this.#Z&&(this.#C=null,await this.#se(this.#$()),this.#C===`new_conversation_required`))throw new Gr(`new_conversation_required`,`A new conversation is required before sending`)}async#le(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#v=e.conversationId,this.#y=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#S||this.#Y(e)}#ue(){this.#v?this.config.setStoredConversationId?.(this.#v):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#y),this.historyInternals.setStoredMessageCursor?.(this.#b)}#de(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#O.clear(),this.#be(null)}#fe(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.messages=[],this.#de(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}#pe(e){this.#x+=1,this.#D=null,this.#w=!0,this.#fe(),this.#v=e.conversationId,this.#y=null,this.#b=null,this.#C=null,this.#ee(),this.#te(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#T=Promise.resolve().then(()=>{this.#w=!1,this.#T=null,this.#ee()})}#me(){let e=this.historyInternals.visitorStore??null;e!==this.#N&&(this.#M?.(),this.#M=null,this.#N=e,e&&(this.#M=e.subscribe(e=>this.#he(e))))}#he(e){if(e.source!==`external`||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#D=null,this.#P=!0,this.#F=null;let t=this.messages.length>0;t||this.#v!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#fe():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#be(null)),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#ee(),t&&this.#te(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#ge(){return this.#P?(this.#F||=this.#_e().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#_e(){if(!this.isClientTokenMode())this.#P=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#P=!1}catch{}}reconcileBootConversation(e){let t=this.#Z,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#v;if(!t||!n)return Promise.resolve();let r=this.#$(e?.scope);this.#w=!0,this.#ee();let i=this.#ve(t,n,r).finally(()=>{this.#w=this.#C!==null,this.#T===i&&(this.#T=null),this.#ee()});return this.#T=i,i}async#ve(e,t,n){this.#v=t;let r=this.clientSession?.conversationRevision??this.#y??null,i=this.#j?this.#A:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#j=!1,this.#b=this.historyInternals.getStoredMessageCursor?.()??this.#b,await this.replayPendingProjections(),r&&i&&r===i){this.#y=r;return}let a=await e.getPage(t,{context:n}),o=this.#ie(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#pt(e));else{let e=this.#r?this.#i:null,t=this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l);u=vt(t,o).map(e=>this.#pt(e))}this.#b=a.nextCursor,this.#y=a.conversationRevision||r||null,this.#O.clear();for(let e of a.messages)this.#O.set(e.id,e.content);this.#ue(),this.messages=this.#ht(u),this.callbacks.onMessagesChanged([...this.messages])}#ye(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#be(e){this.#k=e,this.historyInternals.setPendingDisplayProjections?.(e)}#xe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#k}#Se(e){if(this.#ye())for(let t of e){let e=ht(t);e!==void 0&&this.#O.set(t.id,e)}}#Ce(){if(!this.#ye())return;let e=this.#v;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=ht(e);n!==void 0&&this.#O.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#be({conversationId:e,messageIds:t.map(e=>e.id)}),this.#we(e,t))}#we(e,t){let n=(this.#D??Promise.resolve()).catch(()=>{}).then(()=>this.#Te(e,t,!1)).finally(()=>{this.#D===n&&(this.#D=null)});this.#D=n}async#Te(e,t,n){if(this.#v!==e)return;let r=t.filter(e=>this.#O.get(e.id)!==e.displayContent);if(r.length===0)this.#De(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#O.set(e.id,e.displayContent);this.#v===e&&n&&(this.#y=n),this.#De(e,t)}catch(i){if(!n&&this.#Ee(i)){await this.#Te(e,r,!0);return}if(i instanceof Qn&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#De(e,t);return}this.#te(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Ee(e){return e instanceof Qn?e.code===`request_failed`:e instanceof Error}#De(e,t){let n=this.#xe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#be(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ye())return;let e=this.#xe();if(!e)return;if(this.#v&&e.conversationId!==this.#v){this.#be(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#be(null):(this.#we(e.conversationId,t),await this.#D?.catch(()=>{}))}#Oe(){this.#v&&(this.#y=null,this.historyInternals.setStoredConversationRevision?.(null))}async#ke(){await this.awaitHistorySettled(),await this.#ge(),this.#C===`new_conversation_required`&&await this.#ce()}static#Ae(e){return e instanceof Qn&&e.code===`conversation_deleted`}async#je(t,n,r,i,a){this.#Se(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent);return}catch(t){if(!e.#Ae(t))throw t;let o=await this.#Me(i);if(!o)throw t;this.#Se([o]),await this.client.dispatch({messages:[o],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent)}}async#Me(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#x+=1,this.#D=null,this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#S=!0;try{let e=this.#Z;if(e){let t=await e.prepareStartNew({context:this.#$()});await this.#ae(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#S=!1}return this.#ft(n),this.#ct(!0),this.#te(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=z(this.config,n),i=Wr(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&Cn(n.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#We();return}this.#He(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.client=new ar(this.config,this.historyInternals),a&&this.#We(),this.#Fe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e,f={id:a??(t===`user`?Je():t===`assistant`?Ye():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#mt(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=[];for(let n of e){let{role:e,content:r,llmContent:i,contentParts:a,id:o,createdAt:s,sequence:c,streaming:l=!1,voiceProcessing:u,rawContent:d}=n,f={id:o??(e===`user`?Je():e===`assistant`?Ye():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:r,createdAt:s??(/* @__PURE__ */ new Date()).toISOString(),sequence:c??this.#mt(),streaming:l,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...d!==void 0&&{rawContent:d}};t.push(f)}return this.messages=this.#ht([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}async#Ne(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
|
|
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(st(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(st(a)),t.push(...r.contentParts),e.contentParts=t}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,t){let n=e.trim(),r=!!t?.replayFields&&(t.replayFields.llmContent!==void 0||t.replayFields.rawContent!==void 0||(t.replayFields.contextMentions?.length??0)>0);if(!n&&(!t?.contentParts||t.contentParts.length===0)&&(!t?.mentions||t.mentions.refs.length===0)&&!r)return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#T||this.#D||this.#w||this.#P)&&await this.#ke(),this.stopSpeaking(),this.abortController?.abort(),this.#He(),this.#Le++,this.#it();let i=t?.voiceTurn?.userMessageId,a=i?this.messages.find(e=>e.id===i&&e.role===`user`):void 0,o=a?.id??Je(),s=Ye();this.#i=null;let c=t?.contentParts&&ut(t.contentParts)?dt:``,l={id:o,role:`user`,content:n||c,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#mt(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==n&&(a.llmContent=n),this.callbacks.onMessagesChanged([...this.messages])):this.#ft(l),this.#ct(!0);let u=new AbortController;if(this.abortController=u,t?.mentions){let e=this.messages.find(e=>e.id===o)??l;if(await this.#Ne(e,n,t.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===o)??l,n=Sr({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});n.contentParts&&(e.contentParts=n.contentParts),n.llmContent!==void 0&&(e.llmContent=n.llmContent),(n.contentParts||n.llmContent!==void 0)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let d=(/* @__PURE__ */ new Date()).toISOString(),f=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:d}]:[...this.messages],p=(a??this.messages.find(e=>e.id===o))?.createdAt??d,m=yr(t?.voiceTurn?.priorToolResults,p);for(let e of m)this.messages.some(t=>t.id===e.id)||(this.#ft(e),f.push({...e,createdAt:d}));let h=m.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:n,args:r,result:i}=e.clientToolAnswer;return{toolCallId:t,name:n,arguments:r,result:i}});try{await this.#je(f,u,s,o,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn,...h.length>0&&{voicePriorToolResults:h}})}catch(e){if(this.status===`resuming`||this.#a)return;this.#U&&(this.#U.failed=!0);let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));if(!t){let t=Kr(e,this.config.errorMessage);if(t){let e={id:s,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:t,localOnly:!0,sequence:this.#mt()};this.#ft(e)}}this.#st(`idle`),this.#ct(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let n=wr(this.messages,e);if(!n)return!1;let r=this.messages[n.start],i=t.replacement,a=i?i.text:r.content,o=i?i.contentParts:r.contentParts;if(!(a?.trim()||(o?.length??0)>0||!i&&(r.llmContent?.trim()?.length??0)>0))return!1;let s=i?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},c=i?this.#Pe(i.options):r.composerOptions,l=i?i.contentSegments:r.contentSegments,u=i?i.options?.quote:void 0,d=i?i.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(a??``,{...o?.length?{contentParts:[...o]}:{},...l?.length?{contentSegments:[...l]}:{},...c?{composerOptions:c}:{},...u?{quote:u}:{},...s&&Object.keys(s).length>0?{replayFields:s}:{},viaVoice:d===!0}),!0}#Pe(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#T||this.#D||this.#w||this.#P)&&await this.#ke(),this.abortController?.abort(),this.#it();let e=Ye();this.#i=null,this.#ct(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if(this.status===`resuming`||this.#a)return;let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));if(!n){let n=Kr(t,this.config.errorMessage);if(n){let t={id:e,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:n,localOnly:!0,sequence:this.#mt()};this.#ft(t)}}this.#st(`idle`),this.#ct(!1),this.abortController=null,n||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#i=t.assistantMessageId);let n=t?.preserveAssistantId?t.assistantMessageId:void 0,r=!1;for(let e of this.messages)e.streaming&&e.id!==n&&(e.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#ct(!0);let i={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=i;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#lt(i)}catch(e){if(this.status===`resuming`||this.#a){this.#ut(i);return}this.#lt(i),this.#st(`error`),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Fe(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t;do t=`webmcp-${++this.#d}`;while(this.messages.some(e=>e.id===`approval-${t}`||e.approval?.id===t));let n={id:t,status:`pending`,agentId:``,executionId:``,toolName:e.toolName,toolType:`webmcp`,description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,approval:n}),new Promise(t=>{this.webMcpApprovalResolvers.set(r,t),e.signal?.addEventListener(`abort`,()=>this.resolveWebMcpApproval(r,`timeout`),{once:!0})})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(t=>t.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:t,resolvedAt:Date.now()}}),n(t===`approved`)}#Ie;#Le;#Re(e){let t=this.#Ie??={s:this,setStreaming:e=>this.#ct(e),appendMessage:e=>this.#ft(e),nextSequence:()=>this.#mt(),settleApprovalPausedToolCall:e=>this.#dt(e),resumeAfter:e=>this.#r?.executionId===e?this.#r.lastEventId:void 0},n=_r();if(n)return e(n,t);let r=this.#Le;return gr().then(n=>r===this.#Le?e(n,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,n){return this.#Re((r,i)=>r.resolveApproval(i,e,t,n))}resolveAskUserQuestion(e,t){return this.#Re((n,r)=>n.resolveAskUserQuestion(r,e,t))}resolveWebMcpToolCall(e){return this.#Re((t,n)=>t.resolveWebMcpToolCall(n,e))}persistAskUserQuestionProgress(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#ze(e){let t=e.agentMetadata?.executionId,n=e.toolCall?.id;if(!t||!n){let t=this.#u;queueMicrotask(()=>{t===this.#u&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(t);r||(r={snapshots:[],seen:/* @__PURE__ */ new Set},this.webMcpAwaitBatches.set(t,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(e))}#Be(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#u;queueMicrotask(()=>{if(e===this.#u)for(let e of[...this.webMcpAwaitBatches.keys()])this.#Ve(e)})}#Ve(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.#Re((t,r)=>t.resolveWebMcpToolCallBatch(r,e,n))}#He(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,`denied`);this.webMcpAwaitBatches.clear(),this.#u++}cancel(){this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ct(!1),this.#st(`idle`)}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.messages=[],this.agentExecution=null,this.#Ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#l}selectArtifact(e){this.#l=e,this.#Ke()}clearArtifacts(){this.#Ge()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=e.artifactType===`markdown`?{id:t,artifactType:`markdown`,title:e.title,status:`complete`,markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:`component`,title:e.title,status:`complete`,component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,n),this.#l=t,this.#Ke(),e.transcript!==!1&&this.#Ue(n),n}#Ue(e){let t=`artifact-ref-${e.id}`,n=rt(this.config.features?.artifacts,e),r=at(n,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:`complete`,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown===void 0?{}:{markdown:e.markdown}}),i=this.messages.find(e=>e.id===t);i?(i.rawContent=r,i.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:``,rawContent:r})}#We(){let e=!1;for(let t of this.artifacts.values()){let n=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!n)continue;let r=rt(this.config.features?.artifacts,t),i=at(r,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown===void 0?{}:{markdown:t.markdown}});n.rawContent!==i&&(n.rawContent=i,n.streaming=t.status===`streaming`,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Ge(){(this.artifacts.size!==0||this.#l!==null)&&(this.artifacts.clear(),this.#l=null,this.#Ke())}#Ke(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#l})}#qe(e){switch(e.type){case`artifact_start`:e.artifactType===`markdown`?this.artifacts.set(e.id,{id:e.id,artifactType:`markdown`,title:e.title,status:`streaming`,markdown:``,...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:`component`,title:e.title,status:`streaming`,component:e.component??``,props:{}}),this.#l=e.id;break;case`artifact_delta`:{let t=this.artifacts.get(e.id);t?.artifactType===`markdown`&&(t.markdown=(t.markdown??``)+e.artDelta);break}case`artifact_update`:{let t=this.artifacts.get(e.id);t?.artifactType===`component`&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case`artifact_complete`:{let t=this.artifacts.get(e.id);t&&(t.status=`complete`);break}default:return}this.#Ke()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ht(e.map(e=>({...y(e),streaming:!1,sequence:e.sequence??this.#mt()}))),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:`complete`});this.#l=t,this.#Ke()}#Je(e){let t=this.agentExecution?.executionId;if(!t||!this.#i||this.agentExecution?.status!==`running`)return;let n=this.#r===null;this.#r={executionId:t,lastEventId:e,assistantMessageId:this.#i,status:`running`},this.#ot(n)}#Ye(){return this.#r!==null&&typeof this.config.reconnectStream==`function`&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Xe()}#Xe(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant===`approval`&&e.approval?.status===`pending`)}#Ze(){this.#a||this.#r&&typeof this.config.reconnectStream==`function`&&(this.#a=!0,this.callbacks.onReconnect?.({phase:`paused`,handle:this.#r}),this.#ct(!0),this.#st(`resuming`),this.#Qe().then(e=>{this.#a&&this.#r&&e.begin()}))}#Qe(){return this.#o?Promise.resolve(this.#o):(this.#s||(this.#s=Hr().then(({createReconnectController:e})=>{let t=e(this.#$e());return this.#o=t,t}),this.#s.catch(()=>{this.#s=null})),this.#s)}#$e(){let e=this;return{get config(){return e.config},getResumable:()=>e.#r,clearResumable:()=>e.#at(),getStatus:()=>e.status,setStatus:t=>e.#st(t),setStreaming:t=>e.#ct(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,n,r)=>e.connectStream(t,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:t=>e.#ft(t),settleParked:t=>e.#et(t),nextSequence:()=>e.#mt(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>Kr(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#o?.wake():this.#Ze()}resumeFromHandle(e){if(typeof this.config.reconnectStream!=`function`||this.#a)return;if(this.#Xe()){this.#tt(e.executionId),this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:this.#i??``,status:`running`};return}let t=this.#nt(e.executionId)?Ye():this.#rt();t||(t=Ye(),this.#ft({id:t,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:this.#mt()})),this.#i=t,this.#tt(e.executionId),this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:`running`},this.#Ze()}#et(e){let t=this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0;if(!t&&!this.#Xe()){if(!this.#nt(e))return!1;this.#at()}if(this.#a=!1,!t){let e=!1;for(let t of this.messages)t.streaming&&(t.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.#ct(!1),this.abortController=null}return this.#st(`idle`),!0}#tt(e){this.agentExecution||={executionId:e,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0}}#nt(e){return this.messages.some(t=>t.agentMetadata?.executionId===e&&[t.toolCall,...t.tools??[]].some(e=>e?.interrupted===!0))}#rt(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role===`assistant`&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role===`user`)break}return null}#it(){this.#a=!1,this.#o?.teardown(),this.#at()}#at(){this.#c&&=(clearTimeout(this.#c),null);let e=this.#r!==null;this.#r=null,e&&this.config.onExecutionState?.(null)}#ot(e){let t=this.config.onExecutionState;t&&(e?(this.#c&&=(clearTimeout(this.#c),null),t(this.#r)):this.#c||=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#r)},500))}getResumableHandle(){return this.#r}#st(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#ct(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#lt(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider===`browser`||t.provider===`runtype`&&t.browserFallback))return;let n=[...this.messages].reverse().find(e=>e.role===`assistant`&&e.content&&!e.voiceProcessing);if(!n||e&&!e.includes(n.id))return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Ir(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Or(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=Ir(t.content||``);if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel()}#lt(e){for(let[t,n]of[...this.#e])n===e&&(this.#e.delete(t),this.#dt(t))}#ut(e){for(let[t,n]of this.#e)n===e&&this.#e.set(t,void 0)}#dt(e){let t=this.messages.find(t=>t.id===e)?.approval,n=t?.toolCallId,r=n&&this.messages.find(e=>e.toolCall?.id===n),i=r&&r.toolCall;if(!i||i.status===`complete`||t.status===`pending`)return;let a={...i,status:`complete`,approvalStatus:t.status,completedAt:Date.now(),...t.status===`approved`?{superseded:!0}:{success:!1,error:t.status===`denied`?`Denied`:`Approval timed out`}};this.upsertMessage({...r,streaming:!1,toolCall:a})}#ft(e){let t=this.#pt(e);this.messages=this.#ht([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#pt(e),n=this.messages.findIndex(e=>e.id===t.id);n===-1?this.#ft(t):(this.messages=this.messages.map((e,r)=>{if(r!==n||e.toolCall?.name&&g(e.toolCall.name)&&e.toolCall.status===`complete`&&t.toolCall?.id===e.toolCall.id&&t.toolCall.status!==`complete`&&(t.toolCall.status===`pending`&&!t.toolCall.name||!e.toolCall.interrupted&&(e.toolCall.result!==void 0||e.toolCall.success!==void 0)&&(!t.agentMetadata?.executionId||t.agentMetadata.executionId===e.agentMetadata?.executionId)))return e;let i={...e,...t};e.agentMetadata?.askUserQuestionAnswered===!0&&t.agentMetadata&&(i.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),e.agentMetadata?.suggestRepliesResolved===!0&&t.agentMetadata&&(i.agentMetadata={...i.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let n=e.approval,r=t.approval;i.approval={...n,...r,executionId:r.executionId||n.executionId,toolName:r.toolName||n.toolName,description:r.description||n.description,toolType:r.toolType??n.toolType,reason:r.reason??n.reason,parameters:r.parameters??n.parameters,toolCallId:r.toolCallId??n.toolCallId}}let o=t.toolCall?.name,s=t.agentMetadata?.executionId,c=t.toolCall?.id;if(o&&qr(o)&&s&&c&&t.agentMetadata?.awaitingLocalTool===!0){let t=`${s}:${c}`,n=this.webMcpInflightKeys.has(t),r=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,o=e.agentMetadata?.executionId===s&&e.toolCall?.id===c&&a!==void 0&&qr(a)&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;(n||r||o)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=e.toolCall,i.streaming=e.streaming)}return i}),this.messages=this.#ht(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#pt(e){return e.sequence===void 0?{...e,sequence:this.#mt()}:{...e}}#mt(){return this.#n++}#ht(e){return[...e].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}};const Yr={add:e=>ft(e)},Xr=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Zr={allowedTypes:pt,maxFileSize:10485760,maxFiles:4};function Qr(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $r(e){return e===`application/pdf`||e.startsWith(`text/`)||e.includes(`word`)?sn:e.includes(`excel`)||e.includes(`spreadsheet`)?on:e===`application/json`?an:rn}var ei=class e{#e;#t;#n;constructor(e={}){this.attachments=[],this.#e=null,this.#t=/* @__PURE__ */ new Map,this.#n=!1,this.config={allowedTypes:e.allowedTypes??Zr.allowedTypes,maxFileSize:e.maxFileSize??Zr.maxFileSize,maxFiles:e.maxFiles??Zr.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#r(){return typeof this.config.adapter?.add==`function`}#i(){return this.#r()?this.config.adapter:Yr}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML=``;for(let e of this.attachments)this.#l(e)}this.#f()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Zr.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status===`ready`)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){e&&e.length!==0&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#n)return;let t=[];for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,`count`);continue}let e=lt(n,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes(`type`)?`type`:`size`;this.config.onFileRejected?.(n,t);continue}let r={id:Qr(),file:n,previewUrl:mt(n)?URL.createObjectURL(n):null,contentPart:null,status:this.#r()?`uploading`:`processing`,progress:this.#r()?0:void 0};this.attachments.push(r),this.#l(r),t.push(r)}this.#f(),this.#c(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let n=()=>this.#n||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let r=await this.#i().add(e.file,{signal:t.signal,onProgress:t=>{n()||e.status!==`uploading`||(e.progress=Xr(t),this.#u(e),this.#c())}});if(n())return;e.contentPart=r,e.status=`ready`,e.progress=void 0,e.error=void 0}catch(t){if(n())return;e.status=`error`,e.progress=void 0,e.error=t instanceof Error?t.message:String(t??`Upload failed`)}finally{this.#t.get(e.id)===t&&this.#t.delete(e.id)}this.#u(e),this.#c()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||t.status!==`error`||this.#n||(t.status=this.#r()?`uploading`:`processing`,t.progress=this.#r()?0:void 0,t.error=void 0,this.#u(t),this.#c(),this.#a(t))}#o(e){let t=this.#t.get(e);t&&(this.#t.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(t===-1)return;let n=this.attachments[t];this.#o(e),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let r=this.#e?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),n.status===`ready`&&n.contentPart&&this.#s(n.contentPart),this.#f(),this.#c()}#s(e){let t=this.config.adapter?.remove;if(t)try{let n=t(e,{signal:new AbortController().signal});n&&typeof n.catch==`function`&&n.catch(e=>{console.error(`[AttachmentManager] adapter.remove failed:`,e)})}catch(e){console.error(`[AttachmentManager] adapter.remove failed:`,e)}}clearAttachments(){for(let e of this.attachments)this.#o(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=``),this.#f(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let e of this.#t.values())e.abort();this.#t.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#l(e){if(!this.#e)return;let t=mt(e.file),n=M(`div`,`persona-attachment-preview persona-relative persona-inline-block`);if(n.setAttribute(`data-attachment-id`,e.id),n.style.width=`48px`,n.style.height=`48px`,t&&e.previewUrl){let t=M(`img`);t.src=e.previewUrl,t.alt=e.file.name,t.className=`persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200`,t.style.width=`48px`,t.style.height=`48px`,t.style.objectFit=`cover`,t.style.borderRadius=`8px`,n.appendChild(t)}else{let t=M(`div`);t.style.width=`48px`,t.style.height=`48px`,t.style.borderRadius=`8px`,t.style.backgroundColor=`var(--persona-container, #f3f4f6)`,t.style.border=`1px solid var(--persona-border, #e5e7eb)`,t.style.display=`flex`,t.style.flexDirection=`column`,t.style.alignItems=`center`,t.style.justifyContent=`center`,t.style.gap=`2px`,t.style.overflow=`hidden`;let r=$r(e.file.type),i=b(r,20,`var(--persona-muted, #6b7280)`,1.5);i&&t.appendChild(i);let a=M(`span`);a.textContent=ct(e.file.type,e.file.name),a.style.fontSize=`8px`,a.style.fontWeight=`600`,a.style.color=`var(--persona-muted, #6b7280)`,a.style.textTransform=`uppercase`,a.style.lineHeight=`1`,t.appendChild(a),n.appendChild(t)}let r=j(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),i=M(`div`,`persona-attachment-progress`);i.appendChild(M(`div`,`persona-attachment-progress__bar`));let a=j(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),o=N(`rotate-cw`,12,`var(--persona-text-inverse, #ffffff)`,2);o?a.appendChild(o):a.textContent=`↻`,a.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),r.append(i,a),n.appendChild(r);let s=M(`button`,`persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center`);s.type=`button`,s.setAttribute(`aria-label`,`Remove attachment`),s.style.position=`absolute`,s.style.top=`-4px`,s.style.insetInlineEnd=`-4px`,s.style.width=`18px`,s.style.height=`18px`,s.style.borderRadius=`50%`,s.style.backgroundColor=`var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))`,s.style.border=`none`,s.style.cursor=`pointer`,s.style.display=`flex`,s.style.alignItems=`center`,s.style.justifyContent=`center`,s.style.padding=`0`;let c=b(ln,10,`var(--persona-text-inverse, #ffffff)`,2);c?s.appendChild(c):(s.textContent=`×`,s.style.color=`var(--persona-text-inverse, #ffffff)`,s.style.fontSize=`14px`,s.style.lineHeight=`1`),s.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(s),this.#e.appendChild(n),this.#d(n,e)}#u(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#d(t,e)}#d(e,t){e.dataset.status=t.status;let n=t.status!==`ready`&&t.status!==`error`;e.setAttribute(`aria-busy`,n?`true`:`false`),e.title=t.status===`error`?`${t.file.name}: ${t.error??`Upload failed`}`:t.file.name;let r=e.querySelector(`.persona-attachment-progress__bar`);if(r){let e=t.progress;r.style.width=typeof e==`number`?`${Math.round(e*100)}%`:``}}#f(){this.#e&&(this.#e.style.display=this.attachments.length>0?`flex`:`none`)}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};const ti=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),ni=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.name===r.name&&e.mimeType===r.mimeType&&e.size===r.size&&e.status===r.status&&e.progress===r.progress&&e.error===r.error});function ri(){let e={text:``,attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=/* @__PURE__ */ new Set,n=null,r=!1,i=!1,a=()=>e.preparing?`preparing`:e.streaming?`streaming`:`idle`,o=()=>{let t=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:t,inputDisabled:e.inputDisabled,sendDisabled:t!==`idle`||e.sendDisabled||e.inputDisabled})},s=()=>(n||=o(),n),c=()=>{if(r=!1,i||t.size===0)return;let e=s();for(let n of[...t])try{n(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] composer state listener failed:`,e)}},l=()=>{n=null,!(i||r)&&(r=!0,queueMicrotask(c))};return{getState:s,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,l())},setAttachments:t=>{ni(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{ti(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{ti(e.activeModeIds,t)||(e.activeModeIds=[...t],l())},setQuote:t=>{let n=e.quote;(n?.text!==t?.text||n?.messageId!==t?.messageId||n?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,l())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,l())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,l())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,l())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,l())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,l())},flush:()=>{r&&c()},destroy:()=>{i=!0,r=!1,t.clear()}}}const ii=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},ai=(e,t)=>{let n=M(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function oi(e,t={}){let n=ii(e,`[data-persona-composer-form]`),r=ii(e,`[data-persona-composer-input]`);if(!n||!r){let e=`[Persona] composer surface is missing required element(s): ${[!n&&`form`,!r&&`input`].filter(Boolean).join(`, `)}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||r))throw Error(e);return typeof console<`u`&&console.warn(e),null}let i={header:ii(e,`[data-persona-composer-header]`),body:ii(e,`[data-persona-composer-body]`),actionsStart:ii(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:ii(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:ii(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:ii(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:ii(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=ai(`persona-widget-composer__header`,`data-persona-composer-header`),n.parentNode?n.parentNode.insertBefore(o,n):e.appendChild(o));let s=i.body??r.parentElement??n,c=(e,t,n,r,i)=>{if(t)return t;a.add(e);let o=ai(n,r);return i.appendChild(o),o},l=c(`actionsStart`,i.actionsStart,`persona-widget-composer__left-actions`,`data-persona-composer-actions-start`,n),u=c(`actionsEnd`,i.actionsEnd,`persona-widget-composer__right-actions`,`data-persona-composer-actions-end`,n),d=c(`suggestions`,i.suggestions,`persona-widget-composer__suggestions`,`data-persona-composer-suggestions`,e),f=c(`status`,i.status,`persona-widget-composer__status`,`data-persona-composer-status`,e),p=[],m=(e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler,h=ii(e,`[data-persona-composer-attachment-input]`,`input[type="file"]`)??void 0;return{footer:e,form:n,input:r,header:o,body:s,actionsStart:l,actionsEnd:u,suggestions:d,status:f,attachmentInput:h,attachmentPreviews:ii(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:ii(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:ii(e,`[data-persona-composer-submit]`)??void 0,micButton:ii(e,`[data-persona-composer-mic]`)??void 0,synthesized:a,found:i,addListener:(e,t,n,r)=>{e.addEventListener(t,n,r),p.push({target:e,type:t,handler:n,options:r})},removeListener:(e,t,n,r)=>{e.removeEventListener(t,n,r),p=p.filter(r=>!m(r,{target:e,type:t,handler:n}))},destroy:()=>{for(let e of p)e.target.removeEventListener(e.type,e.handler,e.options);p=[]}}}const si=[`--persona-components-composer-overflowMenu-background`,`--persona-components-composer-overflowMenu-borderColor`,`--persona-components-composer-overflowMenu-borderRadius`,`--persona-components-composer-overflowMenu-foreground`,`--persona-components-composer-overflowMenu-shadow`],ci=`data-persona-menu-focus`,li=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function ui(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const di=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function fi(e){let t=e.label,n=!1,r=M(`div`,`persona-send-button-wrapper`),i=j(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${ue} ${xe}`,attrs:{type:`button`,"aria-haspopup":`menu`,"aria-expanded":`false`,"data-persona-composer-overflow-trigger":``}});r.appendChild(i);let a=j(`div`,{className:`persona-composer-overflow-menu`,attrs:{role:`menu`,tabindex:`-1`,"data-persona-composer-overflow-menu":``}}),o=()=>{let t=e.getButtonSize?.()??``;i.style.width=t,i.style.height=t,i.style.minWidth=t,i.style.minHeight=t,i.style.lineHeight=`1`,i.replaceChildren();let n=N(`plus`,24,`currentColor`,1.5);n?i.appendChild(n):i.textContent=`+`},s=()=>{i.setAttribute(`aria-label`,t),i.setAttribute(`title`,t),a.setAttribute(`aria-label`,t)};s(),o();let c=[],l=-1,u=!1,d=()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null},f=()=>{let e=d();for(let t of c){let n=!!e&&ui(t)===e;t.toggleAttribute(ci,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(ui).filter(e=>!di(e)),m=(e,t)=>{e.forEach((e,n)=>{e.setAttribute(`tabindex`,n===t?`0`:`-1`)})},h=e=>{let t=p();if(t.length===0)return;let n=(e%t.length+t.length)%t.length;l=n,m(t,n),t[n].focus(),f()},g=()=>r.ownerDocument??document,_=null,v=null,y=null,b=()=>{_&&=(g().removeEventListener(`focusin`,_,!0),null)},x=()=>{v&&=(a.removeEventListener(`focusin`,v),null),y&&=(a.removeEventListener(`pointerdown`,y,!0),null)},S=null,C=()=>(S||=Ot({anchor:i,content:a,placement:`top-start`,offset:6,onDismiss:()=>{i.setAttribute(`aria-expanded`,`false`),b()}}),S),w=()=>S?.isOpen===!0,T=(e=!1)=>{if(w()){S?.close(),i.setAttribute(`aria-expanded`,`false`),b(),x(),l=-1,u=!1;for(let e of c)e.removeAttribute(ci);e&&i.focus()}},E=(e=0,t=!1)=>{if(n||w())return;u=t,A(i,a,si),C().open(),i.setAttribute(`aria-expanded`,`true`);let o=p();m(o,-1),h(e<0?o.length-1:e),_=e=>{let t=typeof e.composedPath==`function`?e.composedPath():[];t.includes(a)||t.includes(r)||T()},g().addEventListener(`focusin`,_,!0),v=()=>f(),a.addEventListener(`focusin`,v),y=()=>{u=!1},a.addEventListener(`pointerdown`,y,!0)},D=e=>{e.preventDefault(),e.stopPropagation(),w()?T(!0):E(0)},ee=e=>{e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),u=!0,w()?h(0):E(0,!0)):e.key===`ArrowUp`&&(e.preventDefault(),u=!0,w()?h(-1):E(-1,!0))},te=e=>{switch(li.has(e.key)&&(u=!0),e.key){case`ArrowDown`:e.preventDefault(),h(l+1);return;case`ArrowUp`:e.preventDefault(),h(l-1);return;case`Home`:e.preventDefault(),h(0);return;case`End`:e.preventDefault(),h(p().length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),T(!0);return;case`Tab`:T(!0);return}};return i.addEventListener(`click`,D),i.addEventListener(`keydown`,ee),a.addEventListener(`keydown`,te),{trigger:r,triggerButton:i,panel:a,setItems:e=>{for(let t of c)e.includes(t)||t.removeAttribute(ci);if(c=[...e],!w())return;let t=p();m(t,Math.min(l,t.length-1)),f()},isOpen:w,open:()=>E(0),close:T,setLabel:e=>{e!==t&&(t=e,s())},applyButtonSize:o,destroy:()=>{n=!0,b(),x(),i.removeEventListener(`click`,D),i.removeEventListener(`keydown`,ee),a.removeEventListener(`keydown`,te),S?.destroy(),S=null,r.remove(),a.remove(),c=[]}}}const pi={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},mi=`data-persona-composer-action`,hi=`data-persona-composer-disable-when-streaming`,gi=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function _i(e,t){if(e===void 0)return null;if(typeof e==`number`)return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let r=M(`div`);r.style.position=`absolute`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`,r.style.height=`0`,r.style.width=e,t.appendChild(r);let i=r.getBoundingClientRect().width;return r.remove(),Number.isFinite(i)&&i>0?i:Number.isFinite(n)?n:null}function Y(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let r=n.getComputedStyle(e),i=(Number.parseFloat(r.paddingLeft)||0)+(Number.parseFloat(r.paddingRight)||0);return Math.max(0,t-i)}const vi=(e,t)=>{e&&typeof console<`u`&&console.warn(t)},yi=(e,t)=>t.includes(`:`)?t:`${e}:${t}`;function bi(e){let{debug:t}=e,n=[],r=/* @__PURE__ */ new Map,i=0,a=e=>{let i=r.get(e.id);i?vi(t,`[Persona] composer action "${e.id}" is already contributed by ${xi(i)}; the ${xi(e)} copy is ignored.`):(r.set(e.id,e),n.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:`bar`,order:t.order,sequence:i++,source:`core`,builtIn:t});let o=(e,n,r)=>{let o=r?yi(r,e.id):e.id,s=e.order??pi.custom;e.placement===`end`&&s>=pi.send&&(vi(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${pi.send-1}.`),s=pi.send-1),a({id:o,placement:e.placement,presentation:e.presentation??`bar`,order:s,sequence:i++,source:n,pluginId:r,action:e})};for(let t of e.configActions??[])o(t,`config`);for(let t of e.plugins){if(!t.contributeComposerActions)continue;let n;try{n=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<`u`&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of n??[])o(e,`plugin`,t.id)}return n.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}const xi=e=>e.source===`plugin`?`plugin "${e.pluginId}"`:e.source===`config`?`composer.actions`:`a core built-in`,Si=(e,t,n)=>e===void 0?n:typeof e==`function`?e(t)===!0:e===!0,Ci=e=>e.phase===`streaming`||e.text.trim().length>0||e.attachments.length>0;function wi(e,t){if(!e||e===`always`)return!0;let n=Ci(t);return e===`when-text`?n:!n}const Ti=e=>e.kind===`custom`,Ei=e=>e instanceof HTMLButtonElement?e:e.querySelector(`button`)??e,Di=e=>{let t=Ei(e);return t.getAttribute(`aria-label`)?.trim()||t.getAttribute(`title`)?.trim()||``};function Oi(e){let t=``,n=e=>{if(e.nodeType===Node.TEXT_NODE){t+=e.nodeValue??``;return}if(e.nodeType!==Node.ELEMENT_NODE)return;let r=e;typeof r.matches==`function`&&r.matches(`.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]`)||e.childNodes.forEach(n)};return n(e),t.trim()}const ki=e=>Oi(e).length===0;function Ai(e){let t=/* @__PURE__ */ new Map,n=[],r=!1,i=()=>e.getButtonSize?.(),a=(e,t)=>{let n=e.button;if(!n)return;n.setAttribute(`role`,`menuitem`),n.setAttribute(`tabindex`,`-1`),n.className=`persona-composer-overflow-menu__item`;for(let e of[`width`,`height`,`minWidth`,`minHeight`,`fontSize`,`color`,`backgroundColor`])n.style[e]=``;n.style.lineHeight=`1`,t.tooltipText?n.setAttribute(`title`,t.tooltipText):n.removeAttribute(`title`),n.replaceChildren();let r=M(`span`,`persona-composer-overflow-menu__icon`);if(t.iconName){let e=N(t.iconName,16,`currentColor`,1.5);e&&r.appendChild(e)}let i=M(`span`,`persona-composer-overflow-menu__label`);i.textContent=t.shortLabel??t.label,n.append(r,i)},o=(e,t)=>{let n=e.button;if(!n)return;if(n.setAttribute(`aria-label`,t.label),t.pressed===void 0?n.removeAttribute(`aria-pressed`):n.setAttribute(`aria-pressed`,t.pressed?`true`:`false`),n.toggleAttribute(hi,t.disableWhenStreaming===!0),e.mode===`menu`){e.tooltip?.destroy(),e.tooltip=void 0,a(e,t);return}n.removeAttribute(`role`),n.removeAttribute(`tabindex`),n.removeAttribute(`title`);let r=i(),o=!!t.shortLabel;if(n.className=Me(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button`,ue,xe,o&&`persona-composer-action-button--text persona-gap-1 persona-text-sm`),n.style.width=r&&!o?r:``,n.style.height=r??``,n.style.minWidth=r&&!o?r:``,n.style.minHeight=r??``,n.style.fontSize=o?``:`18px`,n.style.lineHeight=`1`,n.style.color=t.iconColor??``,n.style.backgroundColor=t.backgroundColor??``,n.replaceChildren(),t.iconName){let e=N(t.iconName,24,`currentColor`,1.5);e&&n.appendChild(e)}if(o){let e=M(`span`,`persona-composer-action-button__label`);e.textContent=t.shortLabel,n.appendChild(e)}else n.firstChild||(n.textContent=t.label);e.tooltip?.destroy(),e.tooltip=S({anchor:n,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,n)=>{let r=t.action,i=j(`button`,{attrs:{type:`button`}}),a=i;if(n===`bar`){let e=M(`div`,`persona-send-button-wrapper`);e.appendChild(i),a=e}a.setAttribute(mi,t.id);let s={resolved:t,element:a,button:i,owned:!0,managed:!0,busy:!1,visible:!0,mode:n},c=t=>{if(t.preventDefault(),t.stopPropagation(),s.busy||i.disabled)return;let n=s.resolved.action;s.mode===`menu`&&p?.close(!0);let r;try{r=n.onSelect(e.actionContext,t)}catch(t){e.reportError(t,{actionId:s.resolved.id});return}r&&typeof r.then==`function`&&(s.busy=!0,i.setAttribute(`aria-busy`,`true`),r.catch(t=>{e.reportError(t,{actionId:s.resolved.id})}).finally(()=>{s.busy=!1,i.removeAttribute(`aria-busy`)}))};return i.addEventListener(`click`,c),s.detach=()=>i.removeEventListener(`click`,c),o(s,r),s},c=t=>{let n=t.action,r;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(n){return e.reportError(n,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(mi,t.id),r.element.toggleAttribute(hi,n.disableWhenStreaming===!0),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:`bar`}):null},l=(e,t)=>{if(e.builtIn){let t=e.builtIn.element;return t?{resolved:e,element:t,owned:!1,managed:e.builtIn.managed===!0,busy:!1,visible:!0,mode:`bar`}:null}let n=e.action;return n?Ti(n)?c(e):s(e,t):null},u=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(n){e.reportError(n,{actionId:t.resolved.id})}t.element.remove()}},d=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(!r.managed)continue;let i=null;for(let r=n+1;r<t.length;r++){let n=t[r];if(!n.managed&&n.element.parentElement===e){i=n.element;break}}i?(r.element.parentElement!==e||r.element.nextSibling!==i)&&e.insertBefore(r.element,i):e.lastChild!==r.element&&e.appendChild(r.element)}},f=(e,t)=>{if(e.button){e.button.disabled=t;return}if(!e.owned)return;let n=e.element;n.toggleAttribute(`data-disabled`,t),n.setAttribute(`aria-disabled`,t?`true`:`false`);let r=n instanceof HTMLButtonElement||n instanceof HTMLSelectElement||n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n:n.querySelector(`button, select, input, textarea`);r&&(r.disabled=t)},p=null,m=null,h=null,g=0,_=()=>{let t=e.getOverflow?.();return t?.enabled===!0?t:void 0},v=()=>(p?p.setLabel(e.getOverflowLabel?.()??`More actions`):p=fi({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:i}),p),y=e=>{m!==e&&(h?.disconnect(),m=e,g=Y(e),typeof ResizeObserver<`u`&&(h=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??Y(e);n!==g&&(g=n,E())}),h.observe(e)))},b=(e,t)=>{let n=_i(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=g||Y(t);return r>0&&r<n},x=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=gi(e.resolved.id);return n&&t.includeBuiltIns?.includes(n)?`menu`:`bar`}let r=e.resolved.presentation;return r===`overflow`||r===`auto`&&n?`menu`:`bar`},C=e=>{let t=e.menuSlot;if(!t)return;if(!ki(e.element)){e.menuLabel?.remove(),e.menuLabel=void 0;return}let n=Di(e.element);n?(e.menuLabel||=M(`span`,`persona-composer-overflow-menu__label`),e.menuLabel.textContent!==n&&(e.menuLabel.textContent=n),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},w=(e,n)=>{if(e.mode===n)return e;let r=e.resolved.action;if(r&&!Ti(r)){u(e),t.delete(e.resolved.id);let r=s(e.resolved,n);return t.set(e.resolved.id,r),r}if(n===`menu`){let t=j(`div`,{className:`persona-composer-overflow-menu__slot`,attrs:{role:`none`,[ae]:``}});t.appendChild(e.element),oe(Ei(e.element)),e.menuSlot=t;let n=t=>{let n=Ei(e.element);if(n.disabled)return;let r=t.target===n||n.contains(t.target);p?.close(!0),r||n.click()};t.addEventListener(`click`,n,!0),e.detachMenuSlot=()=>t.removeEventListener(`click`,n,!0),e.managed=!0,C(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=n,e},T=(e,t)=>{let n=t.map(e=>e.menuSlot??e.element);for(n.forEach((t,n)=>{let r=e.children[n];r!==t&&(r?e.insertBefore(t,r):e.appendChild(t))});e.children.length>n.length;)e.lastElementChild?.remove()},E=()=>{if(r)return;let i=e.getBindings();if(!i)return;let a=e.getState(),o=a.phase===`streaming`,s=_();s&&y(i.footer);let c=s?b(s,i.footer):!1,l={start:[],end:[]},u=[];for(let e of n){let n=t.get(e.id);if(!n)continue;let r=e.action,i=!r||Si(r.visible,a,!0)&&wi(r.visibility,a);if(n.visible!==i&&(n.visible=i,!i&&n.managed&&(n.menuSlot??n.element).remove()),i){if(n=w(n,x(n,s,c)),r){let e=Si(r.disabled,a,!1)||r.disableWhenStreaming===!0&&o;f(n,e),!Ti(r)&&r.pressed!==void 0&&n.button?.setAttribute(`aria-pressed`,r.pressed?`true`:`false`)}n.mode===`menu`?(C(n),u.push(n)):l[e.placement].push(n)}}if(u.length>0){let e=v();T(e.panel,u),e.setItems(u.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(s?.order)?s?.order:pi.overflow,n=l.start.findIndex(e=>e.resolved.order>t),r={resolved:{id:`core:overflow`,placement:`start`,presentation:`bar`,order:t,sequence:-1,source:`core`},element:e.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:`bar`};l.start.splice(n<0?l.start.length:n,0,r)}else p&&(p.close(),p.trigger.remove(),p.setItems([]));d(i.actionsStart,l.start),d(i.actionsEnd,l.end)};return{resolve:()=>{if(r)return;let i=bi(e.collect()),a=new Set(i.map(e=>e.id));for(let[e,n]of t)a.has(e)||(u(n),t.delete(e));for(let e of i){let n=t.get(e.id);if(!n){let n=l(e,`bar`);n&&t.set(e.id,n);continue}let r=n.resolved.action,i=e.action;if(!!r!=!!i||r&&i&&Ti(r)!==Ti(i)||r&&i&&Ti(r)&&Ti(i)&&r.render!==i.render){u(n),t.delete(e.id);let r=l(e,n.mode);r&&t.set(e.id,r)}else n.resolved=e,e.builtIn?(n.managed=e.builtIn.managed===!0||n.mode===`menu`,e.builtIn.element&&n.mode===`bar`&&(n.element=e.builtIn.element)):i&&!Ti(i)?o(n,i):i&&n.element.toggleAttribute(hi,i.disableWhenStreaming===!0)}n=i,E()},sync:E,getResolved:()=>n,getOverflowMenu:()=>p,destroy:()=>{if(!r){r=!0,h?.disconnect(),h=null,m=null;for(let e of t.values())u(e);t.clear(),p?.destroy(),p=null,n=[]}}}}const ji=[`--persona-components-composer-modelPicker-menuBackground`,`--persona-components-composer-modelPicker-menuBorderRadius`,`--persona-components-composer-modelPicker-rowHoverBackground`,`--persona-components-composer-modelPicker-labelColor`,`--persona-components-composer-modelPicker-descriptionColor`],Mi=()=>({wrapper:j(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:j(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function Ni(e){let t=e.label??`Model`,n=e.presentation??`native`,r=null,i=t=>{let n=e.getSelectedModelId();return t.find(e=>e.id===n)??t[0]},a=()=>{let n=j(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":t,"data-persona-composer-model-picker":``}}),a=``,o=()=>{let t=e.getModels(),r=t.map(e=>`${e.id}:${e.label}`).join(`|`);r!==a&&(a=r,n.replaceChildren(...t.map(e=>{let t=j(`option`,{attrs:{value:e.id}});return t.textContent=e.label,t}))),n.value=i(t)?.id??``};o(),r=o;let s=()=>{n.value&&e.onSelect(n.value)};n.addEventListener(`change`,s);let c=e=>e.stopPropagation();n.addEventListener(`click`,c);let{wrapper:l,chevron:u}=Mi();return l.append(n,u),{element:l,destroy:()=>{r===o&&(r=null),n.removeEventListener(`change`,s),n.removeEventListener(`click`,c)}}},o=()=>{let n=j(`button`,{className:`persona-composer-model-picker persona-composer-model-picker-trigger`,attrs:{type:`button`,"aria-haspopup":`listbox`,"aria-expanded":`false`,"data-persona-composer-model-picker":`popover`}}),a=M(`span`,`persona-composer-model-picker-label`),o=M(`span`,`persona-composer-model-picker-suffix`);n.append(a,o);let s=j(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":t,"data-persona-composer-model-menu":``}}),c=/* @__PURE__ */ new Map,l=``,u=null,d=()=>u?.isOpen===!0,f=(e=!1)=>{d()&&(u?.close(),n.setAttribute(`aria-expanded`,`false`),e&&n.focus())},p=e=>{let t=[...c.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(d())return;u||=Ot({anchor:n,content:s,placement:`top-start`,offset:6,onDismiss:()=>n.setAttribute(`aria-expanded`,`false`)}),A(n,s,ji),u.open(),n.setAttribute(`aria-expanded`,`true`);let r=[...c.keys()].indexOf(i(e.getModels())?.id??``);p(t??(r>=0?r:0))},h=t=>{f(!0),e.onSelect(t)},g=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&h(t)},_=e=>{let t=j(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":e.id}});if(e.icon){let n=N(e.icon,16,`currentColor`,1.5);if(n){let e=M(`span`,`persona-composer-model-option-icon`);e.appendChild(n),t.appendChild(e)}}let n=M(`span`,`persona-composer-model-option-body`),r=M(`span`,`persona-composer-model-option-label`);if(r.textContent=e.label,n.appendChild(r),e.description){let t=M(`span`,`persona-composer-model-option-description`);t.textContent=e.description,n.appendChild(t)}t.appendChild(n);let i=M(`span`,`persona-composer-model-option-check`);i.setAttribute(`aria-hidden`,`true`);let a=N(`check`,16,`currentColor`,2);return a&&i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,g),t},v=()=>{let r=e.getModels(),u=r.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(u!==l){l=u;for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),s.replaceChildren(...r.map(e=>{let t=_(e);return c.set(e.id,t),t}))}let d=i(r);for(let[e,t]of c)t.setAttribute(`aria-selected`,String(e===d?.id));a.textContent=d?.label??``;let f=e.getSuffix?.()??``;o.textContent=f,n.setAttribute(`aria-label`,[t,[d?.label,f].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};v(),r=v;let y=e=>{e.preventDefault(),e.stopPropagation(),d()?f(!0):m()},b=e=>{e.key===`ArrowDown`?(e.preventDefault(),d()?p(0):m(0)):e.key===`ArrowUp`&&(e.preventDefault(),d()?p(-1):m(-1))},x=e=>{let t=[...c.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),p(n+1);return;case`ArrowUp`:e.preventDefault(),p(n-1);return;case`Home`:e.preventDefault(),p(0);return;case`End`:e.preventDefault(),p(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),f(!0);return;case`Tab`:f(!0);return}};n.addEventListener(`click`,y),n.addEventListener(`keydown`,b),s.addEventListener(`keydown`,x);let{wrapper:S,chevron:C}=Mi();return S.append(n,C),{element:S,destroy:()=>{r===v&&(r=null),n.removeEventListener(`click`,y),n.removeEventListener(`keydown`,b),s.removeEventListener(`keydown`,x);for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),u?.destroy(),u=null,s.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:n===`popover`?`bar`:`auto`,label:t,render:()=>n===`popover`?o():a()},repaint:()=>r?.()}}function Pi(e){let t=e.row,n=``,r=!1,i=new Set(e.initialIds??[]),a=t=>{let n=j(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=M(`span`,`persona-mention-chip-icon`),r=N(t.iconName,12,`currentColor`,1.5);r&&e.appendChild(r),n.appendChild(e)}let r=M(`span`,`persona-mention-chip-label`);r.textContent=t.shortLabel??t.label,n.appendChild(r);let i=j(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label}`}}),a=N(`x`,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=`×`,i.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),e.onRemove(t.id)}),n.appendChild(i),n},o=()=>Array.from(t.querySelectorAll(`:scope > [data-persona-composer-mode]`)),s=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let n=()=>{e.remove(),Et(t)},r=t.ownerDocument.defaultView,i=typeof r?.getComputedStyle==`function`?r.getComputedStyle(e).animationName:``;!i||i===`none`?n():(e.addEventListener(`animationend`,n,{once:!0}),e.addEventListener(`animationcancel`,n,{once:!0}))},c=()=>{for(let e of o())e.remove()};return{element:t,render:(e,c)=>{if(r)return;let l=c.filter(t=>e.includes(t.id)),u=l.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===n)return;n=u;let d=/* @__PURE__ */ new Map;for(let e of o()){let t=e.getAttribute(`data-persona-composer-mode`);t&&l.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?d.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||s(e)}let f=t.firstChild;for(let e of l){let n=d.get(e.id);n||(n=a(e),i.has(e.id)||(n.setAttribute(`data-persona-chip-enter`,``),n.addEventListener(`animationend`,()=>n?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),i.delete(e.id),n!==f&&t.insertBefore(n,f),f=n.nextSibling}Et(t)},destroy:()=>{r=!0,c(),Et(t)}}}const Fi=e=>`core:mode:${e}`,Ii=e=>Math.min(300+e,499),Li=e=>`core:mode-group:${e}`;function Ri(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function zi(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function Bi(e,t){return e?.length?e.filter(e=>!Ri(e.groupId,t)&&!zi(e.groupId,t)):[]}const Vi=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function Hi(e,t,n,r){let i=n.find(e=>e.id===t);if(!i)return[...e];let a=e.includes(t),o=new Set(e);if(a)o.delete(t);else{if(Vi(i,r)===`single`){let e=n.filter(e=>e.groupId===i.groupId).map(e=>e.id);o=new Set([...o].filter(t=>!e.includes(t)))}o.add(t)}return n.filter(e=>o.has(e.id)).map(e=>e.id)}function Ui(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function Wi(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function Gi(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}function Ki(e){let t=null;return{action:{id:Li(e.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:e.getGroup()?.label??e.groupId,render:()=>{let n=j(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":e.groupId}}),r=/* @__PURE__ */ new Map,i=``,a=t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getAttribute(`data-persona-composer-mode`);n&&(e.getActiveIds().includes(n)&&e.getGroup()?.selection===`single`||e.onSelect(n))},o=e=>{let t=j(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let n=N(e.iconName,16,`currentColor`,1.5);n&&t.appendChild(n)}let n=M(`span`,`persona-composer-segmented-label`);return n.textContent=e.shortLabel??e.label,t.appendChild(n),t.addEventListener(`click`,a),t},s=()=>{let t=e.getGroup();t?.label?(n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,t.label)):(n.removeAttribute(`role`),n.removeAttribute(`aria-label`));let s=e.getModes(),c=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(c!==i){i=c;for(let e of r.values())e.removeEventListener(`click`,a);r.clear();let e=s.map(e=>{let t=o(e);return r.set(e.id,t),t});n.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of r)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return s(),t=s,{element:n,destroy:()=>{t===s&&(t=null);for(let e of r.values())e.removeEventListener(`click`,a);r.clear()}}}},repaint:()=>t?.()}}function qi(e){let t=j(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=M(`span`,`persona-composer-quote-bar`),i=M(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=M(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=j(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=Cr(n.text),i.appendChild(a);let o=j(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=N(`x`,12,`currentColor`,2);s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(r,i,o)};return{element:t,render:e=>{if(r)return;let a=e?`${e.sourceLabel??``}${e.text}`:``;a!==n&&(n=a,e?(i(e),t.style.display=`flex`):(t.replaceChildren(),t.style.display=`none`))},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}function Ji(e){let t=j(`div`,{className:`persona-composer-pending`,attrs:{"data-persona-composer-pending":``}});t.style.display=`none`;let n,r=!1,i=(e,t,n,r)=>{let i=j(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=N(e,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=t,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},a=e=>{let t=Cr(e.text??``,90);if(t)return t;let n=e.contentParts?.length??0;return n>0?n===1?`1 attachment`:`${n} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(`, `):`Queued message`};return{element:t,render:o=>{if(r||o===n)return;if(n=o,!o){t.replaceChildren(),t.style.display=`none`;return}let s=M(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=j(`div`,{className:`persona-composer-pending-text`,attrs:{"data-persona-composer-pending-text":``}});c.textContent=a(o),t.replaceChildren(s,c,i(`pencil`,e.editLabel??`Edit queued message`,`data-persona-composer-pending-edit`,e.onEdit),i(`x`,e.removeLabel??`Remove queued message`,`data-persona-composer-pending-remove`,e.onRemove)),t.style.display=`flex`},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}function Yi(e){let t=j(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=j(`textarea`,{className:`persona-message-edit-input`,attrs:{rows:`1`,dir:`auto`,"aria-label":`Edit message`,"data-persona-message-edit-input":``}});n.value=e.initialText;let r=()=>{n.style.height=`auto`,n.style.height=`${n.scrollHeight}px`};n.addEventListener(`input`,r);let i=M(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=j(`button`,{className:`persona-message-edit-button ${t}`,attrs:{type:`button`,[n]:``},text:e});return i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},o=()=>{let t=n.value.trim();t&&e.onSave(t)};return i.append(a(e.cancelLabel??`Cancel`,`persona-message-edit-cancel`,`data-persona-message-edit-cancel`,e.onCancel),a(e.saveLabel??`Send`,`persona-message-edit-save`,`data-persona-message-edit-save`,o)),n.addEventListener(`keydown`,t=>{t.key===`Escape`?(t.preventDefault(),t.stopPropagation(),e.onCancel()):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),o())}),t.append(n,i),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let e=n.value.length;n.setSelectionRange(e,e),r()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Xi(e){let t=e.text??``;if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function Zi(e,t){if(!e||typeof e.text!=`string`)return;let n=new Set(t.mentionSourceIds),r=(e.mentionRefs??[]).filter(e=>n.has(e.sourceId)),i=r.length===(e.mentionRefs?.length??0)&&r.length>0,a=new Set(t.modes.map(e=>e.id)),o=(e.activeModeIds??[]).filter(e=>a.has(e)),s=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...i?{mentionRefs:r}:{},...i&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...s?{selectedModelId:s}:{},...o.length?{activeModeIds:o}:{},...e.quote?.text?{quote:e.quote}:{}}}function Qi(e){let t=e.delay??500,n=null,r=!1,i=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{r||(i(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{r||n===null||(i(),e.write())},cancel:i,destroy:()=>{r=!0,i()}}}function $i(e){return e.wrapped||e.text.includes(`
|
|
12
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function ea(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function ta(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-o>a*1.5}function na(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function ra(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const ia=e=>typeof e?.then==`function`;function aa(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function oa(e,t,n){let r;try{r=e(na(t),{signal:n})}catch(e){return{status:`error`,error:e}}return ia(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:aa(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):aa(t,r)}const sa=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),ca={background:`semantic.colors.primary`,foreground:`semantic.colors.textInverse`,border:`transparent`,size:`48px`,iconSize:`24px`,borderRadius:`palette.radius.full`,shadow:`0 8px 24px rgba(0,0,0,.16)`,offset:`20px`},la=`16px`,ua=`transparent`,da={colors:{primary:{50:`#ffffff`,100:`#f5f5f5`,200:`#d4d4d4`,300:`#a3a3a3`,400:`#737373`,500:`#171717`,600:`#0f0f0f`,700:`#0a0a0a`,800:`#050505`,900:`#030303`,950:`#000000`},secondary:{50:`#f5f3ff`,100:`#ede9fe`,200:`#ddd6fe`,300:`#c4b5fd`,400:`#a78bfa`,500:`#8b5cf6`,600:`#7c3aed`,700:`#6d28d9`,800:`#5b21b6`,900:`#4c1d95`,950:`#2e1065`},accent:{50:`#ecfeff`,100:`#cffafe`,200:`#a5f3fc`,300:`#67e8f9`,400:`#22d3ee`,500:`#06b6d4`,600:`#0891b2`,700:`#0e7490`,800:`#155e75`,900:`#164e63`,950:`#083344`},gray:{50:`#f9fafb`,100:`#f3f4f6`,200:`#e5e7eb`,300:`#d1d5db`,400:`#9ca3af`,500:`#6b7280`,600:`#4b5563`,700:`#374151`,800:`#1f2937`,900:`#111827`,950:`#030712`},success:{50:`#f0fdf4`,100:`#dcfce7`,200:`#bbf7d0`,300:`#86efac`,400:`#4ade80`,500:`#22c55e`,600:`#16a34a`,700:`#15803d`,800:`#166534`,900:`#14532d`},warning:{50:`#fefce8`,100:`#fef9c3`,200:`#fef08a`,300:`#fde047`,400:`#facc15`,500:`#eab308`,600:`#ca8a04`,700:`#a16207`,800:`#854d0e`,900:`#713f12`},error:{50:`#fef2f2`,100:`#fee2e2`,200:`#fecaca`,300:`#fca5a5`,400:`#f87171`,500:`#ef4444`,600:`#dc2626`,700:`#b91c1c`,800:`#991b1b`,900:`#7f1d1d`},info:{50:`#eff6ff`,100:`#dbeafe`,200:`#bfdbfe`,300:`#93c5fd`,400:`#60a5fa`,500:`#3b82f6`,600:`#2563eb`,700:`#1d4ed8`,800:`#1e40af`,900:`#1e3a8a`,950:`#172554`},purple:{50:`#faf5ff`,100:`#f3e8ff`,200:`#e9d5ff`,300:`#d8b4fe`,400:`#c084fc`,500:`#a855f7`,600:`#9333ea`,700:`#7e22ce`,800:`#6b21a8`,900:`#581c87`,950:`#3b0764`},teal:{50:`#f0fdfa`,100:`#ccfbf1`,200:`#99f6e4`,300:`#5eead4`,400:`#2dd4bf`,500:`#14b8a6`,600:`#0d9488`,700:`#0f766e`,800:`#115e59`,900:`#134e4a`,950:`#042f2e`}},spacing:(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?`0px`:`${t/4}rem`;return e})(),typography:{fontFamily:{sans:`system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,serif:`Georgia, Cambria, "Times New Roman", Times, serif`,mono:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`},fontSize:{xs:`0.75rem`,sm:`0.875rem`,base:`1rem`,lg:`1.125rem`,xl:`1.25rem`,"2xl":`1.5rem`,"3xl":`1.875rem`,"4xl":`2.25rem`},fontWeight:{normal:`400`,medium:`500`,semibold:`600`,bold:`700`},lineHeight:{tight:`1.25`,normal:`1.5`,relaxed:`1.625`}},shadows:{none:`none`,sm:`0 1px 2px 0 rgb(0 0 0 / 0.05)`,md:`0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)`,lg:`0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)`,xl:`0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)`,"2xl":`0 25px 50px -12px rgb(0 0 0 / 0.25)`},borders:{none:`none`,sm:`1px solid`,md:`2px solid`,lg:`4px solid`},radius:{none:`0px`,sm:`0.125rem`,md:`0.375rem`,lg:`0.5rem`,xl:`0.75rem`,"2xl":`1rem`,full:`9999px`}},fa={colors:{primary:`palette.colors.primary.500`,secondary:`palette.colors.secondary.500`,accent:`palette.colors.primary.600`,surface:`palette.colors.gray.50`,background:`palette.colors.gray.50`,container:`palette.colors.gray.50`,text:`palette.colors.gray.900`,textMuted:`palette.colors.gray.500`,textInverse:`palette.colors.gray.50`,border:`palette.colors.gray.200`,divider:`palette.colors.gray.200`,interactive:{default:`palette.colors.primary.600`,hover:`palette.colors.primary.700`,focus:`palette.colors.primary.600`,active:`palette.colors.primary.600`,disabled:`palette.colors.gray.300`},feedback:{success:`palette.colors.success.500`,warning:`palette.colors.warning.500`,error:`palette.colors.error.500`,info:`palette.colors.info.500`}},spacing:{xs:`palette.spacing.1`,sm:`palette.spacing.2`,md:`palette.spacing.4`,lg:`palette.spacing.6`,xl:`palette.spacing.8`,"2xl":`palette.spacing.10`},typography:{fontFamily:`palette.typography.fontFamily.sans`,fontSize:`palette.typography.fontSize.base`,fontWeight:`palette.typography.fontWeight.normal`,lineHeight:`palette.typography.lineHeight.normal`}},pa={button:{primary:{background:`palette.colors.primary.500`,foreground:`palette.colors.primary.50`,borderRadius:`palette.radius.lg`,padding:`semantic.spacing.md`},secondary:{background:`semantic.colors.surface`,foreground:`semantic.colors.secondary`,borderRadius:`palette.radius.lg`,padding:`semantic.spacing.md`},ghost:{background:`transparent`,foreground:`semantic.colors.text`,borderRadius:`palette.radius.md`,padding:`semantic.spacing.sm`,hoverBackground:`rgba(0, 0, 0, 0.05)`}},input:{background:`semantic.colors.surface`,placeholder:`semantic.colors.textMuted`,borderRadius:`palette.radius.lg`,padding:`semantic.spacing.md`,focus:{border:`palette.colors.gray.400`,ring:`palette.colors.gray.400`}},launcher:{background:`semantic.colors.surface`,foreground:`semantic.colors.primary`,border:`semantic.colors.border`,size:`60px`,iconSize:`28px`,borderRadius:`palette.radius.full`,shadow:`palette.shadows.lg`},panel:{width:ve,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:la,canvasBackground:ua,modes:{floating:{border:`1px solid var(--persona-border)`,shadow:`palette.shadows.xl`,borderRadius:`palette.radius.xl`},inline:{border:`1px solid var(--persona-border)`,shadow:`none`,borderRadius:`palette.radius.xl`},docked:{border:`none`,shadow:`none`,borderRadius:`palette.radius.xl`},sidebar:{border:`none`,borderRadius:`0`},mobile:{border:`none`,shadow:`none`,borderRadius:`0`}}},header:{background:`palette.colors.primary.500`,foreground:`palette.colors.primary.50`,borderRadius:`palette.radius.xl palette.radius.xl 0 0`,padding:`20px 24px`,minimalPadding:`16px 24px`,iconBackground:`palette.colors.primary.600`,iconForeground:`palette.colors.primary.50`},message:{gap:`12px`,user:{background:`palette.colors.primary.500`,text:`palette.colors.primary.50`,borderRadius:`palette.radius.lg`,shadow:`palette.shadows.sm`},assistant:{background:`semantic.colors.container`,text:`semantic.colors.text`,borderRadius:`palette.radius.lg`,border:`semantic.colors.border`,shadow:`palette.shadows.sm`},border:`semantic.colors.border`},introCard:{background:`transparent`,borderRadius:`palette.radius.2xl`,padding:`semantic.spacing.lg`,shadow:`palette.shadows.none`},suggestion:{chip:{background:`semantic.colors.surface`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,borderRadius:`palette.radius.full`,padding:`0.5rem 0.875rem`,gap:`0.5rem`,itemGap:`8px`,minHeight:`36px`,fontSize:`0.8125rem`,lineHeight:`1.25`,iconSize:`16px`,hoverBackground:`palette.colors.gray.100`,hoverBorder:`palette.colors.gray.300`,pressedBackground:`palette.colors.gray.200`,focusRing:`semantic.colors.interactive.focus`,disabledOpacity:`0.5`},card:{background:`semantic.colors.surface`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,borderRadius:`palette.radius.xl`,padding:`1rem`,shadow:`palette.shadows.sm`,gap:`0.625rem`,itemGap:`8px`,minHeight:`72px`,fontSize:`0.875rem`,lineHeight:`1.35`,iconSize:`18px`,hoverBackground:`palette.colors.gray.100`,hoverBorder:`palette.colors.gray.300`,pressedBackground:`palette.colors.gray.200`,focusRing:`semantic.colors.interactive.focus`,disabledOpacity:`0.5`},list:{background:`transparent`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,borderRadius:`palette.radius.md`,padding:`0.75rem`,gap:`0.625rem`,itemGap:`8px`,minHeight:`44px`,fontSize:`0.875rem`,lineHeight:`1.35`,iconSize:`17px`,hoverBackground:`palette.colors.gray.100`,hoverBorder:`palette.colors.gray.300`,pressedBackground:`palette.colors.gray.200`,focusRing:`semantic.colors.interactive.focus`,disabledOpacity:`0.5`}},toolBubble:{shadow:`palette.shadows.sm`},reasoningBubble:{shadow:`palette.shadows.sm`},composer:{shadow:`palette.shadows.none`},scrollbar:{thumb:`semantic.colors.border`,track:`transparent`},markdown:{inlineCode:{background:`palette.colors.gray.50`,foreground:`palette.colors.gray.900`},link:{foreground:`palette.colors.primary.600`},prose:{fontFamily:`inherit`},codeBlock:{background:`semantic.colors.container`,borderColor:`semantic.colors.border`,textColor:`inherit`,borderRadius:`palette.radius.md`},table:{headerBackground:`semantic.colors.container`,borderColor:`semantic.colors.border`},hr:{color:`semantic.colors.divider`},blockquote:{borderColor:`palette.colors.gray.900`,background:`transparent`,textColor:`palette.colors.gray.500`}},collapsibleWidget:{container:`palette.colors.gray.50`,surface:`semantic.colors.surface`,border:`semantic.colors.border`},voice:{recording:{indicator:`palette.colors.error.500`,background:`palette.colors.error.50`,border:`palette.colors.error.200`},processing:{icon:`palette.colors.primary.500`,background:`palette.colors.primary.50`},speaking:{icon:`palette.colors.success.500`}},approval:{requested:{background:`semantic.colors.surface`,border:`semantic.colors.border`,text:`palette.colors.gray.900`,shadow:`0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)`},approve:{background:`semantic.colors.primary`,foreground:`semantic.colors.textInverse`,borderRadius:`palette.radius.md`,padding:`semantic.spacing.sm`},deny:{background:`semantic.colors.container`,foreground:`semantic.colors.text`,borderRadius:`palette.radius.md`,padding:`semantic.spacing.sm`}},attachment:{image:{background:`palette.colors.gray.100`,border:`palette.colors.gray.200`}},eventStream:{badge:{flow:{background:`palette.colors.success.100`,foreground:`palette.colors.success.700`},step:{background:`palette.colors.primary.100`,foreground:`palette.colors.primary.700`},reasoning:{background:`palette.colors.warning.100`,foreground:`palette.colors.warning.700`},tool:{background:`palette.colors.purple.100`,foreground:`palette.colors.purple.800`},agent:{background:`palette.colors.teal.100`,foreground:`palette.colors.teal.800`},error:{background:`palette.colors.error.100`,foreground:`palette.colors.error.700`},default:{background:`palette.colors.gray.100`,foreground:`palette.colors.gray.600`}}},scrollToBottom:{background:`components.button.primary.background`,foreground:`components.button.primary.foreground`,border:`semantic.colors.primary`,size:`40px`,borderRadius:`palette.radius.full`,shadow:`palette.shadows.sm`,padding:`0.5rem 0.875rem`,gap:`0.5rem`,fontSize:`0.875rem`,iconSize:`14px`},artifact:{pane:{background:`semantic.colors.container`,toolbarBackground:`semantic.colors.container`}}},ma=da.colors.gray,ha={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},X={...da,colors:{...da.colors,gray:ma}},ga={...da,colors:{...da.colors,gray:ha},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},_a=fa,va={...fa,colors:{...fa.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...fa.typography,fontSize:`14px`,lineHeight:`1.5`}},ya=pa,ba={...pa,launcher:ca,activity:{rowHeight:`32px`,labelSize:`13px`,iconSize:`16px`,indent:`0px`,groupIndent:`0px`,groupGap:`0px`,groupPadding:`0px`,transcriptGap:`0px`,responseGap:`12px`,bodyPadding:`4px 0`,bodySize:`13px`,bodyLineHeight:`1.5`,bodyFontWeight:`400`,sectionGap:`8px`,bodySurface:`transparent`},toolBubble:{shadow:`none`},reasoningBubble:{shadow:`none`},input:{...pa.input,borderRadius:`palette.radius.full`},introCard:{...pa.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...pa.suggestion.chip,fontWeight:`400`},card:{...pa.suggestion.card,fontWeight:`400`},list:{...pa.suggestion.list,fontWeight:`400`}},panel:{...pa.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...pa.header,background:`semantic.colors.container`,foreground:`semantic.colors.text`,padding:`8px 8px 8px 16px`,minimalPadding:`8px 8px 8px 16px`,minHeight:`48px`,borderBottom:`none`,iconBackground:`transparent`,iconForeground:`semantic.colors.text`,iconScale:`1`,controlSize:`28px`,controlIconSize:`18px`,controlStrokeWidth:`1.5`,actionIconForeground:`semantic.colors.textMuted`,controlBorderRadius:`8px`,controlHoverBackground:`color-mix(in srgb, var(--persona-text) 8%, transparent)`,controlHoverForeground:`semantic.colors.text`,controlFocusOutline:`2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)`,title:{fontSize:`14px`,fontWeight:`500`,lineHeight:`1.5`}},message:{...pa.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...pa.message.user,background:`palette.colors.gray.100`,text:`semantic.colors.text`,borderRadius:`palette.radius.xl`,shadow:`none`,padding:`8px 14px`,fontSize:`14px`,lineHeight:`1.5`},assistant:{...pa.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},composer:{...pa.composer,padding:`8px`,fontSize:`15px`,lineHeight:`1.5`,controlSize:`32px`,controlIconSize:`20px`,sendIconSize:`18px`,sendButtonRadius:`9999px`,footerBorder:`none`,overlayBand:`linear-gradient(to bottom, transparent, var(--persona-container) 24px)`,focusBorderColor:`color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))`,focusRing:`1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)`}},xa=e=>T({future:e}),Sa=e=>xa(e)===`v5`?{palette:ga,semantic:va,components:ba}:{palette:X,semantic:_a,components:ya};function Ca(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?Ca(e,r):r}function wa(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=Ca(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function Ta(e){let t=[],n=[];return e.palette||t.push({path:`palette`,message:`Theme must include a palette`,severity:`error`}),e.semantic||n.push({path:`semantic`,message:`No semantic tokens defined - defaults will be used`,severity:`warning`}),e.components||n.push({path:`components`,message:`No component tokens defined - defaults will be used`,severity:`warning`}),{valid:t.length===0,errors:t,warnings:n}}function Ea(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?Ea(t,r):r}return n}function Da(e,t){return t?Ea(e,t):e}function Oa(e,t={}){let n=Sa(t.future),r={palette:n.palette,semantic:n.semantic,components:n.components},i={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:Da(r.components,e?.components)},a=e?.components?.activity;for(let e of[`toolBubble`,`reasoningBubble`])for(let t of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[t]!==void 0&&(i.components[e][t]=a[t]);let o=e?.components?.collapsibleWidget?.surface;o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=e?.components?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=Ta(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const ka=e=>e.trim()===`0`?`0px`:e,Aa=`--persona-`,ja=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},Ma=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[Aa+n],t!==void 0)break;t!==void 0&&(e[Aa+n]=t)}};function Na(e){let t=wa(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}Ma(n,[[`primary`,`semantic-colors-primary`,`palette-colors-primary-500`],[`secondary`,`semantic-colors-secondary`,`palette-colors-secondary-500`],[`accent`,`semantic-colors-accent`,`palette-colors-accent-500`],[`surface`,`semantic-colors-surface`,`palette-colors-gray-50`],[`background`,`semantic-colors-background`,`palette-colors-gray-50`],[`container`,`semantic-colors-container`,`palette-colors-gray-100`],[`text`,`semantic-colors-text`,`palette-colors-gray-900`],[`text-muted`,`semantic-colors-text-muted`,`palette-colors-gray-500`],[`text-inverse`,`semantic-colors-text-inverse`,`palette-colors-gray-50`],[`border`,`semantic-colors-border`,`palette-colors-gray-200`],[`divider`,`semantic-colors-divider`,`palette-colors-gray-200`],[`muted`,`text-muted`],[`voice-recording-indicator`,`components-voice-recording-indicator`,`palette-colors-error-500`],[`voice-recording-bg`,`components-voice-recording-background`,`palette-colors-error-50`],[`voice-processing-icon`,`components-voice-processing-icon`,`palette-colors-primary-500`],[`voice-speaking-icon`,`components-voice-speaking-icon`,`palette-colors-success-500`],[`approval-bg`,`components-approval-requested-background`,`surface`],[`approval-border`,`components-approval-requested-border`,`border`],[`approval-text`,`components-approval-requested-text`,`palette-colors-gray-900`],[`approval-shadow`,`components-approval-requested-shadow`,`=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)`],[`approval-approve-bg`,`components-approval-approve-background`,`button-primary-bg`],[`approval-deny-bg`,`components-approval-deny-background`,`container`],[`attachment-image-bg`,`components-attachment-image-background`,`palette-colors-gray-100`],[`attachment-image-border`,`components-attachment-image-border`,`palette-colors-gray-200`],[`font-family`,`semantic-typography-fontFamily`,`palette-typography-fontFamily-sans`],[`font-size`,`semantic-typography-fontSize`,`palette-typography-fontSize-base`],[`font-weight`,`semantic-typography-fontWeight`,`palette-typography-fontWeight-normal`],[`line-height`,`semantic-typography-lineHeight`,`palette-typography-lineHeight-normal`],[`input-font-family`,`font-family`],[`input-font-weight`,`font-weight`],[`radius-sm`,`palette-radius-sm`,`=0.125rem`],[`radius-md`,`palette-radius-md`,`=0.375rem`],[`radius-lg`,`palette-radius-lg`,`=0.5rem`],[`radius-xl`,`palette-radius-xl`,`=0.75rem`],[`radius-full`,`palette-radius-full`,`=9999px`],[`launcher-radius`,`components-launcher-borderRadius`,`palette-radius-full`,`=9999px`],[`launcher-bg`,`components-launcher-background`,`surface`],[`launcher-fg`,`components-launcher-foreground`,`primary`]]);let r=n[`--persona-components-launcher-foreground`];n[`--persona-launcher-fg-muted`]=r&&r!==n[`--persona-primary`]?`color-mix(in srgb, ${r} 70%, transparent)`:n[`--persona-muted`],Ma(n,[[`launcher-border`,`components-launcher-border`,`border`],[`button-primary-bg`,`components-button-primary-background`,`primary`],[`button-primary-fg`,`components-button-primary-foreground`,`text-inverse`],[`button-radius`,`components-button-primary-borderRadius`,`palette-radius-full`,`=9999px`],[`button-stop-bg`,`components-button-stop-background`],[`button-stop-fg`,`components-button-stop-foreground`]]),Ma(n,[[`button-ghost-bg`,`components-button-ghost-background`,`=transparent`],[`button-ghost-fg`,`components-button-ghost-foreground`,`text`],[`button-ghost-radius`,`components-button-ghost-borderRadius`,`radius-md`,`=0.375rem`],[`button-ghost-hover-bg`,`components-button-ghost-hoverBackground`,`=rgba(0, 0, 0, 0.05)`],[`panel-radius`,`components-panel-borderRadius`,`radius-xl`,`=0.75rem`]]),n[`--persona-panel-border`]=n[`--persona-components-panel-border`]??`1px solid ${n[`--persona-border`]}`,Ma(n,[[`panel-shadow`,`components-panel-shadow`,`palette-shadows-xl`,`=0 25px 50px -12px rgba(0, 0, 0, 0.25)`]]),n[`--persona-panel-inset`]=n[`--persona-components-panel-inset`]??`16px`,n[`--persona-panel-canvas-bg`]=n[`--persona-components-panel-canvasBackground`]??`transparent`,Ma(n,[[`launcher-shadow`,`components-launcher-shadow`,`=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)`],[`input-radius`,`components-input-borderRadius`,`radius-lg`,`=0.5rem`],[`message-user-radius`,`components-message-user-borderRadius`,`radius-lg`,`=0.5rem`],[`message-assistant-radius`,`components-message-assistant-borderRadius`,`radius-lg`,`=0.5rem`]]),Ma(n,[[`header-bg`,`components-header-background`,`surface`]]);let i=n[`--persona-header-bg`],a=n[`--persona-components-header-foreground`],o=a?`color-mix(in srgb, ${a} 72%, ${i})`:void 0;n[`--persona-header-border`]=n[`--persona-components-header-border`]??(a?`color-mix(in srgb, ${a} 14%, ${i})`:void 0)??n[`--persona-divider`],Ma(n,[[`header-icon-bg`,`components-header-iconBackground`,`primary`],[`header-icon-fg`,`components-header-iconForeground`,`text-inverse`]]),n[`--persona-header-title-fg`]=n[`--persona-components-header-title-color`]??n[`--persona-components-header-titleForeground`]??a??n[`--persona-primary`],n[`--persona-header-subtitle-fg`]=n[`--persona-components-header-subtitle-color`]??n[`--persona-components-header-subtitleForeground`]??o??n[`--persona-text-muted`],n[`--persona-header-action-icon-fg`]=n[`--persona-components-header-actionIconForeground`]??o??n[`--persona-muted`],Ma(n,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=20px`]]);let s=e.components?.header;s?.shadow&&(n[`--persona-header-shadow`]=s.shadow),s?.borderBottom&&(n[`--persona-header-border-bottom`]=s.borderBottom),s?.minHeight&&(n[`--persona-header-min-height`]=s.minHeight);let c=n[`--persona-components-history-railHeader-background`];c&&(n[`--persona-history-rail-header-bg`]=c);let l=n[`--persona-components-history-railHeader-border`];l&&(n[`--persona-history-rail-header-border`]=l);let u=n[`--persona-components-history-railHeader-minHeight`];u&&(n[`--persona-history-rail-header-min-height`]=u);for(let[e,t]of[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]]){let r=n[`--persona-components-history-overlay-${e}`];r&&(n[`--persona-history-overlay-${t}`]=r)}for(let[e,t]of[[`background`,`bg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-history-menu-${e}`];r&&(n[`--persona-history-menu-${t}`]=r)}let d=e.components?.history?.motion;if(d){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(d.enterDurationMs);t!==void 0&&(n[`--persona-history-enter-ms`]=t);let r=e(d.exitDurationMs);r!==void 0&&(n[`--persona-history-exit-ms`]=r),d.enterEasing&&(n[`--persona-history-enter-easing`]=d.enterEasing),d.exitEasing&&(n[`--persona-history-exit-easing`]=d.exitEasing)}let f=n[`--persona-components-history-dangerForeground`];f&&(n[`--persona-history-danger-fg`]=f),n[`--persona-danger`]=n[`--persona-components-history-confirm-dangerBackground`]??n[`--persona-palette-colors-error-700`]??`#b42318`,n[`--persona-danger-fg`]=n[`--persona-components-history-confirm-dangerForeground`]??`#ffffff`;for(let e of[`scrim`,`shadow`]){let t=n[`--persona-components-history-confirm-${e}`];t&&(n[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]]){let r=n[`--persona-components-tooltip-${e}`];r&&(n[`--persona-tooltip-${t}`]=r)}e.components?.tooltip?.arrow===!1&&(n[`--persona-tooltip-arrow-display`]=`none`);for(let[e,t]of[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-messageActions-${e}`];r&&(n[`--persona-message-action-${t}`]=r)}Ma(n,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let p=n[`--persona-components-introCard-background`],m=n[`--persona-components-introCard-shadow`],h=(!p||p===`transparent`||p===`none`)&&(!m||m===`none`),g=n[`--persona-components-introCard-padding`]??`1.5rem`;n[`--persona-intro-card-padding`]=h&&g===`1.5rem`?`1.5rem 0`:g,Ma(n,[[`intro-card-shadow`,`components-introCard-shadow`,`=none`],[`intro-card-border`,`components-introCard-border`,`=none`],[`input-background`,`components-input-background`,`surface`],[`input-placeholder`,`components-input-placeholder`,`text-muted`],[`input-backdrop-filter`,`components-input-backdropFilter`,`=none`],[`message-user-bg`,`components-message-user-background`,`accent`],[`message-user-text`,`components-message-user-text`,`text-inverse`],[`message-user-shadow`,`components-message-user-shadow`,`=0 5px 15px rgba(15, 23, 42, 0.08)`],[`message-assistant-bg`,`components-message-assistant-background`,`surface`],[`message-assistant-text`,`components-message-assistant-text`,`text`],[`message-assistant-border`,`components-message-assistant-border`,`border`],[`message-assistant-shadow`,`components-message-assistant-shadow`,`=0 1px 2px 0 rgb(0 0 0 / 0.05)`],[`scroll-to-bottom-bg`,`components-scrollToBottom-background`,`button-primary-bg`,`accent`],[`scroll-to-bottom-fg`,`components-scrollToBottom-foreground`,`button-primary-fg`,`text-inverse`],[`scroll-to-bottom-border`,`components-scrollToBottom-border`,`primary`],[`scroll-to-bottom-size`,`components-scrollToBottom-size`,`=40px`],[`scroll-to-bottom-radius`,`components-scrollToBottom-borderRadius`,`button-radius`,`radius-full`,`=9999px`],[`scroll-to-bottom-shadow`,`components-scrollToBottom-shadow`,`palette-shadows-sm`,`=0 1px 2px 0 rgb(0 0 0 / 0.05)`],[`scroll-to-bottom-padding`,`components-scrollToBottom-padding`,`=0.5rem 0.875rem`],[`scroll-to-bottom-gap`,`components-scrollToBottom-gap`,`=0.5rem`],[`scroll-to-bottom-font-size`,`components-scrollToBottom-fontSize`,`palette-typography-fontSize-sm`,`=0.875rem`],[`scroll-to-bottom-icon-size`,`components-scrollToBottom-iconSize`,`=14px`],[`event-badge-flow-bg`,`components-eventStream-badge-flow-background`,`=#dcfce7`],[`event-badge-flow-fg`,`components-eventStream-badge-flow-foreground`,`=#15803d`],[`event-badge-step-bg`,`components-eventStream-badge-step-background`,`=#f5f5f5`],[`event-badge-step-fg`,`components-eventStream-badge-step-foreground`,`=#0a0a0a`],[`event-badge-reasoning-bg`,`components-eventStream-badge-reasoning-background`,`=#fef9c3`],[`event-badge-reasoning-fg`,`components-eventStream-badge-reasoning-foreground`,`=#a16207`],[`event-badge-tool-bg`,`components-eventStream-badge-tool-background`,`=#f3e8ff`],[`event-badge-tool-fg`,`components-eventStream-badge-tool-foreground`,`=#6b21a8`],[`event-badge-agent-bg`,`components-eventStream-badge-agent-background`,`=#ccfbf1`],[`event-badge-agent-fg`,`components-eventStream-badge-agent-foreground`,`=#115e59`],[`event-badge-error-bg`,`components-eventStream-badge-error-background`,`=#fee2e2`],[`event-badge-error-fg`,`components-eventStream-badge-error-foreground`,`=#b91c1c`],[`event-badge-default-bg`,`components-eventStream-badge-default-background`,`=#f3f4f6`],[`event-badge-default-fg`,`components-eventStream-badge-default-foreground`,`=#4b5563`],[`tool-bubble-shadow`,`components-toolBubble-shadow`,`=0 5px 15px rgba(15, 23, 42, 0.08)`],[`reasoning-bubble-shadow`,`components-reasoningBubble-shadow`,`=0 5px 15px rgba(15, 23, 42, 0.08)`],[`composer-shadow`,`components-composer-shadow`,`=none`]]),Ma(n,[[`composer-padding`,`components-composer-padding`,`=0.75rem 1rem`],[`composer-gap`,`components-composer-gap`,`=0.5rem`],[`composer-font-size`,`components-composer-fontSize`,`=0.875rem`],[`composer-line-height`,`components-composer-lineHeight`,`=1.25rem`],[`composer-control-size`,`components-composer-controlSize`,`=40px`],[`composer-control-icon-size`,`components-composer-controlIconSize`,`=24px`],[`motion-duration-fast`,`components-motion-durationFast`,`=120ms`],[`motion-duration-base`,`components-motion-durationBase`,`=200ms`],[`motion-easing`,`components-motion-easing`,`=cubic-bezier(0.2, 0, 0, 1)`],[`composer-border-color`,`components-composer-borderColor`,`border`,`=#e5e7eb`],[`composer-overlay-band`,`components-composer-overlayBand`,`=transparent`],[`scrollbar-thumb`,`components-scrollbar-thumb`,`border`,`=#e5e7eb`],[`scrollbar-track`,`components-scrollbar-track`,`=transparent`],[`md-inline-code-bg`,`components-markdown-inlineCode-background`,`container`],[`md-inline-code-color`,`components-markdown-inlineCode-foreground`,`text`],[`md-link-color`,`components-markdown-link-foreground`,`accent`,`=#0f0f0f`]]);let _=n[`--persona-components-markdown-heading-h1-fontSize`];_&&(n[`--persona-md-h1-size`]=_);let v=n[`--persona-components-markdown-heading-h1-fontWeight`];v&&(n[`--persona-md-h1-weight`]=v);let y=n[`--persona-components-markdown-heading-h2-fontSize`];y&&(n[`--persona-md-h2-size`]=y);let b=n[`--persona-components-markdown-heading-h2-fontWeight`];b&&(n[`--persona-md-h2-weight`]=b);let x=n[`--persona-components-markdown-prose-fontFamily`];x&&x!==`inherit`&&(n[`--persona-md-prose-font-family`]=x),Ma(n,[[`md-code-block-bg`,`components-markdown-codeBlock-background`,`container`],[`md-code-block-border-color`,`components-markdown-codeBlock-borderColor`,`border`],[`md-code-block-text-color`,`components-markdown-codeBlock-textColor`,`=inherit`]]),Ma(n,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),Ma(n,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),Ma(n,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),Ma(n,[[`md-blockquote-border-color`,`components-markdown-blockquote-borderColor`,`palette-colors-gray-900`],[`md-blockquote-bg`,`components-markdown-blockquote-background`,`=transparent`],[`md-blockquote-text-color`,`components-markdown-blockquote-textColor`,`palette-colors-gray-500`]]);for(let[e,t]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=n[`--persona-components-collapsibleWidget-${e}`]??n[`--persona-${t}`];r!==void 0&&(n[`--persona-cw-${e}`]=r,n[`--cw-${e}`]=r)}Ma(n,[[`message-border`,`components-message-border`,`border`]]),Ma(n,[[`message-user-padding`,`components-message-user-padding`],[`message-user-max-width`,`components-message-user-maxWidth`],[`message-user-font-size`,`components-message-user-fontSize`],[`message-user-font-family`,`components-message-user-fontFamily`],[`message-user-line-height`,`components-message-user-lineHeight`],[`message-assistant-padding`,`components-message-assistant-padding`],[`message-assistant-border-width`,`components-message-assistant-borderWidth`],[`message-assistant-max-width`,`components-message-assistant-maxWidth`],[`message-assistant-font-size`,`components-message-assistant-fontSize`],[`message-assistant-font-family`,`components-message-assistant-fontFamily`],[`message-assistant-line-height`,`components-message-assistant-lineHeight`]]);let S=e.components,C=S?.iconButton;C&&(C.background&&(n[`--persona-icon-btn-bg`]=C.background),C.border&&(n[`--persona-icon-btn-border`]=C.border),C.color&&(n[`--persona-icon-btn-color`]=C.color),C.padding&&(n[`--persona-icon-btn-padding`]=C.padding),C.borderRadius&&(n[`--persona-icon-btn-radius`]=C.borderRadius),C.hoverBackground&&(n[`--persona-icon-btn-hover-bg`]=C.hoverBackground),C.hoverColor&&(n[`--persona-icon-btn-hover-color`]=C.hoverColor),C.activeBackground&&(n[`--persona-icon-btn-active-bg`]=C.activeBackground),C.activeBorder&&(n[`--persona-icon-btn-active-border`]=C.activeBorder));let w=S?.labelButton;w&&(w.background&&(n[`--persona-label-btn-bg`]=w.background),w.border&&(n[`--persona-label-btn-border`]=w.border),w.color&&(n[`--persona-label-btn-color`]=w.color),w.padding&&(n[`--persona-label-btn-padding`]=w.padding),w.borderRadius&&(n[`--persona-label-btn-radius`]=w.borderRadius),w.hoverBackground&&(n[`--persona-label-btn-hover-bg`]=w.hoverBackground),w.fontSize&&(n[`--persona-label-btn-font-size`]=w.fontSize),w.gap&&(n[`--persona-label-btn-gap`]=w.gap));let T=S?.toggleGroup;T&&(T.gap&&(n[`--persona-toggle-group-gap`]=T.gap),T.borderRadius&&(n[`--persona-toggle-group-radius`]=T.borderRadius));let E=S?.artifact;if(E?.toolbar){let t=E.toolbar;t.iconHoverColor&&(n[`--persona-artifact-toolbar-icon-hover-color`]=t.iconHoverColor),t.iconHoverBackground&&(n[`--persona-artifact-toolbar-icon-hover-bg`]=t.iconHoverBackground),t.iconPadding&&(n[`--persona-artifact-toolbar-icon-padding`]=t.iconPadding),t.iconBorderRadius&&(n[`--persona-artifact-toolbar-icon-radius`]=t.iconBorderRadius),t.iconBorder&&(n[`--persona-artifact-toolbar-icon-border`]=t.iconBorder),t.toggleGroupGap&&(n[`--persona-artifact-toolbar-toggle-group-gap`]=ka(t.toggleGroupGap)),t.toggleBorderRadius&&(n[`--persona-artifact-toolbar-toggle-radius`]=t.toggleBorderRadius),t.toggleGroupPadding&&(n[`--persona-artifact-toolbar-toggle-group-padding`]=ka(t.toggleGroupPadding)),t.toggleGroupBorder&&(n[`--persona-artifact-toolbar-toggle-group-border`]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(n[`--persona-artifact-toolbar-toggle-group-radius`]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(n[`--persona-artifact-toolbar-toggle-group-bg`]=Ca(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(n[`--persona-artifact-toolbar-copy-bg`]=t.copyBackground),t.copyBorder&&(n[`--persona-artifact-toolbar-copy-border`]=t.copyBorder),t.copyColor&&(n[`--persona-artifact-toolbar-copy-color`]=t.copyColor),t.copyBorderRadius&&(n[`--persona-artifact-toolbar-copy-radius`]=ka(t.copyBorderRadius)),t.copyPadding&&(n[`--persona-artifact-toolbar-copy-padding`]=t.copyPadding),t.copyMenuBackground&&(n[`--persona-artifact-toolbar-copy-menu-bg`]=t.copyMenuBackground,n[`--persona-dropdown-bg`]=n[`--persona-dropdown-bg`]??t.copyMenuBackground),t.copyMenuBorder&&(n[`--persona-artifact-toolbar-copy-menu-border`]=t.copyMenuBorder,n[`--persona-dropdown-border`]=n[`--persona-dropdown-border`]??t.copyMenuBorder),t.copyMenuShadow&&(n[`--persona-artifact-toolbar-copy-menu-shadow`]=t.copyMenuShadow,n[`--persona-dropdown-shadow`]=n[`--persona-dropdown-shadow`]??t.copyMenuShadow),t.copyMenuBorderRadius&&(n[`--persona-artifact-toolbar-copy-menu-radius`]=t.copyMenuBorderRadius,n[`--persona-dropdown-radius`]=n[`--persona-dropdown-radius`]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(n[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=t.copyMenuItemHoverBackground,n[`--persona-dropdown-item-hover-bg`]=n[`--persona-dropdown-item-hover-bg`]??t.copyMenuItemHoverBackground),t.iconBackground&&(n[`--persona-artifact-toolbar-icon-bg`]=t.iconBackground),t.toolbarBorder&&(n[`--persona-artifact-toolbar-border`]=t.toolbarBorder)}if(E?.tab){let e=E.tab;e.background&&(n[`--persona-artifact-tab-bg`]=e.background),e.activeBackground&&(n[`--persona-artifact-tab-active-bg`]=e.activeBackground),e.activeBorder&&(n[`--persona-artifact-tab-active-border`]=e.activeBorder),e.borderRadius&&(n[`--persona-artifact-tab-radius`]=e.borderRadius),e.textColor&&(n[`--persona-artifact-tab-color`]=e.textColor),e.hoverBackground&&(n[`--persona-artifact-tab-hover-bg`]=e.hoverBackground),e.listBackground&&(n[`--persona-artifact-tab-list-bg`]=e.listBackground),e.listBorderColor&&(n[`--persona-artifact-tab-list-border-color`]=e.listBorderColor),e.listPadding&&(n[`--persona-artifact-tab-list-padding`]=e.listPadding)}if(E?.pane){let t=E.pane;t.toolbarBackground&&(n[`--persona-artifact-toolbar-bg`]=Ca(e,t.toolbarBackground)??t.toolbarBackground)}if(E?.card){let e=E.card;e.background&&(n[`--persona-artifact-card-bg`]=e.background),e.border&&(n[`--persona-artifact-card-border`]=e.border),e.borderRadius&&(n[`--persona-artifact-card-radius`]=e.borderRadius),e.hoverBackground&&(n[`--persona-artifact-card-hover-bg`]=e.hoverBackground),e.hoverBorderColor&&(n[`--persona-artifact-card-hover-border`]=e.hoverBorderColor)}if(E?.inline){let t=E.inline;t.background&&(n[`--persona-artifact-inline-bg`]=Ca(e,t.background)??t.background),t.border&&(n[`--persona-artifact-inline-border`]=t.border),t.borderRadius&&(n[`--persona-artifact-inline-radius`]=t.borderRadius),t.chromeBackground&&(n[`--persona-artifact-inline-chrome-bg`]=Ca(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(n[`--persona-artifact-inline-chrome-border`]=Ca(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(n[`--persona-artifact-inline-title-color`]=Ca(e,t.titleColor)??t.titleColor),t.mutedColor&&(n[`--persona-artifact-inline-muted-color`]=Ca(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(n[`--persona-artifact-inline-frame-height`]=t.frameHeight)}let D=S?.code;D&&(D.keywordColor&&(n[`--persona-code-keyword-color`]=D.keywordColor),D.stringColor&&(n[`--persona-code-string-color`]=D.stringColor),D.commentColor&&(n[`--persona-code-comment-color`]=D.commentColor),D.numberColor&&(n[`--persona-code-number-color`]=D.numberColor),D.tagColor&&(n[`--persona-code-tag-color`]=D.tagColor),D.attrColor&&(n[`--persona-code-attr-color`]=D.attrColor),D.propertyColor&&(n[`--persona-code-property-color`]=D.propertyColor),D.lineNumberColor&&(n[`--persona-code-line-number-color`]=D.lineNumberColor),D.gutterBorderColor&&(n[`--persona-code-gutter-border-color`]=D.gutterBorderColor),D.background&&(n[`--persona-code-bg`]=Ca(e,D.background)??D.background));let ee=n[`--persona-surface`],te=n[`--persona-container`],ne=n[`--persona-palette-colors-gray-100`]??`#f3f4f6`,re=n[`--persona-palette-colors-gray-200`]??`#e5e7eb`,ie=n[`--persona-palette-colors-gray-300`]??`#d1d5db`,ae=!te||te===ee,oe=ja(ee??n[`--persona-background`]),se=ae&&oe!==void 0&&oe<.179,O=se?`rgba(255, 255, 255, 0.08)`:ne,ce=se?`rgba(255, 255, 255, 0.12)`:re,le=se?`rgba(255, 255, 255, 0.16)`:ie,ue=ae?O:te,de=ae?ce:te;return n[`--persona-icon-btn-hover-bg`]=n[`--persona-icon-btn-hover-bg`]??ue,n[`--persona-icon-btn-active-bg`]=n[`--persona-icon-btn-active-bg`]??de,ae&&(n[`--persona-icon-btn-active-border`]=n[`--persona-icon-btn-active-border`]??le),n[`--persona-label-btn-hover-bg`]=n[`--persona-label-btn-hover-bg`]??ue,n[`--persona-artifact-tab-hover-bg`]=n[`--persona-artifact-tab-hover-bg`]??ue,n[`--persona-artifact-card-hover-bg`]=n[`--persona-artifact-card-hover-bg`]??ue,n}const Pa=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),Fa=(e,t)=>{if(!t||!Pa(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(Ka(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:T(t)===`v5`?`400px`:`420px`}}}:e},Ia={colors:{primary:{50:`#ffffff`,100:`#f5f5f5`,200:`#d4d4d4`,300:`#a3a3a3`,400:`#737373`,500:`#171717`,600:`#0f0f0f`,700:`#0a0a0a`,800:`#050505`,900:`#030303`,950:`#000000`},secondary:{50:`#f5f3ff`,100:`#ede9fe`,200:`#ddd6fe`,300:`#c4b5fd`,400:`#a78bfa`,500:`#8b5cf6`,600:`#7c3aed`,700:`#6d28d9`,800:`#5b21b6`,900:`#4c1d95`,950:`#2e1065`},accent:{50:`#ecfeff`,100:`#cffafe`,200:`#a5f3fc`,300:`#67e8f9`,400:`#22d3ee`,500:`#06b6d4`,600:`#0891b2`,700:`#0e7490`,800:`#155e75`,900:`#164e63`,950:`#083344`},gray:{50:`#f9fafb`,100:`#f3f4f6`,200:`#e5e7eb`,300:`#d1d5db`,400:`#9ca3af`,500:`#6b7280`,600:`#4b5563`,700:`#374151`,800:`#1f2937`,900:`#111827`,950:`#030712`},success:{50:`#f0fdf4`,100:`#dcfce7`,200:`#bbf7d0`,300:`#86efac`,400:`#4ade80`,500:`#22c55e`,600:`#16a34a`,700:`#15803d`,800:`#166534`,900:`#14532d`},warning:{50:`#fefce8`,100:`#fef9c3`,200:`#fef08a`,300:`#fde047`,400:`#facc15`,500:`#eab308`,600:`#ca8a04`,700:`#a16207`,800:`#854d0e`,900:`#713f12`},error:{50:`#fef2f2`,100:`#fee2e2`,200:`#fecaca`,300:`#fca5a5`,400:`#f87171`,500:`#ef4444`,600:`#dc2626`,700:`#b91c1c`,800:`#991b1b`,900:`#7f1d1d`}}},La={components:{button:{ghost:{hoverBackground:`rgba(255, 255, 255, 0.08)`}},markdown:{link:{foreground:`palette.colors.primary.300`}},eventStream:{badge:{flow:{background:`palette.colors.success.900`,foreground:`palette.colors.success.300`},step:{background:`palette.colors.primary.800`,foreground:`palette.colors.primary.200`},reasoning:{background:`palette.colors.warning.900`,foreground:`palette.colors.warning.300`},tool:{background:`palette.colors.purple.900`,foreground:`palette.colors.purple.300`},agent:{background:`palette.colors.teal.900`,foreground:`palette.colors.teal.300`},error:{background:`palette.colors.error.900`,foreground:`palette.colors.error.300`},default:{background:`palette.colors.gray.800`,foreground:`palette.colors.gray.300`}}},history:{dangerForeground:`#f87171`,confirm:{dangerBackground:`palette.colors.error.600`,scrim:`rgba(0, 0, 0, 0.6)`}}}},Ra=Ia,za={...Ra,colors:{...Ra.colors,primary:{50:`#0f0f10`,100:`#27272a`,200:`#3f3f46`,300:`#52525b`,400:`#71717a`,500:`#f4f4f5`,600:`#e4e4e7`,700:`#d4d4d8`,800:`#a1a1aa`,900:`#fafafa`,950:`#ffffff`},gray:{50:`#1a1a1b`,100:`#27272a`,200:`#2a2a2d`,300:`#52525b`,400:`#71717a`,500:`#a1a1aa`,600:`#b4b4bd`,700:`#d4d4d8`,800:`#e4e4e7`,900:`#f4f4f5`,950:`#fafafa`}}},Ba=La,Va={semantic:{colors:{primary:`palette.colors.primary.500`,accent:`palette.colors.primary.600`,background:`#0f0f10`,surface:`palette.colors.gray.50`,container:`#1c1c20`,text:`palette.colors.gray.900`,textMuted:`palette.colors.gray.500`,textInverse:`#0f0f10`,border:`palette.colors.gray.200`,divider:`palette.colors.gray.200`,interactive:{default:`palette.colors.primary.600`,hover:`palette.colors.primary.700`,focus:`palette.colors.primary.600`,active:`palette.colors.primary.600`}}},components:{...La.components,button:{...La.components?.button,primary:{background:`semantic.colors.primary`,foreground:`palette.colors.primary.50`}},markdown:{inlineCode:{background:`palette.colors.gray.100`,foreground:`semantic.colors.text`},link:{foreground:`semantic.colors.accent`},codeBlock:{background:`semantic.colors.container`,borderColor:`semantic.colors.border`,textColor:`semantic.colors.text`},table:{headerBackground:`palette.colors.gray.100`,borderColor:`semantic.colors.border`},blockquote:{background:`semantic.colors.container`,borderColor:`palette.colors.gray.300`,textColor:`semantic.colors.textMuted`}},eventStream:{...La.components?.eventStream,badge:{...La.components?.eventStream?.badge,step:{background:`palette.colors.gray.100`,foreground:`palette.colors.gray.700`},default:{background:`palette.colors.gray.100`,foreground:`palette.colors.gray.700`}}}}},Ha=e=>T({future:e})===`v5`?{palette:za,components:Va}:{palette:Ra,components:Ba},Ua=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},Wa=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,Ga=e=>{let t=e?.colorScheme??`light`;return t===`light`?`light`:t===`dark`?`dark`:Wa()},Ka=e=>Ga(e),qa=(e,t={})=>Oa(e,t),Ja=(e,t={})=>{let n=Ha(t.future),r=ce(n.components,e??{})??{};return Oa({...r,palette:{...r.palette,colors:T(t)===`v5`?ce(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},Ya=e=>{let t=Ka(e),n=Ua(e?.theme),r=sa(e)===`circle`?ca:{...ya.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}},i=ce({components:{launcher:r}},n),a=Ua(e?.darkTheme);return Fa(t===`dark`?Ja(ce(i??{},a??{}),{future:e?.future}):qa(i,{future:e?.future}),e)},Xa=e=>Na(e),Za=(e,t)=>{let n=Ya(t),r=Xa(n);for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute(`data-persona-color-scheme`,Ka(t)),e.setAttribute(`data-persona-defaults`,T(t))},Qa=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(Wa())});n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),t.push(()=>n.disconnect())}if(typeof window<`u`&&window.matchMedia){let n=window.matchMedia(`(prefers-color-scheme: dark)`),r=()=>e(Wa());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},$a=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),eo=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,to=e=>{if(typeof e!=`string`)return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},no=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight),ro=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;un.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&!t.hasAttribute(`data-preserve-animation`)||t instanceof HTMLElement&&t.hasAttribute(`data-preserve-animation`)&&(e.textContent??``)!==(t.textContent??``)?void 0:!1}}}})},io=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),ao={index:-1,draft:``};function oo(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function so(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??``,e.streaming?`1`:`0`,e.voiceProcessing?`1`:`0`,e.variant??``,e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??``,e.toolCall?.status??``,e.toolCall?.name??``,e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??``,typeof e.toolCall?.args==`string`?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??``,e.contentParts?.length??0,e.stopReason??``,t].join(`\0`)}function co(){return/* @__PURE__ */ new Map}function lo(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function uo(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function fo(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}const{setLoader:po,load:mo}=Ne({fallbackImport:()=>import(`./chunk-Dg7uqL8l.js`)}),ho=mo;function go(e,t=St){let n=e.style.position,r=e.style.zIndex,i=e.style.isolation,a=getComputedStyle(e),o=a.position===`static`||a.position===``;return o&&(e.style.position=`relative`),e.style.zIndex=String(t),e.style.isolation=`isolate`,()=>{o&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=i}}let _o=0,vo=null;function yo(e=document){if(_o++,_o===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;vo={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:n},t.style.overflow=`hidden`,t.style.position=`fixed`,t.style.top=`-${n}px`,t.style.width=`100%`}let t=!1;return()=>{if(!t&&(t=!0,_o=Math.max(0,_o-1),_o===0&&vo)){let t=e.body,n=e.defaultView??window;t.style.overflow=vo.originalOverflow,t.style.position=vo.originalPosition,t.style.top=vo.originalTop,t.style.width=vo.originalWidth,n.scrollTo(0,vo.scrollY),vo=null}}}const bo={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},xo=e=>(e?.launcher?.mountMode??`floating`)===`docked`,So=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,Co=e=>{let t=e?.launcher?.dock,n=D(e).dockWidth?t?.width:Ca(Ya(e),`components.panel.width`);return{side:t?.side??bo.side,width:n??bo.width,animate:t?.animate??bo.animate,reveal:t?.reveal??bo.reveal,maxHeight:t?.maxHeight??bo.maxHeight}},wo=e=>e===`followUp`?`follow-up`:e,To=(e,t=0)=>{if(typeof e==`string`){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:`default`}:null}let n=e.label.trim();if(!n)return null;let r=e.prompt?.trim()||n;return{id:e.id?.trim()||r||`suggestion-${t}`,label:n,prompt:r,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??`default`}},Eo=/* @__PURE__ */ new WeakSet,Do=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Oo=e=>{Do()||e.forEach((e,t)=>{typeof e.animate==`function`&&e.animate([{opacity:`0`,transform:`translateY(4px)`},{opacity:`1`,transform:`none`}],{duration:250,delay:t*60,easing:`ease-out`,fill:`backwards`})})},ko=e=>{let{item:t,index:n,surface:r,source:i,variant:a,streaming:o,config:s,plugins:c,chipsConfig:l,session:u,getTextarea:d,eventTarget:f,submitPrompt:p}=e,m=r===`followUp`,h=t.behavior,g=()=>{if(u.isStreaming())return;let e={suggestion:{...t},surface:r,source:i,behavior:h},n=f.dispatchEvent(new CustomEvent(`persona:suggestion:selected`,{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(m&&f.dispatchEvent(new CustomEvent(`persona:suggestReplies:selected`,{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!n)return;for(let e of c)if(e.onSuggestionSelect?.({suggestion:{...t},surface:r,source:i,variant:a,config:s})===!1)return;let o=d();h===`fill`?(o.value=t.prompt,o.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),o.focus()):p?p(t.prompt):(o.value=``,u.sendMessage(t.prompt))},_=()=>{let e=M(`button`,`persona-suggestion persona-suggestion--${a}`);if(e.type=`button`,e.disabled=o,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=h,a===`chip`&&(l?.fontWeight&&(e.style.fontWeight=l.fontWeight),l?.paddingX&&(e.style.paddingLeft=l.paddingX,e.style.paddingRight=l.paddingX),l?.paddingY&&(e.style.paddingTop=l.paddingY,e.style.paddingBottom=l.paddingY)),t.icon){let n=N(t.icon,`var(--persona-suggestion-icon-size)`,`currentColor`,1.8);n&&(n.classList.add(`persona-suggestion__icon`),t.iconColor&&(n.style.color=t.iconColor),e.appendChild(n))}let n=M(`span`,`persona-suggestion__copy`);if(n.appendChild(j(`span`,{className:`persona-suggestion__label`,text:t.label})),t.description&&a!==`chip`&&n.appendChild(j(`span`,{className:`persona-suggestion__description`,text:t.description})),e.appendChild(n),a!==`chip`){let t=b(Xt,16,`currentColor`,1.8);t&&(t.classList.add(`persona-suggestion__arrow`),e.appendChild(t))}return e.addEventListener(`click`,g),e},v=null;for(let e of c)if(e.renderSuggestion&&(v=e.renderSuggestion({suggestion:{...t},index:n,surface:r,source:i,variant:a,streaming:o,config:s,defaultRenderer:_,select:g}),v))break;return v??=_(),v.dataset.suggestionId||=t.id,v.dataset.behavior||=h,v.dataset.emphasis||=t.emphasis,v instanceof HTMLButtonElement||v.setAttribute(`aria-disabled`,o?`true`:`false`),v},Ao=e=>{let t=[],n=[],r=null,i=null,a=()=>{e.removeAttribute(`data-scroll-left`),e.removeAttribute(`data-scroll-right`)},o=()=>{if(i=null,e.hidden||e.dataset.variant!==`chip`||e.dataset.overflow!==`scroll`){a();return}let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1){a();return}let n=getComputedStyle(e).direction===`rtl`,r=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),o=r<=4,s=r>=t-4,c=n?!s:!o,l=n?!o:!s;e.toggleAttribute(`data-scroll-left`,c),e.toggleAttribute(`data-scroll-right`,l)},s=()=>{i!==null||typeof requestAnimationFrame!=`function`?typeof requestAnimationFrame!=`function`&&o():i=requestAnimationFrame(o)};e.addEventListener(`scroll`,s,{passive:!0});let c=typeof ResizeObserver==`function`?new ResizeObserver(s):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener(`scroll`,s),c?.disconnect(),i!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),i=null},render:(i,c,l,u,d,f)=>{e.replaceChildren(),t.length=0,n.length=0;let p=f?.source??`config`,m=f?.surface??(p===`config`?`starter`:`followUp`),h=m===`followUp`,g=f?.variant??`chip`,_=f?.behavior??`send`,v=f?.overflow??`wrap`,y=f?.config??{},b=f?.plugins??[],x=typeof f?.maxItems==`number`?Math.max(0,Math.floor(f.maxItems)):void 0,S=h?`followUps`:`starters`;!Eo.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(Eo.add(y),console.info(`[persona] suggestions.${S}.overflow applies to the "chip" variant only; the "${g}" variant manages its own stacking.`));let C=e=>e.map(To).filter(e=>e!==null).map(e=>({...e,behavior:e.behavior??_})),w=C(i??[]);b.forEach(e=>{e.transformSuggestions&&(w=C(e.transformSuggestions({suggestions:w.map(e=>({...e})),surface:m,source:p,config:y})))});let T=x===void 0?w:w.slice(0,x);if(!T.length){e.hidden=!0,r=null,a();return}if(!h&&(u??c.getMessages()).some(e=>e.role===`user`)){e.hidden=!0,r=null;return}e.hidden=!1,e.classList.add(`persona-suggestions`),e.dataset.personaSuggestionSurface=wo(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=ko({item:r,index:i,surface:m,source:p,variant:g,streaming:D,config:y,plugins:b,chipsConfig:d,session:c,getTextarea:()=>l,eventTarget:e,submitPrompt:f?.submitPrompt});E.appendChild(a),n.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll(`button`))].forEach(e=>{t.includes(e)||(e.disabled=D,t.push(e))})}),e.appendChild(E),o(),s();let ee=JSON.stringify({normalized:T,surface:m,variant:g,source:p});ee!==r&&(r=ee,Oo(n),e.dispatchEvent(new CustomEvent(`persona:suggestion:shown`,{detail:{suggestions:T.map(e=>({...e})),surface:m,source:p,variant:g},bubbles:!0,composed:!0})),h&&e.dispatchEvent(new CustomEvent(`persona:suggestReplies:shown`,{detail:{suggestions:T.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},jo={"bottom-right":`persona-bottom-6 persona-right-6`,"bottom-left":`persona-bottom-6 persona-left-6`,"top-right":`persona-top-6 persona-right-6`,"top-left":`persona-top-6 persona-left-6`},Mo={x:[1.4,1.05]},Z=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,No=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=Mo[t]??[1,1.5],s=!r;e.classList.toggle(`persona-header-control--glyph`,s),e.classList.toggle(`persona-header-control--sparse`,s&&a!==1);let c=N(t,`${Math.round((parseFloat(r??``)||20)*a)}px`,`currentColor`,o);c?(c.style.display=`block`,s||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((o/1.5).toFixed(4))})`),e.replaceChildren(c)):i&&(e.textContent=i)},Po=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:r,iconName:i,iconText:a,wrapperClassName:o=Z,size:s,iconSize:c,color:l,backgroundColor:u,borderWidth:d,borderColor:f,borderRadius:p,paddingX:m,paddingY:h,hidden:g,extraClassName:_,attrs:v}=e,y=M(`div`,o),b=!!(d||f),x=j(`button`,{className:Me(`persona-header-control`,`persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer`,!u&&`persona-bg-transparent hover:persona-bg-gray-100`,!b&&`persona-border-none`,!p&&`persona-rounded-full`,_),attrs:{type:`button`,"aria-label":t,...v},style:{width:s,height:s,minWidth:s,minHeight:s,display:g?`none`:void 0,color:l||Lo.actionIconColor,backgroundColor:u,border:b?`${d||`0px`} solid ${f||`transparent`}`:void 0,borderRadius:p,paddingLeft:m,paddingRight:m,paddingTop:h,paddingBottom:h}});return i?No(x,i,{iconSize:c,iconText:a}):a&&(x.textContent=a),y.appendChild(x),S({anchor:x,trigger:y,text:()=>x.getAttribute(`aria-label`)??t,hint:r,enabled:n}),{button:x,wrapper:y}},Fo=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=Z,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=Po({ariaLabel:s,tooltip:c,iconName:o.closeButtonIconName??`x`,iconText:o.closeButtonIconText??`×`,wrapperClassName:r,size:i??o.closeButtonSize,iconSize:a,color:o.closeButtonColor,backgroundColor:o.closeButtonBackgroundColor,borderWidth:o.closeButtonBorderWidth,borderColor:o.closeButtonBorderColor,borderRadius:o.closeButtonBorderRadius,paddingX:o.closeButtonPaddingX,paddingY:o.closeButtonPaddingY,hidden:!n});return{button:l,wrapper:u}},Io=(e,t={})=>{let{wrapperClassName:n=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,buttonSize:r,iconSize:i}=t,a=(e?.launcher??{}).clearChat??{},o=a.tooltipText??`Clear chat`,s=a.showTooltip??!0,{button:c,wrapper:l}=Po({ariaLabel:o,tooltip:s,iconName:a.iconName??`refresh-cw`,wrapperClassName:n,size:r??a.size,iconSize:i,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:c,wrapper:l}},Lo={titleColor:`var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))`,subtitleColor:`var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))`,actionIconColor:`var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))`,minHeight:`var(--persona-header-min-height, auto)`},Ro={fontFamily:`var(--persona-components-header-title-fontFamily, inherit)`,fontSize:`var(--persona-components-header-title-fontSize, 1rem)`,fontWeight:`var(--persona-components-header-title-fontWeight, 600)`,lineHeight:`var(--persona-components-header-title-lineHeight, 1.5rem)`,letterSpacing:`var(--persona-components-header-title-letterSpacing, normal)`},zo={fontFamily:`var(--persona-components-header-subtitle-fontFamily, inherit)`,fontSize:`var(--persona-components-header-subtitle-fontSize, 0.75rem)`,fontWeight:`var(--persona-components-header-subtitle-fontWeight, inherit)`,lineHeight:`var(--persona-components-header-subtitle-lineHeight, 1rem)`,letterSpacing:`var(--persona-components-header-subtitle-letterSpacing, normal)`},Bo=e=>{let{config:t,showClose:n=!0}=e,r=j(`div`,{className:`persona-widget-header persona-flex persona-items-center persona-gap-3`,attrs:{"data-persona-theme-zone":`header`},style:{padding:`var(--persona-components-header-padding, 20px 24px)`,minHeight:Lo.minHeight,backgroundColor:`var(--persona-header-bg, var(--persona-surface, #ffffff))`,borderBottomColor:`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,boxShadow:`var(--persona-header-shadow, none)`,borderBottom:`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`}}),i=t?.launcher??{},a=i.headerIconSize??`40px`,o=i.closeButtonPlacement??`inline`,s=i.headerIconHidden??!1,c=i.headerIconName,l=j(`div`,{className:`persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl`,style:{height:a,width:a,backgroundColor:`var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))`,color:`var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))`}});if(!s){if(c){let e=parseFloat(a)||24,n=N(c,e*.6,`currentColor`,1);n?(n.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,n.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,l.replaceChildren(n)):l.textContent=t?.launcher?.agentIconText??`💬`}else if(t?.launcher?.iconUrl){let e=M(`img`);e.src=t.launcher.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=a,e.style.width=a,l.replaceChildren(e)}else l.textContent=t?.launcher?.agentIconText??`💬`}let u=M(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=j(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:Lo.titleColor,...Ro}}),f=j(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:Lo.subtitleColor,...zo}});u.append(d,f),s?r.append(u):r.append(l,u);let p=i.clearChat??{},m=p.enabled??!0,h=p.placement??`inline`,g=null,_=null;if(m){let e=Io(t,{wrapperClassName:h===`top-right`?`persona-absolute persona-top-4 persona-z-50`:`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`});g=e.button,_=e.wrapper,h===`top-right`&&(_.style.right=`48px`),h===`inline`&&r.appendChild(_)}let{button:v,wrapper:y}=Fo(t,{showClose:n,wrapperClassName:o===`top-right`?`persona-absolute persona-top-4 persona-right-4 persona-z-50`:m&&h===`inline`?`persona-relative persona-inline-flex persona-items-center persona-justify-center`:`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`});return o!==`top-right`&&r.appendChild(y),{header:r,iconHolder:l,headerTitle:d,headerSubtitle:f,closeButton:v,closeButtonWrapper:y,clearChatButton:g,clearChatButtonWrapper:_}},Vo=(e,t,n)=>{let r=n?.launcher??{},i=r.closeButtonPlacement??`inline`,a=r.clearChat?.placement??`inline`;e.appendChild(t.header),i===`top-right`&&(e.style.position=`relative`,e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a===`top-right`&&(e.style.position=`relative`,e.appendChild(t.clearChatButtonWrapper))},Ho=e=>{let t=Bo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let e=t.headerTitle.parentElement;e&&(e.style.cursor=`pointer`,e.setAttribute(`role`,`button`),e.setAttribute(`tabindex`,`0`),e.addEventListener(`click`,()=>n()),e.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())}))}return t};function Uo(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=Po({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?_t(r.shortcut):void 0,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`});if(t.setAttribute(`data-persona-header-action`,r.id),r.shortcut){let e=yt(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=Ie({items:r.menuItems,onSelect:e=>n?.(e),anchor:i,position:`bottom-right`});i.appendChild(e.element),t.addEventListener(`click`,t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener(`click`,()=>n?.(r.id));e.appendChild(i)}}const Wo={default:Ho,minimal:e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=M(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=Lo.minHeight,s.style.padding=`var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))`,s.style.backgroundColor=`var(--persona-header-bg, var(--persona-surface, #ffffff))`,s.style.borderBottomColor=`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,s.style.boxShadow=`var(--persona-header-shadow, none)`,s.style.borderBottom=`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`;let c=i?.titleMenu,l,u;if(c){let e=We({label:o.title??`Chat Assistant`,menuItems:c.menuItems,onSelect:t=>{let n=n=>{n===!1&&e.element.dispatchEvent(new CustomEvent(`persona:title-menu-builtin`,{bubbles:!0,composed:!0,detail:{actionId:t}}))},r=c.onSelect(t);r instanceof Promise?r.then(n,()=>{}):n(r)},hover:c.hover,className:``});l=e.element,l.style.color=Lo.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=M(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=M(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=Lo.titleColor,Object.assign(u.style,Ro),u.textContent=o.title??`Chat Assistant`,l.appendChild(u),i?.onTitleClick){l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`);let e=i.onTitleClick;l.addEventListener(`click`,t=>{t.target.closest(`button`)||e()}),l.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())})}let e=i?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??`10px`,l.style.padding=e.padding??`6px 4px 6px 12px`,l.style.margin=`-6px 0 -6px -12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.style.width=`fit-content`,l.style.flex=`none`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=e.background??``,l.style.borderColor=e.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}))}s.appendChild(l);let d=`persona-relative persona-inline-flex persona-items-center persona-justify-center`,{button:f,wrapper:p}=Fo(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=M(`div`,`persona-flex persona-items-center persona-gap-1`);c||Uo(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=Io(t,{wrapperClassName:e===`top-right`?`persona-absolute persona-top-4 persona-z-50`:d});g=n.button,_=n.wrapper,e===`top-right`?_.style.right=`48px`:m.appendChild(_)}m.appendChild(p),s.appendChild(m);let v=M(`div`);v.style.display=`none`;let y=M(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}}},Go=e=>Wo[e]??Wo.default,Ko=(e,t,n)=>{if(t?.render){let r=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=M(`div`);i.style.display=`none`;let a=M(`span`),o=M(`span`),s=M(`button`);s.style.display=`none`;let c=M(`div`);return c.style.display=`none`,{header:r,iconHolder:i,headerTitle:a,headerSubtitle:o,closeButton:s,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??`default`,i=Go(r)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(i.iconHolder.style.display=`none`),t.showTitle===!1&&(i.headerTitle.style.display=`none`),t.showSubtitle===!1&&(i.headerSubtitle.style.display=`none`),t.showCloseButton===!1&&(i.closeButton.style.display=`none`),t.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display=`none`)),i},qo=e=>{let{config:t}=e,n=j(`div`,{className:`persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4`,attrs:{"data-persona-theme-zone":`composer`}}),r=Se(),i=j(`form`,{className:`persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3`,attrs:{"data-persona-composer-form":``}}),{textarea:a,attachAutoResize:o}=ye(t);o();let s=k(t),c=Ee(t),l=fe(t),u=pe(t),d=j(`div`,{className:`persona-widget-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});i.append(d),l&&(l.previewsContainer.style.gap=`8px`,d.append(l.previewsContainer),i.append(l.input)),i.append(a);let f=j(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=j(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=j(`div`,{className:`persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-end":``}});return l&&p.append(l.wrapper),c&&m.append(c.wrapper),m.append(s.wrapper),f.append(p,m),i.append(f),i.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),t?.statusIndicator?.mode===`transient`?n.append(r,u,i):n.append(r,i,u),{footer:n,suggestions:r,composerForm:i,header:d,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:s.setMode}},Jo=()=>{let e=j(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),t=M(`span`,`persona-pill-peek__icon`),n=b(cn,16,`currentColor`,1.5);n&&t.appendChild(n);let r=M(`span`,`persona-pill-peek__text`),i=M(`span`,`persona-pill-peek__caret`),a=b($t,16,`currentColor`,1.5);return a&&i.appendChild(a),e.append(t,r,i),{root:e,textNode:r}},Yo=e=>{let{config:t}=e,n=j(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=Se(),i=pe(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=ye(t,{defaultMaxLines:5});o();let s=k(t),c=Ee(t),l=fe(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=j(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=j(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=j(`div`,{className:`persona-widget-composer__right-actions persona-pill-composer__right`,attrs:{"data-persona-composer-actions-end":``}});c&&f.append(c.wrapper),f.append(s.wrapper),u.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),l&&u.append(l.input),u.append(d,a,f);let p=j(`div`,{className:`persona-pill-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});n.append(p),l&&p.append(l.previewsContainer),n.append(r,u,i);let m=u;return{footer:n,suggestions:r,composerForm:u,header:p,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:i,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:m,leftActions:d,rightActions:f,setSendButtonMode:s.setMode}},Xo=e=>{switch(e){case`max_tool_calls`:return`Stopped after calling a tool. Send a follow-up to continue.`;case`length`:return`Response cut off as max tokens reached. Ask for more to continue.`;case`content_filter`:return`The provider filtered this response.`;case`error`:return`Something went wrong generating this response.`;default:return null}},Zo=(e,t)=>{if(!e)return null;let n=Xo(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},Qo=(e,t)=>{let n=M(`div`,`persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic`);return n.setAttribute(`data-stop-reason`,e),n.setAttribute(`role`,`note`),n.style.opacity=`0.75`,n.textContent=t,n},Q=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},$o=e=>{let t=e.toLowerCase();return t.startsWith(`javascript:`)||t.startsWith(`data:text/html`)||t.startsWith(`data:text/javascript`)||t.startsWith(`data:text/xml`)||t.startsWith(`data:application/xhtml`)||t.startsWith(`data:image/svg+xml`)?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:`)||!e.includes(`:`))},es=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),ts=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),ns=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),rs=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),is=e=>{if(!e||e.length===0)return null;let t=j(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=j(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=M(`span`,`persona-mention-chip-icon`),i=N(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(j(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},as=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(Te(r.ref,{readonly:!0,render:t}));return n},os=(e,t,n,r)=>{let i=Math.random().toString(36).slice(2,8),a=e=>`${i}:${e}`,o=n(t.map((e,t)=>e.kind===`text`?e.text:a(t)).join(``));if(!t.every((e,t)=>e.kind===`text`||o.includes(a(t)))){e.replaceChildren(as(t,r));return}e.innerHTML=o;let s=RegExp(`${i}:(\\d+)`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=[];for(let e=c.nextNode();e;e=c.nextNode())l.push(e);for(let e of l){let n=e;for(let e=s.exec(n.data);e;e=s.exec(n.data)){let i=t[Number(e[1])],a=n.splitText(e.index);a.data=a.data.slice(e[0].length),i?.kind===`mention`&&a.parentNode?.insertBefore(Te(i.ref,{readonly:!0,render:r}),a),n=a}}},ss=(e,t,n)=>{if(e.length===0)return null;try{let r=M(`div`,`persona-flex persona-flex-col persona-gap-2`);r.setAttribute(`data-message-attachments`,`images`),t&&(r.style.marginBottom=`8px`);let i=0,a=!1,o=()=>{a||(a=!0,r.remove(),n?.())};return e.forEach((e,t)=>{let n=M(`img`);n.alt=e.alt?.trim()||`Attached image ${t+1}`,n.loading=`lazy`,n.decoding=`async`,n.referrerPolicy=`no-referrer`,n.style.display=`block`,n.style.width=`100%`,n.style.maxWidth=`320px`,n.style.maxHeight=`320px`,n.style.height=`auto`,n.style.objectFit=`contain`,n.style.borderRadius=`10px`,n.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,n.style.border=`1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))`;let a=!1;i+=1,n.addEventListener(`error`,()=>{a||(a=!0,i=Math.max(0,i-1),n.remove(),i===0&&o())}),n.addEventListener(`load`,()=>{a=!0}),Q(e.image)?(n.src=e.image,r.appendChild(n)):(a=!0,i=Math.max(0,i-1),n.remove())}),i===0?(o(),null):r}catch{return n?.(),null}},cs=e=>{if(e.length===0)return null;try{let t=M(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!$o(e.audio))return;let r=M(`audio`);r.controls=!0,r.preload=`metadata`,r.src=e.audio,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ls=e=>{if(e.length===0)return null;try{let t=M(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!$o(e.video))return;let r=M(`video`);r.controls=!0,r.preload=`metadata`,r.src=e.video,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,r.style.maxHeight=`320px`,r.style.borderRadius=`10px`,r.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},us=e=>{if(e.length===0)return null;try{let t=M(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!$o(e.data))return;let r=M(`a`);r.href=e.data,r.download=e.filename,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=e.filename,r.className=`persona-message-file-attachment`,r.style.display=`inline-flex`,r.style.alignItems=`center`,r.style.gap=`6px`,r.style.padding=`6px 10px`,r.style.borderRadius=`8px`,r.style.fontSize=`0.875rem`,r.style.textDecoration=`underline`,r.style.backgroundColor=`var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))`,r.style.border=`1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))`,r.style.color=`inherit`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ds=()=>{let e=document.createElement(`div`);e.className=`persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2`;let t=document.createElement(`div`);t.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,t.style.backgroundColor=`currentColor`,t.style.opacity=`0.4`,t.style.animationDelay=`0ms`;let n=document.createElement(`div`);n.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,n.style.backgroundColor=`currentColor`,n.style.opacity=`0.4`,n.style.animationDelay=`250ms`;let r=document.createElement(`div`);r.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,r.style.backgroundColor=`currentColor`,r.style.opacity=`0.4`,r.style.animationDelay=`500ms`;let i=document.createElement(`span`);return i.className=`persona-sr-only`,i.textContent=`Loading`,e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e},fs=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:ds};if(t){let e=t(r);if(e!==null)return e}return ds()},ps=(e,t)=>{let n=M(`div`,`persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm`),r=t===`user`?e.userAvatar:e.assistantAvatar;if(r){if(r.startsWith(`http`)||r.startsWith(`/`)||r.startsWith(`data:`)){let e=M(`img`);e.src=r,e.alt=t===`user`?`User`:`Assistant`,e.className=`persona-w-full persona-h-full persona-rounded-full persona-object-cover`,n.appendChild(e)}else n.textContent=r,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`)}else n.textContent=t===`user`?`U`:`A`,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`);return n},ms=(e,t,n=`div`)=>{let r=M(n,`persona-text-xs persona-text-persona-muted`),i=new Date(e.createdAt);return r.textContent=t.format?t.format(i):i.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),r},hs=(e,t=`bubble`)=>{let n=[`persona-message-bubble`];switch(t){case`flat`:e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-text-persona-primary`,`persona-py-2`):n.push(`persona-message-assistant-bubble`,`persona-text-persona-text`,`persona-py-2`);break;case`minimal`:n.push(`persona-text-sm`,`persona-leading-relaxed`),e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-bg-persona-accent`,`persona-text-white`,`persona-px-3`,`persona-py-2`,`persona-rounded-lg`):n.push(`persona-message-assistant-bubble`,`persona-bg-persona-container`,`persona-text-persona-text`,`persona-px-3`,`persona-py-2`,`persona-rounded-lg`);break;default:n.push(`persona-rounded-2xl`,`persona-text-sm`,`persona-leading-relaxed`,`persona-shadow-sm`),e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-bg-persona-accent`,`persona-text-white`,`persona-px-5`,`persona-py-3`):n.push(`persona-message-assistant-bubble`,`persona-bg-persona-container`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-text`,`persona-px-5`,`persona-py-3`)}return n},gs={bubble:{padding:`0.75rem 1.25rem`,fontSize:`0.875rem`,lineHeight:`1.75`},minimal:{padding:`0.5rem 0.75rem`,fontSize:`0.875rem`,lineHeight:`1.75`},flat:{padding:`0.5rem 0`,fontSize:`inherit`,lineHeight:`inherit`}},_s=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=gs[n??`bubble`]??gs.bubble;r.padding&&(e.style.padding=`var(--persona-message-${i}-padding, ${a.padding})`),r.fontSize&&(e.style.fontSize=`var(--persona-message-${i}-font-size, ${a.fontSize})`),r.lineHeight&&(e.style.lineHeight=`var(--persona-message-${i}-line-height, ${a.lineHeight})`),r.fontFamily&&(e.style.fontFamily=`var(--persona-message-${i}-font-family, inherit)`)},vs=e=>`custom:${e}`,ys=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),bs=(e,t,n,r)=>{let i=t.showCopy??!0,a=t.showUpvote??!1,o=t.showDownvote??!1,s=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&r?.canRegenerate===!0,l=(t.showEdit??!1)&&r?.canEdit===!0,u=(t.showQuote??!1)&&r?.canQuote!==!1,d=ys(t,e.role);if(!i&&!a&&!o&&!s&&!c&&!l&&!u&&d.length===0){let t=M(`div`);return t.style.display=`none`,t.id=`actions-${e.id}`,t.setAttribute(`data-actions-for`,e.id),t}let f=t.visibility??`hover`,p=t.align??`right`,m=t.layout??`pill-inside`,h={left:`persona-message-actions-left`,center:`persona-message-actions-center`,right:`persona-message-actions-right`}[p],g={"pill-inside":`persona-message-actions-pill`,"row-inside":`persona-message-actions-row`}[m],_=M(`div`,`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${h} ${g} ${f===`hover`?`persona-message-actions-hover`:``}`);_.id=`actions-${e.id}`,_.setAttribute(`data-actions-for`,e.id);let v=(e,t,n)=>{let r=ze({icon:e,label:t,size:14,className:`persona-message-action-btn`,chromeless:!0});return r.setAttribute(`data-action`,n),r};i&&_.appendChild(v(`copy`,`Copy message`,`copy`)),s&&_.appendChild(v(`volume-2`,`Read aloud`,`read-aloud`)),a&&_.appendChild(v(`thumbs-up`,`Upvote`,`upvote`)),o&&_.appendChild(v(`thumbs-down`,`Downvote`,`downvote`)),c&&_.appendChild(v(`refresh-cw`,`Regenerate response`,`regenerate`)),l&&_.appendChild(v(`pencil`,`Edit message`,`edit`)),u&&_.appendChild(v(`quote`,`Quote message`,`quote`));for(let e of d)_.appendChild(v(e.iconName??`ellipsis`,e.label,vs(e.id)));return _},xs=(e,t,n,r,i,a)=>{let o=n??{},s=o.layout??`bubble`,c=o.avatar,l=o.timestamp,u=c?.show??!1,d=l?.show??!1,f=c?.position??`left`,p=l?.position??`below`,m=hs(e.role,s),h=M(`div`,m.join(` `));h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.setAttribute(`data-persona-theme-zone`,e.role===`user`?`user-message`:`assistant-message`);let g=Sa(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;_s(h,e.role,s,e.role===`user`?{...g.user,..._?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...g.assistant,..._?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),s===`flat`?(h.style.backgroundColor=`transparent`,h.style.color=e.role===`user`?`var(--persona-primary, var(--persona-text))`:`var(--persona-message-assistant-text, var(--persona-text))`):e.role===`user`?(h.style.backgroundColor=`var(--persona-message-user-bg, var(--persona-accent))`,h.style.color=`var(--persona-message-user-text, white)`):e.role===`assistant`&&(h.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,h.style.color=`var(--persona-message-assistant-text, var(--persona-text))`);let v=es(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=Bt(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?Ht(x.type,S):null,w=e.role===`assistant`&&C?.isAnimating?.(e)===!0,T=e.role===`assistant`&&C!==null&&(!!e.streaming||w);T&&C?.bubbleClass&&h.classList.add(C.bubbleClass);let E=document.createElement(`div`);E.classList.add(`persona-message-content`),e.streaming&&E.classList.add(`persona-content-streaming`),T&&C&&(C.containerClass&&E.classList.add(C.containerClass),E.style.setProperty(`--persona-stream-step`,`${x.speed}ms`),E.style.setProperty(`--persona-stream-duration`,`${x.duration}ms`));let D=T?Ut(e.content??``,x.buffer,C,e,!!e.streaming):e.content??``,ee=()=>{let n=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent});return T&&C?.wrap===`char`?Jt(n,`char`,e.id,{skipTags:C.skipTags}):T&&C?.wrap===`word`?Jt(n,`word`,e.id,{skipTags:C.skipTags}):n},te=null;if(b?(te=document.createElement(`div`),te.innerHTML=ee(),te.style.display=`none`,E.appendChild(te)):e.contentSegments?.length?os(E,e.contentSegments,n=>t({text:n,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=ee(),T&&C?.useCaret&&!b&&y){let e=Vt(),t=E.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];if(n?.parentNode)n.parentNode.insertBefore(e,n.nextSibling);else{let t=E.lastElementChild;t?t.appendChild(e):E.appendChild(e)}}if(d&&p===`inline`&&e.createdAt){let t=ms(e,l,`span`);t.classList.add(`persona-timestamp-inline`);let n=E.lastElementChild;n?n.appendChild(t):E.appendChild(t)}if(v.length>0){let e=ss(v,!b&&!!y,()=>{b&&te&&(te.style.display=``)});e?h.appendChild(e):b&&te&&(te.style.display=``)}let ne=ts(e);if(ne.length>0){let e=cs(ne);e&&h.appendChild(e)}let re=ns(e);if(re.length>0){let e=ls(re);e&&h.appendChild(e)}let ie=rs(e);if(ie.length>0){let e=us(ie);e&&h.appendChild(e)}let ae=e.contentSegments?.length?null:is(e.contextMentions);if(ae&&h.appendChild(ae),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=ms(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let oe=e.role===`assistant`?Zo(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role===`assistant`){let e=!!(D&&D.trim()),t=x.placeholder===`skeleton`,n=t&&x.buffer===`line`&&e;if(e)n&&h.appendChild(Gt());else if(t)h.appendChild(Gt());else{let e=fs(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}oe&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild(Qo(e.stopReason,oe)));let se=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,O=a?.actionEligibility,ce=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&O?.canEdit===!0||r?.showQuote===!0&&O?.canQuote===!0||ys(r,`user`).length>0);if((se||ce)&&r){let t=bs(e,ce?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,O);h.appendChild(t)}if(!u||e.role===`system`)return h;let le=M(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),ue=ps(c,e.role);return f===`right`||f===`left`&&e.role===`user`?le.append(h,ue):le.append(ue,h),le},Ss=(e,t)=>{if(e.replaceChildren(),!t)e.hidden=!0;else if(typeof t==`function`){let n=null;try{n=t()}catch(e){console.warn(`[persona] welcome.icon renderer threw`,e)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1}else{if(t.type===`lucide`){let n=N(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(j(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(j(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},Cs=(e,t,n={})=>{let r=j(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=M(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=M(`h2`,`persona-welcome-title`),o=M(`p`,`persona-welcome-subtitle`),s=j(`div`,{className:`persona-welcome-head-text`},i,a),c=j(`div`,{className:`persona-welcome-title-row`},r,s);return{host:j(`div`,{className:`persona-welcome persona-rounded-2xl`,attrs:{"data-persona-welcome":``,"data-persona-intro-card":``,"data-persona-welcome-variant":`card`},style:{background:`var(--persona-intro-card-bg, transparent)`,boxShadow:n.flatShadow?`none`:`var(--persona-intro-card-shadow, none)`,border:`var(--persona-intro-card-border, none)`}},c,o,t),iconHolder:r,kicker:i,title:a,subtitle:o,starterSuggestions:t}},ws=(e,t,n)=>{t.hidden=!n,t.style.display=n?``:`none`,e.classList.toggle(`persona-gap-6`,n),e.classList.toggle(`persona-gap-3`,!n)},Ts=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??``,e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle===``,Ss(e.iconHolder,t.icon),e.host.setAttribute(`data-persona-welcome-variant`,t.variant),e.host.setAttribute(`data-persona-welcome-dismiss`,t.dismiss),e.host.setAttribute(`data-persona-welcome-layout`,t.layout??`top`),e.host.setAttribute(`data-persona-welcome-anchor`,t.anchor??`bottom`),t.iconPlacement===`inline`?e.host.setAttribute(`data-persona-welcome-icon-placement`,`inline`):e.host.removeAttribute(`data-persona-welcome-icon-placement`),t.align?e.host.setAttribute(`data-persona-welcome-align`,t.align):e.host.removeAttribute(`data-persona-welcome-align`)},Es=`data-persona-welcome-overlay`,Ds=`persona-welcome-overlay-active`,Os=/* @__PURE__ */ new WeakMap,ks=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(Es,``),e.classList.contains(Ds)||(Os.set(e,e.scrollTop),e.classList.add(Ds),e.scrollTop=0)},As=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(Es),e.classList.contains(Ds)&&(e.classList.remove(Ds),e.scrollTop=Os.get(e)??e.scrollTop,Os.delete(e))},js=()=>{let e=j(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},Ms=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=j(`div`,{className:hs(`assistant`,r).join(` `),attrs:{"data-persona-theme-zone":`assistant-message`},text:t,style:r===`flat`?{backgroundColor:`transparent`,color:`var(--persona-message-assistant-text, var(--persona-text))`}:{backgroundColor:`var(--persona-message-assistant-bg, var(--persona-container))`,color:`var(--persona-message-assistant-text, var(--persona-text))`}});e.appendChild(j(`div`,{className:`persona-flex`},i)),e.hidden=!1},Ns=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Ps=(e,t)=>{if(Ns()||typeof e.animate!=`function`||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),r=e.parentElement,i=0,a=0,o=0;if(r){let t=getComputedStyle(r);i=parseFloat(t.rowGap)||0;let s=e.previousElementSibling,c=e.nextElementSibling,l=r.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-r.scrollTop;a=Math.max(0,s?n.top-s.getBoundingClientRect().bottom-i:n.top-l),o=Math.max(0,c?c.getBoundingClientRect().top-n.bottom-i:0)}let s=e.style.overflow;e.style.overflow=`hidden`;let c=getComputedStyle(e),l=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,d=e.animate([{opacity:`1`,transform:`none`,height:`${n.height}px`,minHeight:`0px`,paddingTop:`${l}px`,paddingBottom:`${u}px`,marginTop:`${a}px`,marginBottom:`${o}px`},{opacity:`0`,transform:`translateY(-4px)`,height:`0px`,minHeight:`0px`,paddingTop:`0px`,paddingBottom:`0px`,marginTop:`0px`,marginBottom:`${-i}px`}],{duration:180,easing:`ease-out`,fill:`forwards`}),f=!1,p=()=>{f||(f=!0,e.style.overflow=s,t(d))};return d.finished.then(p).catch(p),d},Fs=(e,t,n,r=260)=>{if(t<=1||Ns()||typeof e.animate!=`function`||!e.isConnected)return null;let i=n===`drop`?-t:t;return e.animate([{transform:`translateY(${i}px)`},{transform:`none`}],{duration:r,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`none`})},Is=/* @__PURE__ */ new WeakSet,Ls=(e,t)=>!!e&&e[t]!==void 0,Rs=(e,t)=>{e&&e.debug===!0&&t.length&&(Is.has(e)||(Is.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},zs=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!==`docked`)=>{let n=e?.welcome,r=e?.copy,i=e?.future?.v5Defaults===!0,a=n?.layout??(i?`centered`:`top`),o=Ls(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:Ls(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];Ls(n,`title`)&&Ls(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),Ls(n,`subtitle`)&&Ls(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),Ls(n,`variant`)&&Ls(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&Ls(n,`message`)&&c.push(`welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.`),!i&&n?.layout===void 0&&o===`hero`&&Ls(n,`dismiss`)&&n.dismiss!==`on-first-message`&&c.push(`welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".`);let l=n?.anchor??(a===`centered`&&t?`center`:`bottom`),u=to(n?.anchorComposerTop)!==null;return Ls(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(Ls(n,`anchorComposerTop`)||Ls(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),Rs(e,c),{title:Ls(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:Ls(n,`subtitle`)?n.subtitle:r?.welcomeSubtitle??(i?``:`I can answer questions and help you get things done here.`),icon:n?.icon,align:n?.align===`start`||n?.align===`center`?n.align:a===`centered`?`center`:void 0,iconPlacement:n?.icon&&typeof n.icon!=`function`&&n.icon.placement===`inline`?`inline`:`above`,variant:o,dismiss:s,message:o===`hero`?void 0:n?.message,layout:a,anchor:l,anchorComposerTop:u?n.anchorComposerTop:`44%`,composerGap:n?.composerGap?.trim()||`24px`}},Bs=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,Vs=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`),Hs=`var(--persona-components-panel-height)`,Us=e=>{let t=D(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,r=e?.launcher?.heightOffset??0,i=r===0?`max(200px, ${Hs})`:`max(200px, calc(${Hs} - ${r}px))`;return{width:n??`var(--persona-components-panel-width)`,maxWidth:n??`var(--persona-components-panel-maxWidth)`,height:i,maxHeight:`var(--persona-components-panel-maxHeight)`}},Ws=`16px`,Gs=`10px`,Ks=`14px`,qs=e=>{let t=e?.launcher?.enabled??!0,n=xo(e);if(So(e)){let t=e?.launcher?.composerBar??{},n=M(`div`,`persona-widget-wrapper persona-fixed persona-transition`);n.setAttribute(`data-persona-composer-bar`,``),n.dataset.state=`collapsed`,n.dataset.expandedSize=t.expandedSize??`anchored`,n.style.zIndex=String(e?.launcher?.zIndex??1e5);let r=M(`div`,`persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);r.style.width=`100%`,n.appendChild(r);let i=M(`div`,`persona-widget-pill-root`);return i.setAttribute(`data-persona-composer-bar`,``),i.dataset.state=`collapsed`,i.dataset.expandedSize=t.expandedSize??`anchored`,i.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:n,panel:r,pillRoot:i}}if(n){let e=M(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=M(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=M(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=M(`div`,`persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0`),r=D(e),i=r.launcherWidth||r.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Us(e).width:`100%`;return t.style.width=i,n.style.width=`100%`,t.appendChild(n),{wrapper:t,panel:n}}let r=e?.launcher??{},i=r.position&&jo[r.position]?jo[r.position]:jo[`bottom-right`],a=M(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=M(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),s=Us(e);return o.style.width=s.width,o.style.maxWidth=s.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},Js=e=>{let t=j(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":wo(e)}});return t.hidden=!0,t},Ys=(e,t)=>{let n=Js(`starter`),r=Cs(e,n,{flatShadow:xo(e)}),i=zs(e);Ts(r,i),ws(t,r.host,Vs(i,e?.initialMessages));let a=js();return Ms(a,i.message,e),{welcome:r,greetingHost:a}},Xs=(e,t)=>{let n=M(`div`,`persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary`);n.setAttribute(`data-persona-theme-zone`,`container`);let{button:r,wrapper:i}=Fo(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:Ws,iconSize:Gs});i.style.position=`absolute`,i.style.top=`8px`,i.style.right=`8px`,i.style.zIndex=`10`;let a=e?.launcher?.clearChat?.enabled??!0,o=null,s=null;if(a){let t=Io(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:Ws,iconSize:Ks});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=j(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=j(`div`,{className:`persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6`,attrs:{id:`persona-scroll-container`,"data-persona-theme-zone":`messages`},style:{paddingTop:`48px`}});l.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:u,greetingHost:d}=Ys(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=M(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=Js(`followUp`),v=$a(e,!0);v&&(g.style.maxWidth=v,g.style.marginLeft=`auto`,g.style.marginRight=`auto`,g.style.width=`100%`),l.append(f,d,g,_);let y=j(`div`,{className:`persona-composer-overlay persona-pointer-events-none`,attrs:{"data-persona-composer-overlay":``},style:{position:`absolute`,left:`0`,right:`0`,bottom:`calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))`,zIndex:`20`}}),b=Yo({config:e}),{root:x,textNode:S}=Jo();return n.append(c,i,l,y),s&&n.appendChild(s),{container:n,body:l,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:_,composerOverlay:y,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:f,welcomeIconHolder:u.iconHolder,greetingHost:d,introKicker:u.kicker,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:i,clearChatButton:o,clearChatButtonWrapper:s,iconHolder:M(`span`),headerTitle:M(`span`),headerSubtitle:M(`span`),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:x,peekTextNode:S}},Zs=(e,t=!0)=>{if(So(e))return Xs(e,t);let n=j(`div`,{className:`persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border`,attrs:{"data-persona-theme-zone":`container`}}),r=e?.layout?.header,i=e?.layout?.showHeader!==!1,a=r?Ko(e,r,{showClose:t}):Bo({config:e,showClose:t}),o=j(`div`,{className:`persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6`,attrs:{id:`persona-scroll-container`,"data-persona-theme-zone":`messages`}});o.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:s,greetingHost:c}=Ys(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=M(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=Js(`followUp`),h=$a(e,!1);h&&(p.style.maxWidth=h,p.style.marginLeft=`auto`,p.style.marginRight=`auto`,p.style.width=`100%`),o.append(l,c,p,m);let g=qo({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),Vo(n,a,e),n.append(o);let v=j(`div`,{className:`persona-composer-overlay persona-pointer-events-none`,attrs:{"data-persona-composer-overlay":``},style:{position:`absolute`,left:`0`,right:`0`,bottom:`calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))`,zIndex:`20`}});return _||(g.footer.style.display=`none`),n.append(g.footer),n.append(v),{container:n,body:o,messagesWrapper:p,starterSuggestions:f,transcriptSuggestions:m,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,welcomeHost:l,welcomeIconHolder:s.iconHolder,greetingHost:c,introKicker:s.kicker,introTitle:u,introSubtitle:d,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}},Qs=(e,t)=>{let n=M(`button`);n.type=`button`,n.innerHTML=`
|
|
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{_ 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 a
|
|
|
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:a.codeBlockTextColor??a.contentTextColor}}),l=
|
|
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
23
|
`);let a=i(n.args).trim();return a?a.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
-
`):``},bc=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??`var(--persona-container, #f3f4f6)`,e.style.borderColor=t.codeBlockBorderColor??`var(--persona-border, #e5e7eb)`,e.style.color=t.codeBlockTextColor??`var(--persona-text, #171717)`},xc=(e,t)=>{let n=e.toolCall,i=t?.features?.toolCallDisplay,a=i?.collapsedMode??ee.collapsedMode,o=n?.success===!1?n.error||`Tool failed`:yc(e,i?.previewMaxLines??ee.previewMaxLines),s=n?.interrupted?`${n.name?.trim()||`Tool`} · Interrupted`:n?yn(t,`tool`)===`row`?`${n.status===`complete`?`Used`:`Using`} ${n.name?.trim()||`tool`}`:r(n):``;if(!n)return{summary:s,previewText:o,isActive:!1};let l=n.status!==`complete`,u=t?.toolCall??{},d=s;return a===`tool-name`?d=n.name?.trim()||s:a===`tool-preview`&&o&&(d=o),l&&u.activeTextTemplate?d=c(n,u.activeTextTemplate,d):!l&&!n.interrupted&&u.completeTextTemplate&&(d=c(n,u.completeTextTemplate,d)),n.interrupted?d.includes(` · Interrupted`)||(d+=` · Interrupted`):n.success===!1?d+=` · Failed`:n.superseded&&(d+=` · Approved, ran again below`),{summary:d,previewText:o,isActive:l}},Sc=(e,t,n,r)=>{L(e,t,{stateSet:n,previewKind:`tool`,iconColor:vc(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},Cc=(e,t,n=/* @__PURE__ */ new Set)=>{t=vn(t,`tool`);let r=e.toolCall,a=t?.toolCall??{},o=pn(`persona-tool-bubble`,e.id);if(a.backgroundColor&&(o.style.backgroundColor=a.backgroundColor),a.borderColor&&(o.style.borderColor=a.borderColor),a.borderWidth&&(o.style.borderWidth=a.borderWidth),a.borderRadius&&(o.style.borderRadius=a.borderRadius),o.style.boxShadow=a.shadow===void 0?`var(--persona-tool-bubble-shadow)`:a.shadow.trim()===``?`none`:a.shadow,!r)return R(o,e,t,`tool`);let s=t?.features?.toolCallDisplay??{},c=s.expandable??ee.expandable,u=c&&n.has(e.id),{summary:f,previewText:p,isActive:m}=xc(e,t),h=mn({expandable:c,expanded:u,bubbleType:`tool`});a.headerBackgroundColor&&(h.style.backgroundColor=a.headerBackgroundColor),a.headerPaddingX&&(h.style.paddingLeft=a.headerPaddingX,h.style.paddingRight=a.headerPaddingX),a.headerPaddingY&&(h.style.paddingTop=a.headerPaddingY,h.style.paddingBottom=a.headerPaddingY);let g=M(`div`,`persona-flex persona-flex-col persona-text-left`),_=M(`span`,`persona-text-xs persona-text-persona-primary`);a.headerTextColor&&(_.style.color=a.headerTextColor);let v=String(r.startedAt??Date.now()),y=()=>{let e=M(`span`,``);return m&&e.setAttribute(`data-tool-elapsed`,v),e.textContent=l(r),e},b=a.renderCollapsedSummary?.({message:e,toolCall:r,defaultSummary:f,previewText:p,collapsedMode:s.collapsedMode??ee.collapsedMode,isActive:m,config:t??{},elapsed:l(r),createElapsedElement:y});typeof b==`string`&&b.trim()?(_.textContent=b,g.appendChild(_)):b instanceof HTMLElement?g.appendChild(b):(_.textContent=f,g.appendChild(_));let x=s.loadingAnimation??ee.loadingAnimation,S=a.activeTextTemplate,C=r.interrupted?void 0:a.completeTextTemplate,w=m?S:C,T=b instanceof HTMLElement,E=(e,t)=>{_.textContent=``;let n=r.name?.trim()||`tool`,i=d(e,n),a=0;for(let e of i){let n=e.styles.length>0?(()=>{let t=M(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return _.appendChild(t),t})():_;if(e.isDuration&&m)n.appendChild(y());else{let i=e.isDuration?l(r):e.text;t?a=He(n,i,a):n.appendChild(document.createTextNode(i))}}};if(!T){if(m&&x!==`none`){let e=a.loadingAnimationDuration??2e3;if(_.setAttribute(`data-preserve-animation`,`true`),x===`pulse`)_.classList.add(`persona-tool-loading-pulse`),_.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),w&&E(w,!1);else if(_.classList.add(`persona-tool-loading-${x}`),_.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),x===`shimmer-color`&&(a.loadingAnimationColor&&_.style.setProperty(`--persona-tool-anim-color`,a.loadingAnimationColor),a.loadingAnimationSecondaryColor&&_.style.setProperty(`--persona-tool-anim-secondary-color`,a.loadingAnimationSecondaryColor)),w)E(w,!0);else{let e=_.textContent||f;_.textContent=``,He(_,e,0)}}else w&&E(w,!1)}let D=vc(a,yn(t,`tool`)===`row`),te=gn(h,g,{expandable:c,expanded:u,iconColor:D,metaGap:!0}),ne=_n({bubble:o,previewKind:`tool`,expanded:u,isActive:m,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>a.renderCollapsedPreview?.({message:e,toolCall:r,defaultPreview:p,isActive:m,config:t??{}})});if(!c)return o.append(h,ne),R(o,e,t,`tool`);let re=M(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);if(re.style.display=u?``:`none`,a.contentBackgroundColor&&(re.style.backgroundColor=a.contentBackgroundColor),a.contentTextColor&&(re.style.color=a.contentTextColor),a.contentPaddingX&&(re.style.paddingLeft=a.contentPaddingX,re.style.paddingRight=a.contentPaddingX),a.contentPaddingY&&(re.style.paddingTop=a.contentPaddingY,re.style.paddingBottom=a.contentPaddingY),t.future?.v5Defaults===!0)hc(re,e,t);else{if(r.name){let e=M(`div`,`persona-text-xs persona-text-persona-muted persona-italic`);a.contentTextColor?e.style.color=a.contentTextColor:a.headerTextColor&&(e.style.color=a.headerTextColor),e.textContent=r.name,re.appendChild(e)}if(r.args!==void 0){let e=M(`div`,`persona-space-y-1`),t=M(`div`,`persona-text-xs persona-text-persona-muted`);a.labelTextColor&&(t.style.color=a.labelTextColor),t.textContent=`Arguments`;let n=M(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,bc(n,a),n.textContent=i(r.args),e.append(t,n),re.appendChild(e)}if(r.chunks&&r.chunks.length){let e=M(`div`,`persona-space-y-1`),t=M(`div`,`persona-text-xs persona-text-persona-muted`);a.labelTextColor&&(t.style.color=a.labelTextColor),t.textContent=`Activity`;let n=M(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,bc(n,a),n.textContent=r.chunks.join(``),e.append(t,n),re.appendChild(e)}if(r.success===!1&&re.appendChild(j(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``}})),r.status===`complete`&&r.result!==void 0){let e=M(`div`,`persona-space-y-1`),t=M(`div`,`persona-text-xs persona-text-persona-muted`);a.labelTextColor&&(t.style.color=a.labelTextColor),t.textContent=`Result`;let n=M(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,bc(n,a),n.textContent=i(r.result),e.append(t,n),re.appendChild(e)}if(r.status===`complete`&&typeof r.duration==`number`){let e=M(`div`,`persona-text-xs persona-text-persona-muted`);a.contentTextColor&&(e.style.color=a.contentTextColor),e.textContent=`Duration: ${r.duration}ms`,re.appendChild(e)}}return I({expanded:u,header:h,toggleIcon:te,content:re,collapsedPreview:ne,iconColor:D}),o.append(h,ne,re),R(o,e,t,`tool`)},{setLoader:wc,load:Tc,provide:Ec,getSync:Dc}=Ne({fallbackImport:()=>import(`./chunk-Bm2-bemv.js`)}),Oc=Tc,kc=Dc,{setLoader:Ac,load:jc}=Ne({fallbackImport:()=>import(`./chunk-DvqveR1q.js`)}),Mc=jc,Nc=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:Pc,load:Fc,provide:Ic,getSync:Lc}=Ne({fallbackImport:()=>import(`./chunk-Do_1TKAR.js`)});let Rc=null;const zc=/* @__PURE__ */ new Set,Bc=e=>{if(Rc)return Rc;Rc=e,e.initArtifactsUi({componentRegistry:Ge});for(let t of Nc)Ge.has(t)||Ge.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Re();t?e.__provideMarkdownParsers(t):Ve(()=>{let t=Re();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>Pe());let n=[...zc];zc.clear();for(let e of n)try{e()}catch{}return e},Vc=()=>Fc().then(Bc),Hc=()=>{if(Rc)return Rc;let e=Lc();return e?Bc(e):null},Uc=e=>Rc?()=>{}:(zc.add(e),()=>{zc.delete(e)});function Wc(e){return e?.features?.artifacts?.enabled===!0}function Gc(e,t){if(e.classList.remove(`persona-artifact-border-full`,`persona-artifact-border-left`),e.style.removeProperty(`--persona-artifact-pane-border`),e.style.removeProperty(`--persona-artifact-pane-border-left`),!Wc(t))return;let n=t.features?.artifacts?.layout,r=n?.paneBorder?.trim(),i=n?.paneBorderLeft?.trim();r?(e.classList.add(`persona-artifact-border-full`),e.style.setProperty(`--persona-artifact-pane-border`,r)):i&&(e.classList.add(`persona-artifact-border-left`),e.style.setProperty(`--persona-artifact-pane-border-left`,i))}function Kc(e){e.style.removeProperty(`--persona-artifact-doc-toolbar-icon-color`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-bg`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-border`)}const qc=[`panel`,`seamless`,`detached`];function Jc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&qc.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function Yc(e){return!e||!Wc(e)?!1:Jc(e)===`detached`}function Xc(e,t){if(!Wc(t)){e.style.removeProperty(`--persona-artifact-split-gap`),e.style.removeProperty(`--persona-artifact-pane-width`),e.style.removeProperty(`--persona-artifact-pane-max-width`),e.style.removeProperty(`--persona-artifact-pane-min-width`),e.style.removeProperty(`--persona-artifact-drawer-width`),e.style.removeProperty(`--persona-artifact-pane-bg`),e.style.removeProperty(`--persona-artifact-pane-padding`),Kc(e),Gc(e,t);return}let n=t.features?.artifacts?.layout,r=Jc(t)===`detached`?`var(--persona-panel-inset)`:`0`;e.style.setProperty(`--persona-artifact-split-gap`,n?.splitGap??r),e.style.setProperty(`--persona-artifact-pane-width`,n?.paneWidth??`40%`),e.style.setProperty(`--persona-artifact-pane-max-width`,n?.paneMaxWidth??`28rem`),n?.drawerWidth?e.style.setProperty(`--persona-artifact-drawer-width`,n.drawerWidth):e.style.removeProperty(`--persona-artifact-drawer-width`),n?.paneMinWidth?e.style.setProperty(`--persona-artifact-pane-min-width`,n.paneMinWidth):e.style.removeProperty(`--persona-artifact-pane-min-width`);let i=n?.paneBackground?.trim();i?e.style.setProperty(`--persona-artifact-pane-bg`,i):e.style.removeProperty(`--persona-artifact-pane-bg`);let a=n?.panePadding?.trim();a?e.style.setProperty(`--persona-artifact-pane-padding`,a):e.style.removeProperty(`--persona-artifact-pane-padding`);let o=[[n?.documentToolbarIconColor,`--persona-artifact-doc-toolbar-icon-color`],[n?.documentToolbarToggleActiveBackground,`--persona-artifact-doc-toggle-active-bg`],[n?.documentToolbarToggleActiveBorderColor,`--persona-artifact-doc-toggle-active-border`],[n?.documentToolbarToggleActiveColor,`--persona-artifact-doc-toggle-active-color`]];for(let[t,n]of o){let r=t?.trim();r?e.style.setProperty(n,r):e.style.removeProperty(n)}Gc(e,t)}function Zc(e,t){for(let t of qc)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty(`--persona-artifact-pane-radius`),e.style.removeProperty(`--persona-artifact-pane-shadow`),e.style.removeProperty(`--persona-artifact-chat-shadow`),!Wc(t))return;let n=t.features?.artifacts?.layout,r=Jc(t);e.classList.add(`persona-artifact-appearance-${r}`);let i=n?.paneBorderRadius?.trim();i&&e.style.setProperty(`--persona-artifact-pane-radius`,i);let a=n?.paneShadow?.trim();a&&e.style.setProperty(`--persona-artifact-pane-shadow`,a);let o=n?.chatShadow?.trim();o&&e.style.setProperty(`--persona-artifact-chat-shadow`,o)}function Qc(e,t){return!t||!Wc(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}const $c=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),el=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),tl=/* @__PURE__ */ new Set([`markdown`,`component`]),nl=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,rl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),il=e=>!$c.has(e),al=e=>typeof e==`string`&&el.has(e),ol=e=>Object.keys(e).length>0;function sl(e,t,n,r){e.push({path:t,code:n,message:r})}const cl=`Ignored an unsupported value.`,ll={kind:`mode`,message:cl},ul={kind:`string`,message:`Expected a CSS length string.`},dl={kind:`boolean`},fl={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:dl,showReasoning:dl,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:cl},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:cl},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:cl},expandable:dl,grouped:dl}},reasoningDisplay:{kind:`object`,children:{expandable:dl,activePreview:dl}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:ll,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:ll,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:tl,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:tl}}},filePreview:{kind:`object`,children:{enabled:dl}},layout:{kind:`object`,children:{paneWidth:ul,paneMaxWidth:ul,paneMinWidth:ul,expandedPanelWidth:ul,resizableMinWidth:ul,resizableMaxWidth:ul,expandLauncherPanelWhenOpen:dl,resizable:dl}}}}}};function pl(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:sl(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:sl(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:sl(r,n,`invalid_value`,t.message);case`mode`:return al(e)?it(e):sl(r,n,`invalid_value`,t.message);case`modeMap`:{if(!rl(e))return sl(r,n,`invalid_type`,`Expected an object.`);let i=t.keys===`mediaType`?void 0:t.keys,a={};for(let[t,o]of Object.entries(e)){let e=i?t:F(t);il(t)&&(i?i.has(t):nl.test(e))?al(o)?a[e]=it(o):sl(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):sl(r,`${n}.${t}`,i?`unknown_key`:`invalid_value`,i?`Ignored an unsupported selector.`:`Expected a MIME type such as "text/html" or a wildcard such as "image/*".`)}return ol(a)?a:void 0}case`object`:{if(t.bareMode&&al(e))return it(e);if(!rl(e))return sl(r,n,`invalid_type`,t.message??`Expected an object.`);let i=Object.keys(t.children),a=e=>n?`${n}.${e}`:e;for(let t of Object.keys(e))(!il(t)||!i.includes(t))&&sl(r,a(t),`unknown_key`,`Ignored because this key is not part of the persisted preference schema.`);let o={};for(let n of i){let i=t.children[n],s=pl(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&sl(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=rl(l)&&rl(s)?{...l,...s}:s}return ol(o)?o:void 0}}}function ml(e){let t=[];return{preferences:(e===null?void 0:pl(e,fl,``,t))??{},issues:t}}function hl(e){if(Array.isArray(e))return e.map(hl);if(!rl(e))return e;let t={};for(let[n,r]of Object.entries(e))il(n)&&r!==void 0&&(t[n]=hl(r));return t}function gl(e,t){let n=hl(e);for(let[e,r]of Object.entries(t)){if(!il(e)||r===void 0)continue;let t=n[e];n[e]=rl(t)&&rl(r)?gl(t,r):hl(r)}return n}function _l(e){let t={},n;for(let r of e){let e=ml(r).preferences;n=yl(n,e.artifacts?.display),t=gl(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function vl(e,t){if(t===void 0)return e===void 0?void 0:hl(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byMediaType,...t.byMediaType},a={...r?{default:r}:{},...ol(i)?{byMediaType:i}:{}};return ol(a)?a:void 0}function yl(e,t){if(t===void 0)return e===void 0?void 0:hl(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byType,...n.byKind,...t.byType,...t.byKind},a=vl(n.files,t.files),o={...r?{default:r}:{},...ol(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return ol(o)?o:void 0}function bl(e={},t){let n=_l(t),r={...e};if(n.showToolCalls!==void 0&&(r.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(r.showReasoning=n.showReasoning),n.toolCallDisplay&&(r.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(r.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let t=e.artifacts??{},i={...t};if(n.artifacts.display!==void 0){let e=yl(t.display,n.artifacts.display);e!==void 0&&(i.display=e)}n.artifacts.filePreview&&(i.filePreview={...t.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...t.layout,...n.artifacts.layout}),r.artifacts=i}return r}function xl(e){let t=e.preferences;return!t||!ol(t)?e:{...e,features:bl(e.features??{},[t])}}function Sl(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Cl(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function wl(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Tl(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function El(e,t){let n=(t.getComputedStyle(e).gap||`0px`).trim().split(/\s+/)[0]??`0px`,r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(n);return i?Number(i[1]):8}function Dl(e,t,n,r,i,a,o=200){let s=Sl(i,200),c=Tl(t,n,r,o);c=Math.max(s,c);let l=Cl(a);return l!==null&&(c=Math.min(c,l)),wl(e,s,c)}const{setLoader:Ol,load:kl,provide:Al,getSync:jl}=Ne({fallbackImport:()=>import(`./chunk-Bp9uGcpc.js`)}),Ml=kl,Nl=jl,Pl=new class{#e=/* @__PURE__ */ new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},Fl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Il=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),Ll=(e,t,n)=>{if(!Fl(e)||!Fl(t)||Il.has(n))return t;let r={...e};for(let i of Object.keys(t)){if(t[i]===void 0){delete r[i];continue}let a=n?`${n}.${i}`:i;r[i]=Ll(e[i],t[i],a)}return r};function Rl(e,t){let n=se(ne),r=E(e,t,n),i=O(x(Ll(e,t,``),n,r),r);return ie(te(i),je(e,t))}const zl=()=>{let e=/* @__PURE__ */ new Map,t=(t,r)=>(e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(r),()=>n(t,r)),n=(t,n)=>{e.get(t)?.delete(n)};return{on:t,off:n,emit:(t,n)=>{e.get(t)?.forEach(e=>{try{e(n)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Event handler error:`,e)}})}}},Bl=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Vl=e=>{let t=e.trim(),n=t.indexOf(`{`);if(n===-1)return null;let r=0;for(let e=n;e<t.length;e+=1){let i=t[e];if(i===`{`&&(r+=1),i===`}`&&(--r,r===0))return t.slice(n,e+1)}return null},Hl=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=Bl(e),n=Vl(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!=`object`||!r.action)return null;let{action:i,...a}=r;return{type:String(i),payload:a,raw:r}}catch{return null}},Ul=e=>typeof e==`string`?e:e==null?``:String(e),Wl={message:e=>{if(e.type===`message`)return{handled:!0,displayText:Ul(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=Ul(n.element);if(r&&t.document?.querySelector){let e=t.document.querySelector(r);e?setTimeout(()=>{e.click()},400):typeof console<`u`&&console.warn(`[AgentWidget] Element not found for selector:`,r)}return{handled:!0,displayText:Ul(n.text)}}},Gl=e=>Array.isArray(e)?e.map(e=>String(e)):[],Kl=e=>{let t=new Set(Gl(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Gl(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let n=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!==`assistant`||!n.text||t.has(n.message.id))return null;let i=typeof n.raw==`string`&&n.raw||typeof n.message.rawContent==`string`&&n.message.rawContent||typeof n.text==`string`&&n.text||null;!i&&typeof n.text==`string`&&n.text.trim().startsWith(`{`)&&typeof console<`u`&&console.warn(`[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.`);let a=i?e.parsers.reduce((e,t)=>e||t?.({text:i,message:n.message})||null,null):null;if(!a)return null;t.add(n.message.id),r();let o={action:a,message:n.message};e.emit(`action:detected`,o);for(let t of e.handlers)if(t)try{let r=t(a,{message:n.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit(`action:resubmit`,o)}});if(!r)continue;if(r.handled){let e=r.persistMessage!==!1;return{text:r.displayText===void 0?``:r.displayText,persist:e,resubmit:r.resubmit}}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Action handler error:`,e)}return{text:``,persist:!0}},syncFromMetadata:n}},ql=e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] Failed to parse stored state:`,e),null}},Jl=e=>e.map(e=>({...e,streaming:!1})),Yl=e=>e.map(e=>({...e,status:`complete`})),Xl=e=>`${e??`persona-`}state`,Zl=(e=Xl())=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?ql(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?Jl(n.messages):void 0,artifacts:n.artifacts?Yl(n.artifacts):void 0};r.setItem(e,JSON.stringify(t))}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to persist state:`,e)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to clear stored state:`,e)}}}},Ql=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,`0`)},$l=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{}return Ql(e)},eu=async(e,t)=>{let n=await $l(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await $l(`${e}\0${t}`)}`}},tu=(e,t,n)=>{let r=``,i=``,a=``,o=!1,s=!1,c=0,l=null,u=null,d=/* @__PURE__ */ new Set,f=()=>{if(n||o)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return o=!0,null}},p=()=>{let e=f();if(!e)return l;try{return e.getItem(r)}catch{return o=!0,l}},m=(e,t)=>{if(s||e===l)return;let n=l;l=e,c+=1;let r={previousToken:n,token:e,source:t,revision:c};for(let e of d)e(r)},h=e=>{s||(e.key===null||e.key===r)&&m(e.key===null?null:e.newValue??null,`external`)},g=(async()=>{let o=await eu(e,t);r=o.storageKey,i=o.leaseKey,a=o.lockName,l=p(),!n&&typeof window<`u`&&window.addEventListener(`storage`,h)})(),_=e=>new Promise(t=>setTimeout(t,e)),v=()=>{let e=f();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let n=JSON.parse(t);return typeof n?.expiresAt==`number`&&typeof n?.ownerNonce==`string`?n:null}catch{return null}},y=e=>{let t=f();if(t)try{v()?.ownerNonce===e&&t.removeItem(i)}catch{}},b=/* @__PURE__ */ new Set,x=e=>s?Promise.reject(/* @__PURE__ */ Error(`Visitor store destroyed before its first init could start`)):e(),S=e=>new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),b.delete(r),window.removeEventListener(`storage`,a),t()}function a(e){(e.key===null||e.key===i)&&r()}b.add(r),window.addEventListener(`storage`,a)}),C=async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=Date.now()+15e3;for(;!s&&Date.now()<n;){let n=f();if(!n)break;let r=Date.now(),a=v();if(a&&a.expiresAt>r&&a.ownerNonce!==t)await S(Math.min(a.expiresAt-r,500));else{try{n.setItem(i,JSON.stringify({ownerNonce:t,expiresAt:r+1e4}))}catch{o=!0;break}if(await _(20+Math.random()*40),v()?.ownerNonce!==t)await S(500);else{u=t;try{return await x(e)}finally{u=null,y(t)}}}}return x(e)};return{ready:g,async get(){return await g,m(p(),`external`),l},async set(e){await g;let t=f();if(t)try{t.setItem(r,e)}catch{o=!0}m(e,`local`)},async clear(){await g;let e=f();if(e)try{e.removeItem(r)}catch{o=!0}m(null,`local`)},revision(){return c},subscribe(e){return d.add(e),()=>{d.delete(e)}},async withFirstInitLock(e){await g;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):f()?C(e):x(e)},matches(r,i,a){return r===e&&i===t&&a===n},destroy(){s=!0,d.clear(),typeof window<`u`&&window.removeEventListener(`storage`,h),u&&y(u);for(let e of[...b])e()}}},{setLoader:nu,load:ru}=Ne({fallbackImport:()=>import(`./chunk-Zom7XuVp.js`)}),iu=ru,{setLoader:au,load:ou,provide:su,getSync:cu}=Ne({fallbackImport:()=>import(`./chunk-Bvr_E4ga.js`)}),lu=ou,uu=cu;function du(){return null}function fu(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=Ge.get(e.component);if(!a){if(Nc.includes(e.component)){Vc().catch(()=>{});let e=M(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o={message:r,config:n,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function pu(e){if(typeof e.rawContent==`string`&&e.rawContent.length>0)return e.rawContent;if(typeof e.content==`string`){let t=e.content.trim();if(t.startsWith(`{`)||t.startsWith(`[`))return e.content}return null}function mu(e){let t=pu(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function hu(e){let t=pu(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}const gu=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function _u(e){let{onSubmit:t,onDismiss:n,title:r=`How satisfied are you?`,subtitle:i=`Please rate your experience`,commentPlaceholder:a=`Share your thoughts (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,ratingLabels:l=gu}=e,u=document.createElement(`div`);u.className=`persona-feedback-container persona-feedback-csat`,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-label`,`Customer satisfaction feedback`);let d=null,f=document.createElement(`div`);f.className=`persona-feedback-content`;let p=document.createElement(`div`);p.className=`persona-feedback-header`;let m=document.createElement(`h3`);m.className=`persona-feedback-title`,m.textContent=r,p.appendChild(m);let h=document.createElement(`p`);h.className=`persona-feedback-subtitle`,h.textContent=i,p.appendChild(h),f.appendChild(p);let g=document.createElement(`div`);g.className=`persona-feedback-rating persona-feedback-rating-csat`,g.setAttribute(`role`,`radiogroup`),g.setAttribute(`aria-label`,`Satisfaction rating from 1 to 5`);let _=[];for(let e=1;e<=5;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-star-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`${e} star${e>1?`s`:``}: ${l[e-1]}`),t.title=l[e-1],t.dataset.rating=String(e),t.innerHTML=`
|
|
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 vu(e){let{onSubmit:t,onDismiss:n,title:r=`How likely are you to recommend us?`,subtitle:i=`On a scale of 0 to 10`,commentPlaceholder:a=`What could we do better? (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,lowLabel:l=`Not likely`,highLabel:u=`Very likely`}=e,d=document.createElement(`div`);d.className=`persona-feedback-container persona-feedback-nps`,d.setAttribute(`role`,`dialog`),d.setAttribute(`aria-label`,`Net Promoter Score feedback`);let f=null,p=document.createElement(`div`);p.className=`persona-feedback-content`;let m=document.createElement(`div`);m.className=`persona-feedback-header`;let h=document.createElement(`h3`);h.className=`persona-feedback-title`,h.textContent=r,m.appendChild(h);let g=document.createElement(`p`);g.className=`persona-feedback-subtitle`,g.textContent=i,m.appendChild(g),p.appendChild(m);let _=document.createElement(`div`);_.className=`persona-feedback-rating persona-feedback-rating-nps`,_.setAttribute(`role`,`radiogroup`),_.setAttribute(`aria-label`,`Likelihood rating from 0 to 10`);let v=document.createElement(`div`);v.className=`persona-feedback-labels`;let y=document.createElement(`span`);y.className=`persona-feedback-label-low`,y.textContent=l;let b=document.createElement(`span`);b.className=`persona-feedback-label-high`,b.textContent=u,v.appendChild(y),v.appendChild(b);let x=document.createElement(`div`);x.className=`persona-feedback-numbers`;let S=[];for(let e=0;e<=10;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-number-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add(`persona-feedback-detractor`):e<=8?t.classList.add(`persona-feedback-passive`):t.classList.add(`persona-feedback-promoter`),t.addEventListener(`click`,()=>{f=e,S.forEach((t,n)=>{t.classList.toggle(`selected`,n===e),t.setAttribute(`aria-checked`,n===e?`true`:`false`)})}),S.push(t),x.appendChild(t)}_.appendChild(v),_.appendChild(x),p.appendChild(_);let C=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,C=document.createElement(`textarea`),C.className=`persona-feedback-comment`,C.placeholder=a,C.rows=3,C.setAttribute(`aria-label`,`Additional comments`),e.appendChild(C),p.appendChild(e)}let w=document.createElement(`div`);w.className=`persona-feedback-actions`;let T=document.createElement(`button`);T.type=`button`,T.className=`persona-feedback-btn persona-feedback-btn-skip`,T.textContent=s,T.addEventListener(`click`,()=>{n?.(),d.remove()});let E=document.createElement(`button`);return E.type=`button`,E.className=`persona-feedback-btn persona-feedback-btn-submit`,E.textContent=o,E.addEventListener(`click`,async()=>{if(f===null)x.classList.add(`persona-feedback-shake`),setTimeout(()=>x.classList.remove(`persona-feedback-shake`),500);else{E.disabled=!0,E.textContent=`Submitting...`;try{let e=C?.value.trim()||void 0;await t(f,e),d.remove()}catch(e){E.disabled=!1,E.textContent=o,console.error(`[NPS Feedback] Failed to submit:`,e)}}}),w.appendChild(T),w.appendChild(E),p.appendChild(w),d.appendChild(p),d}const yu=`persona-chat-history`,bu=`data-persona-composer-reason`,xu=`data-persona-composer-notice`,Su={"image/png":`png`,"image/jpeg":`jpg`,"image/jpg":`jpg`,"image/gif":`gif`,"image/webp":`webp`,"image/svg+xml":`svg`,"image/bmp":`bmp`,"image/tiff":`tiff`};function Cu(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let e of n){if(e.kind!==`file`||!e.type.startsWith(`image/`))continue;let n=e.getAsFile();if(!n)continue;if(n.name){t.push(n);continue}let r=Su[n.type]??`png`;t.push(new File([n],`clipboard-image-${Date.now()}.${r}`,{type:n.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith(`image/`)&&t.push(n);return t}function wu(e){if(!e)return!1;let t=e.types;return t?typeof t.contains==`function`?t.contains(`Files`):Array.from(t).includes(`Files`):!1}function Tu(e){return e?e===!0?{storage:`session`,keyPrefix:`persona-`,persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??`session`,keyPrefix:e.keyPrefix??`persona-`,persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function Eu(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const Du=e=>!e||typeof e!=`object`?{}:{...e},Ou=e=>e.filter(e=>!bt(e)).map(e=>({...e,streaming:!1})),ku=(e,t,n)=>{let r=e?.markdown?Ke(e.markdown):null,i=Be(e?.sanitize);e?.postprocessMessage&&i&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,o=a=>{let o=a.text??``,s=a.message.rawContent??null;if(t){let e=t.process({text:o,raw:s??o,message:a.message,streaming:a.streaming});e!==null&&(o=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&n&&n())}let c=Re()!==null,l;if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:o,raw:s??a.text??``});l=i?i(t):t}else if(r){let e=a.streaming?W(o):o,t=r(e);l=i&&c?i(t):t}else l=Le(o);return l};return e=>{try{return o(e)}catch(t){return a||(a=!0,console.error(`[Persona] markdown rendering failed; falling back to plain text:`,t)),Le(e.text??``)}}};function Au(e){let t=M(`div`,`persona-attachment-drop-overlay`);e?.background&&t.style.setProperty(`--persona-drop-overlay-bg`,e.background),e?.backdropBlur!==void 0&&t.style.setProperty(`--persona-drop-overlay-blur`,e.backdropBlur),e?.border&&t.style.setProperty(`--persona-drop-overlay-border`,e.border),e?.borderRadius&&t.style.setProperty(`--persona-drop-overlay-radius`,e.borderRadius),e?.inset&&t.style.setProperty(`--persona-drop-overlay-inset`,e.inset),e?.labelSize&&t.style.setProperty(`--persona-drop-overlay-label-size`,e.labelSize),e?.labelColor&&t.style.setProperty(`--persona-drop-overlay-label-color`,e.labelColor);let n=e?.iconName??`upload`,r=e?.iconSize??`48px`,i=e?.iconColor??`rgba(59, 130, 246, 0.6)`,a=e?.iconStrokeWidth??.5,o=N(n,r,i,a);if(o&&t.appendChild(o),e?.label){let n=M(`span`,`persona-drop-overlay-label`);n.textContent=e.label,t.appendChild(n)}return t}const ju=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t?{...t,...r}:r}return n},Mu=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:ju(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),Nu=(t,n,r)=>{if(t==null)throw Error(`createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).`);t.id&&!t.getAttribute(`data-persona-instance`)&&t.setAttribute(`data-persona-instance`,t.id),t.hasAttribute(`data-persona-root`)||t.setAttribute(`data-persona-root`,`true`);let i=te(n),o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=xn((e,t)=>{gs.delete(e);let n=Array.from(V.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?Sc(e,n,o,i):dc(e,n,s))}),l=/* @__PURE__ */ new Map,u=()=>{Oe({delayMs:i.tooltip?.delayMs??200,skipDelayMs:i.tooltip?.skipDelayMs??300})};u();let d=i.features;i=xl(i);let f=Pl.getForInstance(i.plugins),p=gt(t),m=[],g=!1,_=uc(()=>i),y=null,x=null,T=null,E=!1,ee=null,ne=t=>{y=t,t.initApprovalUi({webMcpToolTitle:e});let n=t.createBuiltInApprovalPlugin(l);x=n.plugin,T=n.teardown},re=()=>{if(y)return y;let e=kc();return e?(ne(e),e):(Oc().then(e=>{E||y||(ne(e),ee?.())}).catch(()=>{}),null)},ie=!1,ae=!1,oe=null,se=(e,t,n,r)=>{if(!e.querySelector(`[data-tv-form]`))return;let i=Nl();i?i.enhanceWithForms(e,t,n,r):Ml().then(()=>{ie||ae||!oe||(ae=!0,oe())}).catch(()=>{})};i.components&&Ge.registerAll(i.components);let O=zl(),fe=i.persistState===!1?null:i.storageAdapter??Zl(Xl(typeof i.persistState==`object`?i.persistState.keyPrefix:void 0)),k=!!i.clientToken&&typeof i.reconnectStream!=`function`,pe={},_e=null,ve,ye=new Promise(e=>{ve=e}),A=()=>{},Se=new Promise(e=>{A=e}),Te,je=!1,Me=e=>{if(i.onStateLoaded)try{let t=i.onStateLoaded(e);if(t&&typeof t==`object`&&`state`in t){let{state:e,open:n}=t;return n&&(je=!0),e}return t}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}return e};if(fe?.load)try{let e=fe.load();if(e&&typeof e.then==`function`)_e=e.then(e=>Me(e??{messages:[],metadata:{}}));else{let t=Me(e??{messages:[],metadata:{}});t.metadata&&(pe=Du(t.metadata)),t.messages?.length&&(i={...i,initialMessages:t.messages}),t.artifacts?.length&&(i={...i,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),Te=t.draft}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to load stored state:`,e)}else if(i.onStateLoaded)try{let e=Me({messages:[],metadata:{}});e.messages?.length&&(i={...i,initialMessages:e.messages})}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}_e||ve();let j=()=>pe,Ne=e=>{pe=e({...pe})??{},Dc()},Pe=i.actionParsers&&i.actionParsers.length?i.actionParsers:[Hl],Ie=i.actionHandlers&&i.actionHandlers.length?i.actionHandlers:[Wl.message,Wl.messageAndClick],ze=Kl({parsers:Pe,handlers:Ie,getSessionMetadata:j,updateSessionMetadata:Ne,emit:O.emit,documentRef:typeof document<`u`?document:null});ze.syncFromMetadata();let Be=i.launcher?.enabled??!0,He=i.launcher?.autoExpand??!1,We=i.autoFocusInput??!1,Ke=He,qe=Be,Je=i.layout?.header?.layout,Ye=!1,P=()=>So(i),it=()=>Be||P(),F=P()?!1:!Be||He,at=!1,ot=null,ct=()=>{at=!0,ot&&clearTimeout(ot),ot=setTimeout(()=>{at&&=(typeof console<`u`&&console.warn(`[AgentWidget] Resubmit requested but no injection occurred within 10s`),!1)},1e4)},lt=ku(i,ze,ct),ut=i.features?.showReasoning??!0,dt=i.features?.showToolCalls??!0,ft=i.features?.showEventStreamToggle??!1,mt=i.features?.scrollToBottom??{},ht=i.features?.scrollBehavior??{},_t=()=>(typeof i.persistState==`object`?i.persistState?.keyPrefix:void 0)??`persona-`,vt=`${_t()}event-stream`,yt=null,bt=i.features?.eventStream?.maxEvents??2e3,St=null,wt=null,Et=null,Ot=!1,Xt=null,Qt=!1,$t=null,en=0,tn=(e,t)=>{St?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},rn=(e,t)=>{wt?.processEvent(e,t),St?tn(e,t):Et&&(Et.length>=bt&&Et.shift(),Et.push({type:e,payload:t}))},an=()=>{!St&&ft&&(Et??=[],Mc().then(e=>{if(Ot||St||!ft)return;yt=new e.EventStreamStore(vt),St=new e.EventStreamBuffer(bt,yt),wt??=new e.ThroughputTracker,yt.open().then(()=>St?.restore()).catch(e=>{i.debug&&console.warn(`[AgentWidget] IndexedDB not available for event stream:`,e)});let t=Et??[];Et=null;for(let e of t)wt?.processEvent(e.type,e.payload),tn(e.type,e.payload)}).catch(()=>{}))};ft&&an();let on=!1,sn=null,cn=()=>{},ln=()=>{},un=()=>{},dn=()=>{},fn=()=>{},pn=()=>Qt||on&&sn===`panel`,mn={onCopy:e=>{O.emit(`message:copy`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.id,`copy`).catch(e=>{i.debug&&console.error(`[AgentWidget] Failed to submit copy feedback:`,e)}),i.messageActions?.onCopy?.(e)},onFeedback:e=>{O.emit(`message:feedback`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.messageId,e.type).catch(e=>{i.debug&&console.error(`[AgentWidget] Failed to submit feedback:`,e)}),i.messageActions?.onFeedback?.(e)}};i.statusIndicator;let hn=(e,t=i.statusIndicator??{})=>e===`idle`?t.idleText??xt.idle:e===`connecting`?t.connectingText??xt.connecting:e===`connected`?t.connectedText??xt.connected:e===`error`?t.errorText??xt.error:e===`paused`?t.pausedText??xt.paused:e===`resuming`?t.resumingText??xt.resuming:xt[e];function gn(e,t,n,r){if(!P()&&(n.mode===`transient`||e.classList.contains(`persona-mb-2`))&&(C(e,Dn,n),w(e,n,r)),!(e.hasAttribute(bu)||e.hasAttribute(xu))){if(r===`idle`&&n.idleLink){e.textContent=``;let r=document.createElement(`a`);r.href=n.idleLink,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=t,r.style.color=`inherit`,r.style.textDecoration=`none`,e.appendChild(r)}else e.textContent=t}}let _n=oc({config:i,showClose:it()}),{wrapper:I,panel:L,pillRoot:vn}=_n.shell,R=_n.panelElements,{container:z,body:B,messagesWrapper:V,starterSuggestions:wn,transcriptSuggestions:Tn,suggestions:En,textarea:H,sendButton:U,composerForm:Dn,statusText:W,welcomeHost:On,welcomeIconHolder:kn,greetingHost:jn,introKicker:Nn,introTitle:Pn,introSubtitle:Fn,closeButton:G,iconHolder:Ln,headerTitle:Rn,headerSubtitle:zn,header:Bn,footer:K,actionsRow:Vn}=R,Hn=R.leftActions,Un=R.rightActions,Wn=R.sendButtonWrapper,Gn=R.setSendButtonMode,q=R.micButton,Kn=R.micButtonWrapper,qn=R.attachmentButton,Jn=R.attachmentButtonWrapper,Yn=R.attachmentInput,Xn=R.attachmentPreviewsContainer;z.classList.add(`persona-relative`),B.classList.add(`persona-relative`);let Zn=()=>mt.label??``,$n=()=>mt.iconName??`arrow-down`,er=()=>mt.enabled!==!1,tr=()=>ht.mode??`anchor-top`,nr=()=>tr()===`follow`||tr()===`anchor-top`&&Xs,rr=()=>ht.anchorTopOffset??16,ir=()=>ht.restorePosition??`bottom`,ar=()=>ht.pauseOnInteraction===!0,or=()=>ht.showActivityWhilePinned!==!1,sr=()=>ht.announce===!0,cr=()=>ht.scrollbar??`on-scroll`,lr=M(`button`,`persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer`);lr.type=`button`,lr.style.display=`none`,lr.setAttribute(`data-persona-scroll-to-bottom`,`true`);let fr=M(`span`,`persona-flex persona-items-center`),pr=M(`span`,``),mr=M(`span`,``);mr.setAttribute(`data-persona-scroll-to-bottom-count`,``),mr.style.display=`none`,lr.append(fr,pr,mr),z.appendChild(lr);let hr=M(`div`,`persona-stream-anchor-spacer`);hr.setAttribute(`aria-hidden`,`true`),hr.setAttribute(`data-persona-anchor-spacer`,``),hr.style.flexShrink=`0`,hr.style.pointerEvents=`none`,hr.style.height=`0px`,hr.style.display=`none`,B.appendChild(hr);let gr=M(`div`,`persona-sr-only`);gr.setAttribute(`aria-live`,`polite`),gr.setAttribute(`aria-atomic`,`true`),gr.setAttribute(`role`,`status`),gr.setAttribute(`data-persona-live-region`,``),Object.assign(gr.style,{position:`absolute`,width:`1px`,height:`1px`,margin:`-1px`,padding:`0`,overflow:`hidden`,clip:`rect(0 0 0 0)`,clipPath:`inset(50%)`,whiteSpace:`nowrap`,border:`0`}),z.appendChild(gr);let _r=null,vr=null,yr=e=>{sr()&&e&&(vr=e,_r===null&&(_r=setTimeout(()=>{_r=null,vr&&sr()&&(gr.textContent=vr),vr=null},400)))},br=()=>{let e=t.ownerDocument.defaultView??window;return(i.launcher?.mobileFullscreen??!0)&&e.innerWidth<=(i.launcher?.mobileBreakpoint??640)&&(Be||xo(i))||i.launcher?.fullHeight===!0&&!i.launcher.sidebarMode&&!xo(i)},xr=()=>zs(i,br()),Sr=`empty`,Cr=0,wr=()=>Cr||parseFloat(t.style.getPropertyValue(`--persona-composer-lift`))||0,Or=()=>{let e=K.style.display===`none`?0:K.offsetHeight;lr.style.bottom=`${e+wr()+12}px`};Or();let kr=()=>{hi||(K.style.marginBottom=Cr>0?`${Cr}px`:``)},Ar=()=>{let e=eo(i,P()),n=xr();t.setAttribute(`data-persona-welcome-fullscreen`,String(br())),t.setAttribute(`data-persona-welcome-layout`,n.layout??`top`),t.setAttribute(`data-persona-welcome-layout-explicit`,i.welcome?.layout??``),t.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`);let r=K.style.display===`none`?0:K.offsetHeight,a=n.anchor===`center`&&Sr===`empty`?to(n.anchorComposerTop)??to(`44%`):null,o=a!==null&&n.layout===`centered`&&i.welcome?.anchor===void 0&&i.welcome?.anchorComposerTop===void 0,s=o?getComputedStyle(B):null,c=parseFloat(t.style.getPropertyValue(`--persona-composer-overlay-height`))||0,l=parseFloat(t.style.getPropertyValue(`--persona-composer-lift`))||0,u=Math.max(0,(parseFloat(s?.paddingBottom??``)||0)-(e===`overlay`?c+l:0)),d=o?B.getBoundingClientRect().top-z.getBoundingClientRect().top:0,f=!o||On.hidden?0:(On.querySelector(`[data-persona-welcome-plugin]`)??On).offsetHeight,p=a===null||P()?0:o?Math.max(0,Math.round((z.clientHeight-d-f-u-r)/2)):no({columnHeight:z.clientHeight,footerHeight:r,fraction:a});t.style.setProperty(`--persona-composer-overlay-height`,`${r}px`),t.style.setProperty(`--persona-composer-lift`,`${e===`overlay`?p:0}px`),Cr=e===`block`?p:0,kr(),Or()},jr=()=>{let e=!!Zn();lr.setAttribute(`aria-label`,Zn()||`Jump to latest`),lr.title=Zn(),lr.setAttribute(`data-persona-scroll-to-bottom-has-label`,e?`true`:`false`),fr.innerHTML=``;let t=N($n(),`14px`,`currentColor`,2);t?(fr.appendChild(t),fr.style.display=``):fr.style.display=`none`,pr.textContent=Zn(),pr.style.display=e?``:`none`};jr();let Mr=null,Nr=null,J=ri();J.subscribe(e=>{try{z.dispatchEvent(new CustomEvent(`persona:composer:state`,{detail:e,bubbles:!0,composed:!0}))}catch{}});let Ir=()=>{J.setText(H?.value??``)},Lr=()=>{J.setMentionRefs(Nr?.getMentionRefs()??[])},Rr=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),zr=e=>{let t=Object.freeze(e.map(Rr));J.setAttachments(t);try{i.attachments?.onChange?.(t)}catch(e){console.error(`[AgentWidget] attachments.onChange failed:`,e)}ju()};J.setSelectedModelId(i.composer?.selectedModelId);let Br=()=>i.composer?.modes??[],Vr=()=>Bi(Br(),i.composer?.modeGroups);{let e=Ui(i.composer?.defaultActiveModeIds??[],Br());e.length&&J.setActiveModeIds(e)}function Hr(e){if(J.getState().selectedModelId!==e){J.setSelectedModelId(e),Gr?.repaint();try{i.composer?.onModelChange?.(e)}catch(e){console.error(`[AgentWidget] composer.onModelChange failed:`,e)}}}function Ur(e){J.setActiveModeIds(e),qr?.render(e,Vr()),Yr.forEach(e=>e.repaint()),Ei?.resolve(),od(),Vi()}function Wr(e){Ur(Hi(J.getState().activeModeIds,e,Br(),i.composer?.modeGroups))}let Gr=null,Kr=null,qr=null,Yr=/* @__PURE__ */ new Map,Xr=null;function Zr(e){J.setQuote(e),Xr?.render(J.getState().quote),Vi(),Pc()}let Qr=!1;function $r(){let e=i.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?i.clientToken?`interrupt`:(!Qr&&i.debug===!0&&(Qr=!0,typeof console<`u`&&console.warn(`[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".`)),`block`):e}let ti=null;function ni(e){J.setPendingSubmission(e),ti?.render(J.getState().pendingSubmission),Vi()}let ii=e=>{let t=Yr.get(e);if(t)return t;let n=Ki({groupId:e,getGroup:()=>i.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>Br().filter(t=>t.groupId===e),getActiveIds:()=>J.getState().activeModeIds,onSelect:e=>Wr(e)});return Yr.set(e,n),n},ai=()=>{let e=[],t=J.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(Br().forEach((r,a)=>{if(Ri(r.groupId,i.composer?.modeGroups)){let t=r.groupId;if(n.has(t))return;n.add(t);let o=ii(t);o.action.order=Ii(a),o.action.label=i.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(o.action)}else e.push({id:Fi(r.id),kind:`button`,placement:`start`,order:Ii(a),presentation:r.presentation??`auto`,label:r.label,shortLabel:r.shortLabel,iconName:r.iconName,pressed:t.includes(r.id),onSelect:()=>Wr(r.id)})}),i.composer?.models?.length&&!f.some(e=>e.renderComposer)){let t=i.composer?.modelPicker?.presentation??`native`;(!Gr||Kr!==t)&&(Kr=t,Gr=Ni({getModels:()=>i.composer?.models??[],getSelectedModelId:()=>J.getState().selectedModelId,onSelect:e=>Hr(e),presentation:t,getSuffix:()=>i.composer?.modelPicker?.suffix})),e.push(Gr.action)}return e},si=null,ci=f.find(e=>e.renderHeader);if(ci?.renderHeader){let e=ci.renderHeader({config:i,defaultRenderer:()=>{let e=Bo({config:i,showClose:it()});return Vo(z,e,i),e.header},onClose:()=>ou(!1,`user`)});if(e){let t=Bn;t&&(t.replaceWith(e),Bn=e,_n.header.element=e)}}let li=()=>{Xt&&(B.style.display=`none`,K.parentNode?.insertBefore(Xt.element,K),Xt.update())},ui=()=>{if(!St){an();return}if(Qt=!0,Xt?li():Mc().then(e=>{!Xt&&Qt&&St&&(Xt=e.createEventStreamView({buffer:St,getFullHistory:()=>St.getAllFromStore(),onClose:()=>di(),config:i,plugins:f,getThroughput:()=>wt?.getMetric()??{status:`idle`},renderIconByName:N}),li())}).catch(()=>{di()}),fi){fi.style.boxShadow=`inset 0 0 0 1.5px ${Lo.actionIconColor}`;let e=i.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&fi.classList.add(e))}let e=()=>{if(!Qt)return;let t=Date.now();t-en>=200&&(Xt?.update(),en=t),$t=requestAnimationFrame(e)};en=0,$t=requestAnimationFrame(e),nl(),O.emit(`eventStream:opened`,{timestamp:Date.now()})},di=()=>{if(Qt){if(Qt=!1,Xt&&Xt.element.remove(),B.style.display=``,fi){fi.style.boxShadow=``;let e=i.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&fi.classList.remove(e))}$t!==null&&(cancelAnimationFrame($t),$t=null),nl(),O.emit(`eventStream:closed`,{timestamp:Date.now()})}},fi=null;if(ft){let e=i.features?.eventStream?.classNames,t=`persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1`+(e?.toggleButton?` `+e.toggleButton:``);fi=M(`button`,t),fi.style.width=`28px`,fi.style.height=`28px`,fi.style.color=Lo.actionIconColor,fi.type=`button`,fi.setAttribute(`aria-label`,`Event Stream`),fi.title=`Event Stream`;let n=b(Yt,`18px`,`currentColor`,1.5);n&&fi.appendChild(n);let r=R.clearChatButtonWrapper,a=R.closeButtonWrapper,o=r||a;o&&o.parentNode===Bn?Bn.insertBefore(fi,o):Bn.appendChild(fi),fi.addEventListener(`click`,()=>{Qt?di():ui()})}let mi=e=>{let t=i.attachments;if(!t?.enabled)return;let n=e.querySelector(`[data-persona-composer-attachment-previews]`)??e.querySelector(`.persona-attachment-previews`);if(!n){n=M(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let t=e.querySelector(`[data-persona-composer-form]`);t?.parentNode?t.parentNode.insertBefore(n,t):e.insertBefore(n,e.firstChild)}if(!(e.querySelector(`[data-persona-composer-attachment-input]`)??e.querySelector(`input[type="file"]`))){let n=M(`input`);n.type=`file`,n.setAttribute(`data-persona-composer-attachment-input`,``),n.accept=(t.allowedTypes??pt).join(`,`),n.multiple=(t.maxFiles??4)>1,n.style.display=`none`,n.setAttribute(`aria-label`,t.buttonTooltipText??`Attach files`),e.appendChild(n)}},hi=!1,gi=e=>{let t=f.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let n=i.composer,r=g?Q.isStreaming():!1;return t.renderComposer({config:i,defaultRenderer:e,requestRender:()=>Kp(),storage:_(t.id),onSubmit:e=>{Q&&!Q.isStreaming()&&Ef(e.trim(),{consumeDraft:!1})},streaming:r,disabled:r,openAttachmentPicker:()=>{cu()||Yn?.click()},models:n?.models,selectedModelId:J.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>Hr(e),onVoiceToggle:i.voiceRecognition?.enabled===!0?()=>{si?.()}:void 0})},_i=gi(()=>qo({config:i}).footer);_i&&(_n.replaceComposer(_i),K=_n.composer.footer,hi=!0);let Y=null,vi=e=>{Dn=e.form,H=e.input,Wn=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(U=e.sendButton),e.micButton&&(q=e.micButton,Kn=e.micButton.parentElement),e.found.status&&(W=e.found.status),e.found.suggestions&&(En=e.found.suggestions),e.attachmentButton&&(qn=e.attachmentButton,Jn=e.attachmentButton.parentElement),Yn=e.attachmentInput??null,Xn=e.attachmentPreviews??null,e.found.actionsRow&&(Vn=e.found.actionsRow),Hn=e.found.actionsStart,Un=e.found.actionsEnd};function yi(){let e=H;if(!e)return;let t=i.composer?.inputAttributes,n=!t?.ariaLabel&&!(e instanceof HTMLTextAreaElement)?e.getAttribute(`aria-label`):null;me(e,t),n&&e.setAttribute(`aria-label`,n),he(e,{submitKey:i.composer?.submitKey,insertNewlineOnTouchEnter:i.composer?.insertNewlineOnTouchEnter,coarsePointer:De(e)}),le(e,ke(i.composer?.maxLines,P()?5:3))}let bi=e=>{Y=oi(e,{debug:i.debug===!0}),Y&&vi(Y),yi()};mi(K),bi(K),Ir();let xi=$a(i,P());xi&&(V.style.maxWidth=xi,V.style.marginLeft=`auto`,V.style.marginRight=`auto`,V.style.width=`100%`,jn.style.maxWidth=xi,jn.style.marginLeft=`auto`,jn.style.marginRight=`auto`,jn.style.width=`100%`,wn.style.maxWidth=xi,Tn.style.maxWidth=xi,Tn.style.marginLeft=`auto`,Tn.style.marginRight=`auto`,Tn.style.width=`100%`);let Si=()=>{let e=$a(i,P());if(e&&!P())for(let t of[Dn,En,Xn,W])t&&(t.style.maxWidth=e,t.style.marginLeft=`auto`,t.style.marginRight=`auto`,t.style.width=`100%`)};Si();let Ci=()=>{i.attachments?.enabled&&Yn&&Xn&&(Mr?Mr.remountPreviews(Xn):(Mr=ei.fromConfig(i.attachments,zr),Mr.setPreviewsContainer(Xn)),Y?.addListener(Yn,`change`,e=>{let t=e.target;Mr?.handleFileSelect(t.files),t.value=``}),z.querySelector(`.persona-attachment-drop-overlay`)||z.appendChild(Au(i.attachments.dropOverlay)))};Ci();let wi=()=>Nr?.prefetch(),Ti=()=>{if(!i.contextMentions?.enabled||!H)return;let e=dr();if(!e){let e=H;ur().then(()=>{!Nr&&H===e&&e.isConnected&&(Ti(),Ei?.resolve())},()=>{});return}let t=Y?.header??null,n=t?Tt(t):void 0;if(Nr=e.createContextMentionOrchestrator({deps:{loadContextMentions:ge,loadContextMentionsInline:Ce,renderLucideIcon:N,createMentionButton:be},config:i,textarea:H,anchor:Dn??H,getMessages:()=>Q.getMessages(),liveRegionHost:z,chipRow:n}),Nr&&!n){let e=H;e.parentElement?.insertBefore(Nr.contextRow,e)}};Ti();let Ei=null,Di={getState:()=>J.getState(),getValue:()=>H?.value??``,setValue:e=>{H&&(H.value=e,H.dispatchEvent(new Event(`input`,{bubbles:!0})),Ir())},submit:()=>{kt(Y?.form??null)},openAttachmentPicker:()=>{cu()||Yn?.click()},toggleVoice:()=>{si?.()},requestRender:()=>Ei?.resolve()},Oi=()=>{let e=[];return(Nr?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:pi.mention+n,element:t,managed:!0})}),Jn&&e.push({id:`core:attachment`,placement:`start`,order:pi.attachment,element:Jn}),Kn&&e.push({id:`core:mic`,placement:`end`,order:pi.mic,element:Kn}),Wn&&e.push({id:`core:send`,placement:`end`,order:pi.send,element:Wn}),e},ki=()=>{Ei?.destroy(),Ei=Ai({getBindings:()=>Y,collect:()=>({builtIns:Oi(),configActions:[...ai(),...i.composer?.actions??[]],plugins:f,contributionContext:{config:i,getState:()=>J.getState(),requestRender:()=>Ei?.resolve()},debug:i.debug===!0}),actionContext:Di,getState:()=>J.getState(),getOverflow:()=>i.composer?.actionOverflow,reportError:(e,t)=>{typeof console<`u`&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),Ei.resolve()};ki();let ji=()=>{if(qr?.destroy(),qr=null,!Vr().length)return;let e=Y?.header;e&&(qr=Pi({row:Tt(e),onRemove:e=>Wr(e),initialIds:J.getState().activeModeIds}),qr.render(J.getState().activeModeIds,Vr()))};ji();let Mi=()=>{Xr?.destroy(),Xr=null,ti?.destroy(),ti=null;let e=Y?.header;e&&(Xr=qi({onDismiss:()=>Zr(void 0)}),e.appendChild(Xr.element),Xr.render(J.getState().quote),$r()===`defer-one`&&(ti=Ji({onEdit:()=>hf(),onRemove:()=>ni(void 0)}),e.appendChild(ti.element),ti.render(J.getState().pendingSubmission)))};Mi();let Li=ea(),zi=()=>{let e=Y?.header?.querySelector(Dt);if(e)return e.childElementCount>0;let t=J.getState();return t.mentionRefs.length>0||Ui(t.activeModeIds,Vr()).length>0};function Vi(){let e=J.getState(),t=Li.observe(ta(H),e.text);K.toggleAttribute(`data-persona-composer-compact`,$i({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:zi(),hasQuote:e.quote!==void 0,hasPendingSubmission:e.pendingSubmission!==void 0}))}function ia(){i.composer?.layout===`single-row`&&!P()?K.setAttribute(`data-persona-composer-layout`,`single-row`):K.removeAttribute(`data-persona-composer-layout`)}ia(),J.subscribe(()=>{Ei?.sync(),ju(),Nu(),Vi(),Pc()}),Nu();let aa=!1,sa=e=>{if(aa||i.debug!==!0)return;let t=[`messages`,`composer`].filter(t=>e[t]);t.length&&(aa=!0,console.warn(`[persona] layout.slots.${t.join(` and layout.slots.`)} ${t.length>1?`are`:`is`} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let e=i.layout?.slots??{};sa(e);let t=e=>{switch(e){case`body-top`:return B.querySelector(`[data-persona-intro-card]`);case`messages`:return V;case`footer-top`:return En;case`composer`:return Dn;case`footer-bottom`:return W;default:return null}},n=(e,t)=>{switch(e){case`header-left`:case`header-center`:case`header-right`:if(e===`header-left`)Bn.insertBefore(t,Bn.firstChild);else if(e===`header-right`)Bn.appendChild(t);else{let e=Bn.querySelector(`.persona-flex-col`);e?e.parentNode?.insertBefore(t,e.nextSibling):Bn.appendChild(t)}break;case`body-top`:{let e=B.querySelector(`[data-persona-intro-card]`);e?e.replaceWith(t):B.insertBefore(t,B.firstChild);break}case`body-bottom`:B.appendChild(t);break;case`footer-top`:En.replaceWith(t);break;case`footer-bottom`:W.replaceWith(t)}};for(let[r,a]of Object.entries(e))if(a)try{let e=a({config:i,defaultContent:()=>t(r)});e&&n(r,e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Error rendering slot "${r}":`,e)}})(),V.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`button[data-persona-copy-tool-detail]`);n&&(e.preventDefault(),e.stopPropagation(),_c(n))});let ca=e=>{let t=e.target.closest(`button[data-expand-header="true"]`);if(!t)return;let n=t.closest(`.persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;ec(),rl();let a=t.getAttribute(`data-bubble-type`);if(n.classList.contains(`persona-activity-row`)){c.manual(r);let e=n.parentElement?.closest(`[data-persona-tool-group]`);e?.dataset.messageId&&c.manual(e.dataset.messageId)}if(a===`reasoning`)s.has(r)?s.delete(r):s.add(r),dc(r,n,s);else if(a===`tool`)o.has(r)?o.delete(r):o.add(r),Sc(r,n,o,i);else if(a===`approval`&&y){let e=((i.approval===!1?void 0:i.approval)?.detailsDisplay??`collapsed`)===`expanded`,t=l.get(r)??e;l.set(r,!t),y.updateApprovalDetailsUI(r,n,i,l)}gs.delete(r)};V.addEventListener(`pointerdown`,e=>{e.target.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),ca(e))}),V.addEventListener(`click`,e=>{e.detail===0&&e.target.closest(`.persona-activity-row`)&&ca(e)}),V.addEventListener(`keydown`,e=>{let t=e.target;(e.key===`Enter`||e.key===` `)&&t.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),ca(e))}),V.addEventListener(`copy`,e=>{let{clipboardData:t}=e;if(!t)return;let n=V.getRootNode(),r=typeof n.getSelection==`function`?n.getSelection():window.getSelection();if(!r||r.isCollapsed)return;let i=r.toString(),a=io(i);a&&a!==i&&(t.setData(`text/plain`,a),e.preventDefault())});let la=/* @__PURE__ */ new Map,ua=null,da=`idle`,fa={idle:{icon:`volume-2`,label:`Read aloud`},loading:{icon:`loader-circle`,label:`Loading…`},playing:{icon:`pause`,label:`Pause`},paused:{icon:`play`,label:`Resume`}},pa=(e,t)=>{let{icon:n,label:r}=fa[t];e.setAttribute(`aria-label`,r),e.title=r,e.setAttribute(`aria-pressed`,t===`idle`?`false`:`true`),e.classList.toggle(`persona-message-action-active`,t!==`idle`),e.classList.toggle(`persona-message-action-loading`,t===`loading`);let i=N(n,14,`currentColor`,2);i&&(e.innerHTML=``,e.appendChild(i))},ma=()=>{V.querySelectorAll(`[data-action="read-aloud"]`).forEach(e=>{let t=e.closest(`[data-actions-for]`)?.getAttribute(`data-actions-for`)??null;pa(e,t&&t===ua?da:`idle`)})};V.addEventListener(`click`,e=>{let t=e.target.closest(`.persona-message-action-btn[data-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`[data-actions-for]`);if(!n)return;let r=n.getAttribute(`data-actions-for`);if(!r)return;let a=t.getAttribute(`data-action`);if(a===`copy`){let e=Q.getMessages().find(e=>e.id===r);if(e&&mn.onCopy){let n=e.content||``;navigator.clipboard.writeText(n).then(()=>{t.classList.add(`persona-message-action-success`);let e=b(Zt,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e)),setTimeout(()=>{t.classList.remove(`persona-message-action-success`);let e=b(nn,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))},2e3)}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to copy message:`,e)}),mn.onCopy(e)}}else if(a===`read-aloud`)Q.toggleReadAloud(r);else if(a===`upvote`||a===`downvote`){let e=(la.get(r)??null)===a,i=a===`upvote`?`thumbs-up`:`thumbs-down`;if(e){la.delete(r),t.classList.remove(`persona-message-action-active`);let e=N(i,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))}else{let e=a===`upvote`?`downvote`:`upvote`,o=n.querySelector(`[data-action="${e}"]`);if(o){o.classList.remove(`persona-message-action-active`);let t=N(e===`upvote`?`thumbs-up`:`thumbs-down`,14,`currentColor`,2);t&&(o.innerHTML=``,o.appendChild(t))}la.set(r,a),t.classList.add(`persona-message-action-active`);let s=N(i,14,`currentColor`,2);s&&(s.setAttribute(`fill`,`currentColor`),t.innerHTML=``,t.appendChild(s)),t.classList.remove(`persona-message-action-pop`),t.offsetWidth,t.classList.add(`persona-message-action-pop`);let c=Q.getMessages().find(e=>e.id===r);c&&mn.onFeedback&&mn.onFeedback({type:a,messageId:c.id,message:c})}}else if(a===`regenerate`)ha?.regenerate(r);else if(a===`edit`)ha?.edit(r);else if(a===`quote`)ha?.quote(r);else if(a?.startsWith(`custom:`)){let e=a.slice(7),t=i.messageActions?.custom?.find(t=>t.id===e),n=Q.getMessages().find(e=>e.id===r);if(!t||!n)return;try{t.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let ha=null;V.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-approval-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`.persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;let i=t.getAttribute(`data-approval-action`);if(!i)return;let a=i===`approve`?`approved`:`denied`,o=Q.getMessages().find(e=>e.id===r);if(!o?.approval)return;let s=n.querySelector(`[data-approval-buttons]`);s&&s.querySelectorAll(`button`).forEach(e=>{e.disabled=!0,e.style.opacity=`0.5`,e.style.cursor=`not-allowed`}),v(o.approval)?Q.resolveWebMcpApproval(r,a):Q.resolveApproval(o.approval,a)});let X=null,ga=!1,_a=null,va=()=>{},ya=`none`,ba=null,xa={artifacts:[],selectedId:null},Sa=!1,wa=!1,Ta=!1,Ea=!1,Da=()=>Ea||xa.artifacts.some(e=>rt(i.features?.artifacts,e)===`panel`),Oa=()=>xa.artifacts.length>0&&!Sa&&Da(),ka={current:null},Aa=(e,t)=>{let n=Q.getArtifactById(t),r=n?.markdown,i=n?.title||`artifact`,a=n?.file,o=n?.artifactType??`markdown`;if(!r){let t=(e.closest(`[data-open-artifact], [data-artifact-inline]`)?.closest(`[data-message-id]`))?.getAttribute(`data-message-id`);if(t){let e=Q.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);r=t?.props?.markdown,i=t?.props?.title||i,t?.props?.file&&typeof t.props.file==`object`&&(a=t.props.file),!n&&typeof t?.props?.artifactType==`string`&&(o=t.props.artifactType)}catch{}}}return{markdown:r,title:i,file:a,artifactType:o}};V.addEventListener(`click`,e=>{let t=e.target.closest(`[data-download-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-download-artifact`);if(!n||i.features?.artifacts?.onArtifactAction?.({type:`download`,artifactId:n})===!0)return;let{markdown:r,title:a,file:o}=Aa(t,n);if(!r)return;let s=Hc();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:a,markdown:r,file:o}))}),V.addEventListener(`click`,e=>{let t=e.target.closest(`[data-artifact-custom-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-artifact-custom-action`);if(!n)return;let r=t.closest(`[data-artifact-inline]`),a=r?null:t.closest(`[data-open-artifact]`),o=r?r.getAttribute(`data-artifact-inline`):a?.getAttribute(`data-open-artifact`)??null,s=(r?i.features?.artifacts?.inlineActions:i.features?.artifacts?.cardActions)?.find(e=>e.id===n);if(!s)return;let{markdown:c,title:l,file:u,artifactType:d}=Aa(t,o??``),f={artifactId:o,title:l,artifactType:d,markdown:c,file:u};try{Promise.resolve(s.onClick(f)).catch(()=>{})}catch{}}),V.addEventListener(`click`,e=>{let t=e.target.closest(`[data-copy-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-copy-artifact`);if(!n)return;let r=Q.getArtifactById(n),i=Hc();if(!i)return;let a=``;if(r)a=i.artifactCopyText(r);else{let{markdown:e,file:r,artifactType:o}=Aa(t,n);o===`markdown`&&(a=i.artifactCopyText({id:n,artifactType:`markdown`,status:`complete`,markdown:e??``,...r?{file:r}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=b(Zt,16,`currentColor`,2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=b(nn,16,`currentColor`,2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),V.addEventListener(`click`,e=>{let t=e.target.closest(`[data-expand-artifact-inline]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-expand-artifact-inline`);n&&i.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:n})!==!0&&(Sa=!1,Ea=!0,wa=!0,Ta=!0,Q.selectArtifact(n),vo())}),V.addEventListener(`click`,e=>{let t=e.target;if(t.closest(`[data-download-artifact]`)||t.closest(`[data-artifact-custom-action]`))return;let n=t.closest(`[data-open-artifact]`);if(!n)return;let r=n.getAttribute(`data-open-artifact`);r&&i.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:r})!==!0&&(e.preventDefault(),e.stopPropagation(),Sa=!1,Ea=!0,Q.selectArtifact(r),vo())}),V.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target;(t.hasAttribute(`data-open-artifact`)||t.hasAttribute(`data-expand-artifact-inline`))&&(e.preventDefault(),t.click())});let ja=R.composerOverlay,Ma=e=>{ur().catch(()=>{}),Ze(e,i,ja)},Na=null,Pa={mount:t,overlay:ja,sessionRef:ka,config:()=>i},Fa=!1,Ia=e=>t=>{let n=t.target,r=n?.closest?.(`[data-persona-ask-sheet-for]`);if(!r||!(e===`click`?n?.closest(`[data-ask-user-action]`):t.key===`Enter`&&n?.matches?.(`[data-ask-free-text-input="true"]`)))return;let i=n=>{Na??=n.createAskUserSheetHandlers(Pa),Na[e](t)},a=dr();a?i(a):Fa||(Fa=!0,ur().then(e=>{Fa=!1,r.isConnected&&i(e)},()=>{Fa=!1}))};ja.addEventListener(`click`,Ia(`click`)),ja.addEventListener(`keydown`,Ia(`keydown`));let La=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)return;let n=ja.querySelector(`[data-persona-ask-sheet-for]`);if(!n||n.getAttribute(`data-ask-layout`)!==`rows`||n.getAttribute(`data-multi-select`)===`true`)return;let r=Number(e.key),i=n.querySelectorAll(`[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]`)[r-1];i&&(e.preventDefault(),i.click())};document.addEventListener(`keydown`,La);let Ra=null,za=null,Ba=null,Va=null,Ha=()=>{},Ua=!1,Wa=``,Ga=``;function qa(){Va?.(),Va=null}let Ja=()=>{let e=Fd?.railShell?Fd.railHost:null,t=e?.isConnected?e:null,n=t?t.getBoundingClientRect().width:0;return n<=0?200:n+360},Xa=()=>{if(!Ra||!za)return;let e=t.classList.contains(`persona-artifact-welded-split`),n=t.ownerDocument.defaultView??window,r=n.innerWidth<=640;if(!e||t.classList.contains(`persona-artifact-narrow-host`)||r){za.style.removeProperty(`position`),za.style.removeProperty(`left`),za.style.removeProperty(`top`),za.style.removeProperty(`bottom`),za.style.removeProperty(`width`),za.style.removeProperty(`z-index`);return}let i=Ra.firstElementChild;if(!i||i===za)return;za.style.position=`absolute`,za.style.top=`0`,za.style.bottom=`0`,za.style.width=`10px`,za.style.zIndex=`5`;let a=El(Ra,n),o=i.offsetWidth+a/2-5;za.style.left=`${Math.max(0,o)}px`},po=()=>{},mo=()=>{let e=t.ownerDocument.defaultView??window,n=i.launcher?.mobileFullscreen??!0,r=i.launcher?.mobileBreakpoint??640;return!n||e.innerWidth>r?!1:Be||xo(i)},_o=()=>!Wc(i)||!Oa()||t.classList.contains(`persona-artifact-narrow-host`)||mo()||(t.ownerDocument.defaultView??window).innerWidth<641?`none`:Yc(i)?`detached`:`welded`,vo=()=>{if(!X||!Wc(i))return;Xc(t,i),Zc(t,i),po();let e=i.features?.artifacts?.layout?.narrowHostMaxWidth??520,n=L.getBoundingClientRect().width||0;t.classList.toggle(`persona-artifact-narrow-host`,n>0&&n<=e);let r=Oa();X.setVisible(r),X.update(xa),Sa?(X.setMobileOpen(!1),X.element.classList.add(`persona-hidden`),X.backdrop?.classList.add(`persona-hidden`),wa=!1,Ta=!1):xa.artifacts.length>0&&Da()?(X.element.classList.remove(`persona-hidden`),X.setMobileOpen(!0)):(X.setMobileOpen(!1),X.element.classList.add(`persona-hidden`),X.backdrop?.classList.add(`persona-hidden`),wa=!1,Ta=!1);let a=i.features?.artifacts?.layout?.showExpandToggle===!0;if(X.setExpandToggleVisible(a),X.setCopyButtonVisible(i.features?.artifacts?.layout?.showCopyButton===!0),X.setRefreshButtonVisible(typeof i.features?.artifacts?.layout?.onDocumentToolbarRefresh==`function`),X.setCustomActions(i.features?.artifacts?.toolbarActions??[]),X.setTabFade(i.features?.artifacts?.layout?.tabFade),X.setRenderTabBar(i.features?.artifacts?.renderTabBar),!a&&!Ta&&(wa=!1),wa!==Ua){let e=X.element;wa?(Wa=e.style.width,Ga=e.style.maxWidth,e.style.removeProperty(`width`),e.style.removeProperty(`max-width`)):(Wa&&(e.style.width=Wa),Ga&&(e.style.maxWidth=Ga),Wa=``,Ga=``),Ua=wa}t.classList.toggle(`persona-artifact-expanded`,wa),X.setExpanded(wa);let o=_o();o!==ya&&(ya=o,va()),Ha()};if(Wc(i)){L.style.position=`relative`;let e=M(`div`,`persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0`),n=M(`div`,`persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root`);e.appendChild(z),Ra=n,n.appendChild(e),L.appendChild(n);let r=e=>{ga||X||(X=e.createArtifactPane(i,{onSelect:e=>ka.current?.selectArtifact(e),onDismiss:()=>{Sa=!0,vo()},onToggleExpand:()=>{let e=!wa,t=xa.selectedId??xa.artifacts[xa.artifacts.length-1]?.id??null;i.features?.artifacts?.onArtifactAction?.({type:`expand`,artifactId:t,expanded:e})!==!0&&(wa=e,e||(Ta=!1),vo())}}),X.element.classList.add(`persona-hidden`),n.appendChild(X.element),X.backdrop&&L.appendChild(X.backdrop),Ha(),vo())},a=Hc();a?r(a):(Uc(()=>{let e=Hc();e&&r(e)}),Vc().catch(()=>{})),Ha=()=>{if(Ra&&X){if(i.features?.artifacts?.layout?.resizable!==!0)Ba?.(),Ba=null,qa(),za&&=(za.remove(),null),X.element.style.removeProperty(`width`),X.element.style.removeProperty(`maxWidth`);else{if(!za){let e=M(`div`,`persona-artifact-split-handle persona-shrink-0 persona-h-full`);e.setAttribute(`role`,`separator`),e.setAttribute(`aria-orientation`,`vertical`),e.setAttribute(`aria-label`,`Resize artifacts panel`),e.tabIndex=0;let n=t.ownerDocument,r=n.defaultView??window,a=a=>{if(!X||a.button!==0||t.classList.contains(`persona-artifact-narrow-host`)||t.classList.contains(`persona-artifact-expanded`)||r.innerWidth<=640)return;a.preventDefault(),qa();let o=a.clientX,s=X.element.getBoundingClientRect().width,c=i.features?.artifacts?.layout,l=n=>{let i=Ra.getBoundingClientRect().width,a=t.classList.contains(`persona-artifact-welded-split`),l=El(Ra,r),u=a?0:e.getBoundingClientRect().width||6,d=Dl(s-(n.clientX-o),i,l,u,c?.resizableMinWidth,c?.resizableMaxWidth,Ja());X.element.style.width=`${d}px`,X.element.style.maxWidth=`none`,Xa()},u=()=>{n.removeEventListener(`pointermove`,l),n.removeEventListener(`pointerup`,u),n.removeEventListener(`pointercancel`,u),Va=null;try{e.releasePointerCapture(a.pointerId)}catch{}};Va=u,n.addEventListener(`pointermove`,l),n.addEventListener(`pointerup`,u),n.addEventListener(`pointercancel`,u);try{e.setPointerCapture(a.pointerId)}catch{}};e.addEventListener(`pointerdown`,a),za=e,Ra.insertBefore(e,X.element),Ba=()=>{e.removeEventListener(`pointerdown`,a)}}if(za){let e=Oa();za.classList.toggle(`persona-hidden`,!e),Xa()}}}},po=()=>{if(!Be||!X||(i.launcher?.sidebarMode??!1)||xo(i)&&Co(i).reveal===`emerge`)return;let e=t.ownerDocument.defaultView??window,n=i.launcher?.mobileFullscreen??!0,r=i.launcher?.mobileBreakpoint??640;if(n&&e.innerWidth<=r||!Qc(i,Be))return;let a=Us(i).width,o=i.features?.artifacts?.layout?.expandedPanelWidth??`min(720px, calc(100vw - 24px))`;Oa()?(L.style.width=o,L.style.maxWidth=o):(L.style.width=a,L.style.maxWidth=a)},typeof ResizeObserver<`u`&&(_a=new ResizeObserver(()=>{vo()}),_a.observe(L))}else L.appendChild(z);P()&&vn&&(R.peekBanner&&vn.appendChild(R.peekBanner),vn.appendChild(K)),t.appendChild(I),vn&&t.appendChild(vn);let bo=()=>{let e=mo()||P()&&i.launcher?.composerBar?.expandedSize===`fullscreen`||i.launcher?.fullHeight===!0&&!i.launcher?.sidebarMode&&!xo(i);if(V.style.gap=e?`var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))`:`var(--persona-components-message-gap, 12px)`,V.style.setProperty(`--persona-transcript-gap`,V.style.gap),P()){L.style.width=`100%`,L.style.maxWidth=`100%`;let e=i.launcher?.composerBar??{},t=I.dataset.state===`expanded`,n=e.expandedSize??`anchored`;if(!(t&&n!==`fullscreen`)){z.style.background=``,z.style.border=``,z.style.borderRadius=``,z.style.overflow=``,z.style.boxShadow=``;return}let r=i.theme?.components?.panel,a=Ya(i),o=(e,t)=>e==null||e===``?t:Ca(a,e)??e;z.style.background=`var(--persona-surface, #ffffff)`,z.style.border=o(r?.border,`1px solid var(--persona-border)`),z.style.borderRadius=o(r?.borderRadius,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`),z.style.boxShadow=o(r?.shadow,`var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))`),z.style.overflow=`hidden`;return}let n=xo(i),r=i.launcher?.sidebarMode??!1,a=n||r||(i.launcher?.fullHeight??!1),o=i.launcher?.enabled===!1,s=i.launcher?.detachedPanel===!0,c=i.theme?.components?.panel,l=i.darkTheme?.components?.panel,u=Ka(i)===`dark`?ce(c??{},l??{}):c,d=Ya(i),f=(e,t)=>e==null||e===``?t:Ca(d,e)??e,p=t.ownerDocument.defaultView??window,m=i.launcher?.mobileFullscreen??!0,h=i.launcher?.mobileBreakpoint??640,g=p.innerWidth<=h,_=m&&g&&Be,v=n&&m&&g,y=i.launcher?.position??`bottom-left`,b=y===`bottom-left`||y===`top-left`,x=i.launcher?.zIndex??1e5,S=(e,t,n)=>`var(--persona-components-panel-modes-${e}-${t}, ${n})`,C=u?.modes?.floating,w=f(C?.border??u?.border,S(`floating`,`border`,`var(--persona-panel-border, 1px solid var(--persona-border))`)),T=f(C?.shadow??u?.shadow,S(`floating`,`shadow`,`var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))`)),E=f(C?.borderRadius??u?.borderRadius,S(`floating`,`borderRadius`,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`)),ee=s&&!_&&!v,te=_||v?`mobile`:ee?`floating`:n?`docked`:r?`sidebar`:o?`inline`:`floating`,ne=u?.modes?.[te];ee?t.setAttribute(`data-persona-panel-detached`,`true`):t.removeAttribute(`data-persona-panel-detached`);let re=ee?w:r||_?`none`:w,ie=ee?T:_?`none`:r?b?`2px 0 12px rgba(0, 0, 0, 0.08)`:`-2px 0 12px rgba(0, 0, 0, 0.08)`:o?`none`:T;n&&!_&&!ee&&(ie=`none`,re=`none`);let ae=ee?E:r||_?`0`:E,oe=f(ne?.border??u?.border,S(te,`border`,re)),se=f(ne?.shadow??u?.shadow,S(te,`shadow`,ie)),O=f(ne?.borderRadius??u?.borderRadius,S(te,`borderRadius`,ae)),le=_o(),ue=le===`detached`,de=le===`welded`;t.classList.toggle(`persona-artifact-detached-split`,ue),t.classList.toggle(`persona-artifact-welded-split`,de);let fe=`var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))`,k=(i.features?.artifacts?.layout?.chatSurface===`flush`?`flush`:`card`)==`flush`&&Wc(i)&&Yc(i)&&o&&!n;t.classList.toggle(`persona-artifact-chat-flush`,k);let pe=ue||k?`none`:se,me=ue?w:de?`none`:oe,he=ue?E:O;k&&(me=`none`,he=`0`);let ge=ne?.borderRadius!=null&&ne.borderRadius!==``||u?.borderRadius!=null&&u.borderRadius!==``,_e=k&&!ge?`0`:O,ve=B.scrollTop;t.style.cssText=``,I.style.cssText=``,L.style.cssText=``,z.style.cssText=``,B.style.cssText=``,hi||(K.style.cssText=``),Qt&&(B.style.display=`none`),(a||o)&&(t.style.minWidth=`0`);let ye=()=>{ve<=0||(B.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(B.scrollTop===ve)return;let e=B.scrollHeight-B.clientHeight;e<=0||(B.scrollTop=Math.min(ve,e))})};if(_){I.classList.remove(`persona-bottom-6`,`persona-right-6`,`persona-left-6`,`persona-top-6`,`persona-bottom-4`,`persona-right-4`,`persona-left-4`,`persona-top-4`),I.style.cssText=`
|
|
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;
|
|
@@ -37,7 +37,7 @@ 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 a
|
|
|
37
37
|
flex-direction: column !important;
|
|
38
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{_ 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 a
|
|
|
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{_ 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 a
|
|
|
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;
|
|
@@ -74,7 +74,7 @@ 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 a
|
|
|
74
74
|
flex-direction: column !important;
|
|
75
75
|
z-index: ${x} !important;
|
|
76
76
|
${b?`left: var(--persona-panel-inset) !important; right: auto !important;`:`left: auto !important; right: var(--persona-panel-inset) !important;`}
|
|
77
|
-
`:
|
|
77
|
+
`:L.style.cssText=`
|
|
78
78
|
position: fixed !important;
|
|
79
79
|
top: 0 !important;
|
|
80
80
|
bottom: 0 !important;
|
|
@@ -87,7 +87,7 @@ 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 a
|
|
|
87
87
|
flex-direction: column !important;
|
|
88
88
|
z-index: ${x} !important;
|
|
89
89
|
${b?`left: 0 !important; right: auto !important;`:`left: auto !important; right: 0 !important;`}
|
|
90
|
-
`,
|
|
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{_ 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 a
|
|
|
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{_ 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 a
|
|
|
110
110
|
min-height: 0 !important;
|
|
111
111
|
max-height: 100% !important;
|
|
112
112
|
overflow: hidden !important;
|
|
113
|
-
border-radius: ${
|
|
114
|
-
border: ${
|
|
115
|
-
${
|
|
116
|
-
${
|
|
117
|
-
`,
|
|
113
|
+
border-radius: ${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(!o&&!n){let e=r?``:`padding-top: 1.25em !important;`,t=r?``:`z-index: ${i.launcher?.zIndex??1e5} !important;`;I.style.cssText+=`max-height: -moz-available !important; max-height: stretch !important;`+e+t}kr(),ye()},wo=()=>{t.style.setProperty(`--persona-content-max-width`,$a(i,P()))},Eo=!1;function Do(){i.layout?.topFade&&B.scrollTop>1?B.setAttribute(`data-persona-top-fade`,`true`):B.removeAttribute(`data-persona-top-fade`)}let Oo=()=>{Do();let e=eo(i,P());P()&&i.composer?.placement&&i.debug===!0&&!Eo&&(Eo=!0,console.warn(`[persona] composer.placement is ignored in composer-bar mount mode.`));let n=xr();t.setAttribute(`data-persona-composer-placement`,e),t.setAttribute(`data-persona-conversation-state`,Sr),t.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`),t.style.setProperty(`--persona-composer-anchor-gap`,n.composerGap??`24px`),Ar()},Mo=()=>{if(P())return;let e=xo(i),n=i.launcher?.sidebarMode??!1;if(e||n||(i.launcher?.fullHeight??!1)||!Be)return;let r=t.ownerDocument.defaultView??window,a=i.launcher?.mobileFullscreen??!0,o=i.launcher?.mobileBreakpoint??640;if(a&&r.innerWidth<=o)return;let s=Us(i);L.style.height=s.height,L.style.maxHeight=s.maxHeight};bo(),Za(t,i),Xc(t,i),Zc(t,i),wo(),Oo(),va=()=>{bo(),Mo(),Za(t,i),Xc(t,i),Zc(t,i),wo(),Oo(),ba?t.style.setProperty(`--persona-artifact-welded-outer-radius`,ba):t.style.removeProperty(`--persona-artifact-welded-outer-radius`),ln(),cn()};let Z=[];Z.push(()=>{ga=!0}),Z.push(()=>{m.forEach(e=>e()),p.destroy()}),Z.push(()=>{document.removeEventListener(`keydown`,La)}),Z.push(()=>{_r!==null&&clearTimeout(_r)});let Fo=null,Io=null;Z.push(()=>{Fo?.(),Fo=null,Io?.(),Io=null}),_a&&Z.push(()=>{_a?.disconnect(),_a=null}),Z.push(()=>{Ba?.(),Ba=null,qa(),za&&=(za.remove(),null),X?.element.style.removeProperty(`width`),X?.element.style.removeProperty(`maxWidth`),X?.destroy()}),ft&&Z.push(()=>{Ot=!0,Et=null,$t!==null&&(cancelAnimationFrame($t),$t=null),Xt?.destroy(),Xt=null,St?.destroy(),St=null,yt=null});let Ro=null,zo=()=>{Ro&&=(Ro(),null),i.colorScheme===`auto`&&(Ro=Qa(()=>{Za(t,i)}))};zo(),Z.push(()=>{Ro&&=(Ro(),null)}),Z.push(()=>{E=!0,T?.()}),Z.push(()=>{ie=!0});let Ho=!1;Z.push(()=>{Ho=!0});let Uo=(e,n)=>{let r=Ht(e,n);return r||!qt.includes(e)?r:(ho().then(r=>{if(Ho)return;Kt(r.wipe),Kt(r.glyphCycle);let i=Ht(e,n);i&&Wt(i,t)}).catch(()=>{}),null)},Wo=i.features?.streamAnimation;if(Wo?.type&&Wo.type!==`none`){let e=Uo(Wo.type,Wo.plugins);e&&Wt(e,t),Z.push(()=>zt(t))}let Go=Ao(En),Jo=Ao(wn),Xo=Ao(Tn),Zo=[Go,Jo,Xo];Z.push(()=>{Zo.forEach(e=>e.destroy())});let Qo=null,Q,$o=null,es=!1,ts=0,ns=null,rs=e=>e.reduce((e,t)=>t.role===`user`?e+1:e,0),is=e=>{for(let t=e.length-1;t>=0;t--)if(nt(e[t]))return e[t].id??null;return null},as=!1,os=()=>{as||i.debug!==!0||(as=!0,console.warn(`[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".`))},ss=!1,cs=!1,ls=(e,t)=>{ss||i.debug!==!0||t.enabled&&!t.expose&&(es||cs&&(Q.isStreaming()||e.some(nt)||(ss=!0,console.info(`[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.`))))},us=e=>{if(!Q)return;let t=e??Q.getMessages(),n=e=>{e.render([],Q,H,t)},r=e=>{Zo.forEach(t=>{t!==e&&n(t)})};$o&&(rs(t)>ts||is(t)!==ns)&&($o=null);let a=et(i);ls(t,a);let o=a.enabled?tt(t):null,s=$o??o,c=$o?`host`:`agent`;if(s){let e=i.suggestions?.followUps,n=e?.placement??(e?`auto`:`composer`),a=(n===`auto`?P()?`composer`:`after-message`:n)===`after-message`?Xo:Go;r(a),a.render(s,Q,H,t,i.suggestionChipsConfig,{source:c,surface:`followUp`,variant:e?.variant??`chip`,behavior:e?.behavior??`send`,overflow:e?.overflow??`wrap`,maxItems:e?.maxItems??4,config:i,plugins:f,submitPrompt:Tf});return}if(t.some(e=>e.role===`user`)){Zo.forEach(n);return}let l=i.future?.v5Defaults===!0,u=br(),d=i.suggestions?.starters??(l?{}:void 0);if(d){let e=Vs(xr(),t),a=d.placement??`auto`,o=a===`auto`?e?`welcome`:`composer`:a;if(o===`welcome`&&!e){os(),Zo.forEach(n);return}let s=o===`welcome`?Jo:Go;r(s),s.render(d.items??i.suggestionChips,Q,H,t,i.suggestionChipsConfig,{surface:`starter`,variant:d.variant??(l&&!u?`chip`:`card`),behavior:d.behavior??`send`,overflow:d.overflow??`wrap`,maxItems:d.maxItems??(l&&!u?3:4),config:i,plugins:f,submitPrompt:Tf})}else r(Go),Go.render(i.suggestionChips,Q,H,t,i.suggestionChipsConfig,{surface:`starter`,variant:`chip`,behavior:`send`,overflow:`wrap`,maxItems:4,config:i,plugins:f,submitPrompt:Tf})},fs=()=>{$o&&($o=null,us())},ps=e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length){fs();return}let n=Q?Q.getMessages():[];$o=t,es=!0,ts=rs(n),ns=is(n),us(n)},ms=!1,gs=co(),_s=/* @__PURE__ */ new Map,vs=/* @__PURE__ */ new Map,ys=/* @__PURE__ */ new Map,bs=null,Ss=null;function Cs(){if(!bs)return;let e=bs;bs=null,Ss?.destroy(),Ss=null,gs.delete(e),z.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),Q&&Bl(V,Q.getMessages(),lt)}let Es=0,Ds=Re()!==null,Os=It(),js=0,Ns=null,Is=!1,Ls=!1,Rs=0,Hs=null,Ws=null,qs=!1,Js=!1,Ys=null,Xs=!0,Zs=!1,Qs=null,$s=!1,ec=()=>{$s=!0,ic()},tc=null,nc=null,rc=()=>{t.setAttribute(`data-persona-scrollbar`,cr()),cr()!==`on-scroll`&&(nc!==null&&clearTimeout(nc),nc=null,B.removeAttribute(`data-persona-scrollbar-visible`))},ic=()=>{cr()===`on-scroll`&&(B.setAttribute(`data-persona-scrollbar-visible`,``),nc!==null&&clearTimeout(nc),nc=setTimeout(()=>{nc=null,Lt(B,24)&&B.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};rc(),Z.push(()=>{nc!==null&&clearTimeout(nc)});let ac=/* @__PURE__ */ new Map,cc=!1,lc=null,$={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Vi();let pc=i.voiceRecognition?.autoResume??!1,mc=()=>Q.isVoiceActive()||Q.isBargeInActive(),hc=!1,gc=e=>{O.emit(`voice:state`,{active:$.active,source:e,timestamp:Date.now()})},vc=()=>{Ne(e=>({...e,voiceState:{active:$.active,timestamp:Date.now(),manuallyDeactivated:$.manuallyDeactivated}}))},yc=()=>{if(i.voiceRecognition?.enabled===!1)return;let e=Du(pe.voiceState),t=!!e.active,n=Number(e.timestamp??0);$.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-n<3e4&&setTimeout(()=>{$.active||($.manuallyDeactivated=!1,Cn(i.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=mc(),gc(`restore`),$.active?op():(vc(),mf(`Tap the mic to resume your voice call`,1e4))}):np(`restore`))},Cn(i.voiceRecognition?.provider)?0:1e3)},bc=e=>{hc=!e.persisted,$.active&&vc()};typeof window<`u`&&(window.addEventListener(`pagehide`,bc),Z.push(()=>window.removeEventListener(`pagehide`,bc)));let xc=()=>Q?Ou(Q.getMessages()).filter(e=>!e.__skipPersist):[],wc=null,Tc=(e,t)=>{typeof console<`u`&&console.error(e,t)},Ec=(e,t)=>{let n=()=>{try{let n=e();return!n||typeof n.then!=`function`?null:Promise.resolve(n).catch(e=>{Tc(t,e)})}catch(e){return Tc(t,e),null}},r=wc,i=r?r.then(()=>n()??void 0):n();if(!i)return;let a=i.finally(()=>{wc===a&&(wc=null)});wc=a};function Dc(e){if(!fe?.save)return;let t=e?Ou(e):Q?xc():[],n=k&&Q?.getResumableHandle();n&&(pe={...pe,durableResume:{executionId:n.executionId,after:n.lastEventId}});let r={messages:t,metadata:pe,artifacts:xa.artifacts,selectedArtifactId:xa.selectedId,...Ac?{draft:Ac}:{}};Ec(()=>fe.save(r),`[AgentWidget] Failed to persist state:`)}let Ac,jc=()=>!fe?.save||i.persistState===!1?!1:typeof i.persistState!=`object`||i.persistState.persist?.draft!==!1,Nc=Qi({write:()=>{if(!jc())return;let e=J.getState(),t=Xi({text:e.text,mentionRefs:e.mentionRefs,contentSegments:lf(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(Ac)&&(Ac=t,Dc())}});function Pc(){jc()&&Nc.schedule()}function Fc(){Nc.flush()}function Ic(e){if(!jc())return;let t=Zi(e,{mentionSourceIds:(i.contextMentions?.sources??[]).map(e=>e.id),modelIds:(i.composer?.models??[]).map(e=>e.id),modes:i.composer?.modes??[]});t&&(Ac=e,H&&!H.value&&(H.value=t.text,H.dispatchEvent(new Event(`input`,{bubbles:!0})),Ir()),t.selectedModelId&&(J.setSelectedModelId(t.selectedModelId),Gr?.repaint()),Ur(t.activeModeIds??[]),t.quote&&Zr(t.quote),Nc.cancel())}function Lc(){Nc.cancel(),Ac&&(Ac=void 0,jc()&&Dc())}let Rc=null,zc=()=>I.querySelector(`#persona-scroll-container`)||B,Bc=()=>{Rc!==null&&(cancelAnimationFrame(Rc),Rc=null),Is=!1},Gc=()=>{Ns!==null&&(cancelAnimationFrame(Ns),Ns=null),Ls=!1,Bc()},Kc=()=>ms&&el()&&(tr()!==`anchor-top`||or()),qc=()=>{let e=Zn()||`Jump to latest`,t=Kc();lr.toggleAttribute(`data-persona-scroll-to-bottom-streaming`,t),Rs>0?(mr.textContent=String(Rs),mr.style.display=``,lr.setAttribute(`aria-label`,`${e} (${Rs} new)`)):(mr.textContent=``,mr.style.display=`none`,lr.setAttribute(`aria-label`,t?`${e} (response streaming below)`:e))},Jc=()=>{Rs!==0&&(Rs=0,qc())},$c=()=>{let e=Hs?.spacerHeight??0;return e<=0?Lt(B,24):ml(e)-B.scrollTop-B.clientHeight<=24},el=()=>nr()?!Os.isFollowing():!$c(),tl=()=>!!Q&&Q.getMessages().length>0,nl=()=>{if(!er()||pn()){lr.parentNode&&lr.remove(),lr.style.display=`none`;return}lr.parentNode!==z&&z.appendChild(lr),Or();let e=Mt(B)>0&&el()&&tl();e?qc():Jc(),lr.style.display=e?``:`none`},rl=()=>{Os.pause()&&(Gc(),nl())},il=()=>{Os.resume(),Jc(),nl()},al=(e=!1)=>{nr()&&tl()&&Os.isFollowing()&&(e||ms)&&(Ns!==null&&(cancelAnimationFrame(Ns),Ns=null),Ls=!0,Ns=requestAnimationFrame(()=>{Ns=null,Ls=!1,Os.isFollowing()&&sl(zc(),e?220:140)}))},ol=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(Bc(),Math.abs(o)<1){Is=!0,e.scrollTop=a,js=e.scrollTop,Is=!1;return}let s=performance.now();Is=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){Bc();return}let d=t();d!==a&&(a=d,o=a-i);let f=u-s,p=Math.min(f/n,1),m=c(p);e.scrollTop=i+o*m,js=e.scrollTop,p<1?Rc=requestAnimationFrame(l):(e.scrollTop=a,js=e.scrollTop,Rc=null,Is=!1)};Rc=requestAnimationFrame(l)},sl=(e,t=500)=>{let n=Mt(e)-e.scrollTop;Math.abs(n)<1?js=e.scrollTop:Math.abs(n)>=80?(Bc(),Is=!0,e.scrollTop=Mt(e),js=e.scrollTop,Is=!1):ol(e,()=>Mt(e),t,()=>Os.isFollowing())},cl=()=>{if(!tl()){nl();return}let e=zc();Is=!0,e.scrollTop=Mt(e),js=e.scrollTop,Is=!1,nl()},ll=e=>{let t=0,n=e;for(;n&&n!==B;)t+=n.offsetTop,n=n.offsetParent;return t},ul=()=>{let e=B.getRootNode();return(typeof e.getSelection==`function`?e.getSelection():null)??B.ownerDocument.getSelection()},dl=()=>At(ul(),B),fl=()=>{if(ir()!==`last-user-turn`)return!1;let e=Q?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>e.role===`user`);if(!t)return!1;let n=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(t.id):t.id.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),r=B.querySelector(`[data-message-id="${n}"]`);if(!r)return!1;let i=Math.min(Math.max(0,ll(r)-rr()),Mt(B));return Is=!0,B.scrollTop=i,js=B.scrollTop,Is=!1,tr()===`follow`&&!Lt(B,24)&&Os.pause(),nl(),!0},pl=e=>{let t=Math.max(0,Math.round(e));hr.style.height=`${t}px`,hr.style.display=t>0?``:`none`,Hs&&(Hs.spacerHeight=Math.max(0,e))},ml=e=>{let t=parseFloat(getComputedStyle(B).paddingBottom)||0,n=0;for(let e of Array.from(B.children)){if(e===hr||e.offsetHeight===0)continue;let t=ll(e)+e.offsetHeight;t>n&&(n=t)}let r=B.scrollHeight-e;return n>0?Math.min(n+t,r):r},hl=()=>{if(!Hs||Hs.spacerHeight<=0)return;let e=ml(Hs.spacerHeight),t=Math.max(0,Math.round(B.scrollTop)+B.clientHeight-e+24);t<Hs.spacerHeight&&(pl(t),nl())},gl=()=>{Ws!==null&&(cancelAnimationFrame(Ws),Ws=null),Bc(),Hs=null,hr.style.height=`0px`,hr.style.display=`none`},_l=e=>typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),vl=e=>B.querySelector(`[data-message-id="${_l(e)}"]`),yl=e=>{Ws!==null&&cancelAnimationFrame(Ws),Ws=requestAnimationFrame(()=>{Ws=null;let t=_l(e),n=B.querySelector(`[data-message-id="${t}"]`);if(!n)return;let r=ll(n),i=Hs?.spacerHeight??0,a=ml(i),{targetScrollTop:o,spacerHeight:s}=Rt({anchorOffsetTop:r,topOffset:rr(),viewportHeight:B.clientHeight,contentHeight:a,slack:24});Hs={initialSpacerHeight:s,contentHeightAtAnchor:a,spacerHeight:s},pl(s),ol(B,()=>n.isConnected?Math.max(0,ll(n)-rr()):o,220)})},bl=()=>{if(tr()!==`anchor-top`||!Hs||!Qs)return;let e=vl(Qs);if(!e)return;Bc();let t=Hs.spacerHeight,n=ml(t),{targetScrollTop:r,spacerHeight:i}=Rt({anchorOffsetTop:ll(e),topOffset:rr(),viewportHeight:B.clientHeight,contentHeight:n,slack:24});Hs={initialSpacerHeight:i,contentHeightAtAnchor:n,spacerHeight:i},pl(i),Is=!0,B.scrollTop=r,js=B.scrollTop,Is=!1,nl()},Sl=()=>{if(nr()){if(!Os.isFollowing()||Lt(B,1))return;al(!ms)}else{if(Hs&&Hs.initialSpacerHeight>0){let e=B.scrollHeight-Hs.spacerHeight,t=Pt({initialSpacerHeight:Hs.initialSpacerHeight,contentHeightAtAnchor:Hs.contentHeightAtAnchor,currentContentHeight:e});t!==Hs.spacerHeight&&pl(t)}nl()}},Cl=e=>{let t=tr();t===`follow`?(il(),al(!0)):t===`anchor-top`&&(Xs=!1,Zs=!0,$s=!1,Qs=e,yl(e))},wl=()=>{tr()===`anchor-top`&&(Zs?Xs=!1:(Xs=!0,gl(),il(),al(!0)))},Tl=e=>{if(Ys===null)return!0;let t=vl(Ys),n=vl(e);if(!t||!n)return!0;let r=ll(n)-ll(t);return rr()+r>B.clientHeight-96},Ol=e=>{if(tr()!==`anchor-top`||!Zs||$s||dl())return;let t=Ys===null;for(let n of e)if(!t)n.id===Ys&&(t=!0);else if(Ft(n)){if(n.id===Qs||!Tl(n.id))return;Qs=n.id,yl(n.id);return}},kl=e=>{let t=/* @__PURE__ */ new Map;e.forEach(e=>{let n=ac.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!n&&e.role===`assistant`&&(O.emit(`assistant:message`,e),!Js&&(tr()!==`anchor-top`||or())&&el()&&(Rs+=1,qc(),nl(),yr(Rs===1?`1 new message below.`:`${Rs} new messages below.`))),e.role===`assistant`&&n?.streaming&&e.streaming===!1&&O.emit(`assistant:complete`,e),e.variant===`approval`&&e.approval&&(n?e.approval.status!==`pending`&&O.emit(`approval:resolved`,{approval:e.approval,decision:e.approval.status}):O.emit(`approval:requested`,{approval:e.approval,message:e}))}),ac.clear(),t.forEach((e,t)=>{ac.set(t,e)})},Al=(e,t)=>{let n=t===`user`?`user`:`assistant`,r=i.layout?.messages?.[n],a=r?.width??`content`,o=r?.maxWidth??(a===`full`?`var(--persona-message-${n}-max-width, 100%)`:void 0);e.classList.add(`persona-message-row`),e.classList.remove(`persona-message-row-user`,`persona-message-row-assistant`,`persona-message-row-system`,`persona-message-width-content`,`persona-message-width-full`),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${a}`),e.classList.toggle(`persona-justify-end`,t===`user`),e.setAttribute(`data-message-role`,t),e.setAttribute(`data-message-width`,a),o?e.style.setProperty(`--persona-message-row-max-width`,o):e.style.removeProperty(`--persona-message-row-max-width`)},jl=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),Al(n,t),n},Fl=(e,t,n)=>{let r=/* @__PURE__ */ new Set;for(let e of t){let t=e.variant===`tool`?`tool`:e.variant===`reasoning`?`reasoning`:null;if(!t||yn(i,t)!==`row`)continue;let n=t===`tool`?i.features?.toolCallDisplay:i.features?.reasoningDisplay;n?.expandable!==!1&&(r.add(e.id),c.observe(e,t,t===`tool`?o:s,n))}let u=document.createElement(`div`),d=(()=>{let e=f.find(e=>e.renderLoadingIndicator);if(e?.renderLoadingIndicator)return e.renderLoadingIndicator;if(i.loadingIndicator?.render)return i.loadingIndicator.render})(),p=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),m=/* @__PURE__ */ new Set,h=/* @__PURE__ */ new Map,g=/* @__PURE__ */ new Set,_=f.some(e=>e.renderAskUserQuestion),y=[],b=[],S=i.enableComponentStreaming!==!1,C=i.approval!==!1,w=[],T=i.messageActions,E=T?.showRegenerate===!0&&T.enabled!==!1&&ka.current?.isStreaming()!==!0?Er(t):null,D=T?.showEdit===!0&&T.enabled!==!1,ee=T?.showQuote===!0&&T.enabled!==!1,te=null,ne=i.features?.reasoningDisplay?.completedVisibility,ie=e=>ne===`removed`||ne===`removed-when-short`&&a(e,i.features?.reasoningDisplay?.shortThinkThreshold),ae=i.features?.toolCallDisplay?.completedVisibility===`removed`,oe=e=>e.variant===`reasoning`&&e.reasoning?.status===`complete`?ie(e.reasoning):ae&&e.variant===`tool`&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;if(t.forEach(t=>{if(oe(t))return;if(m.add(t.id),h.set(t.id,t.role),bs===t.id&&Ss){let e=jl(t.id,t.role);e.setAttribute(`data-persona-message-edit-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(e),te={messageId:t.id,element:Ss.element};return}let r=_&&Qe(t),a=C&&t.variant===`approval`&&!!t.approval,c=!r&&t.role===`assistant`&&!t.variant&&S&&mu(t);!a&&ys.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),ys.delete(t.id)),!c&&vs.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),vs.delete(t.id));let p=Qe(t)?`:${t.agentMetadata?.askUserQuestionAnswered?`a`:`u`}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:``,T={canRegenerate:E===t.id,canEdit:D&&Dr(t),canQuote:ee&&!t.variant&&(t.content?.trim().length??0)>0},ne=`${T.canRegenerate?`r`:``}${T.canEdit?`e`:``}${T.canQuote?`q`:``}`,ie=so(t,Es)+p+`:${ne}`,ae=r||a||c?null:lo(gs,t.id,ie);if(ae){u.appendChild(ae.cloneNode(!0)),Qe(t)&&t.toolCall?.id&&t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(g.add(t.toolCall.id),Ma(t));return}let O=null,ce=f.find(e=>!!(t.variant===`reasoning`&&e.renderReasoning||t.variant===`tool`&&e.renderToolCall||!t.variant&&e.renderMessage)),le=i.layout?.messages;if(Qe(t)&&t.agentMetadata?.askUserQuestionAnswered===!0){_s.delete(t.id),e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`);return}if(nt(t)&&et(i).enabled)return;if(Qe(t)&&i.features?.askUserQuestion?.enabled!==!1){let e=f.find(e=>typeof e.renderAskUserQuestion==`function`);if(e&&ka.current){let n=_s.get(t.id),r=n!==ie,a=null;if(r){let{payload:n,complete:r}=$e(t),o=t.id,s=()=>ka.current?.getMessages().find(e=>e.id===o);a=e.renderAskUserQuestion({message:t,payload:n,complete:r,resolve:e=>{let t=s();t&&ka.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(ka.current?.markAskUserQuestionResolved(e),ka.current?.resolveAskUserQuestion(e,`(dismissed)`))},config:i})}if(r&&a===null&&n==null){t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(g.add(t.toolCall.id),Ma(t));return}let o=jl(t.id,t.role);o.setAttribute(`data-ask-plugin-stub`,`true`),o.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(o),y.push({messageId:t.id,fingerprint:ie,bubble:a});return}t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(g.add(t.toolCall.id),Ma(t));return}if(a){let n=re();if(!n){u.appendChild(jl(t.id,t.role));return}let r=f.find(e=>typeof e.renderApproval==`function`)??x,a=ys.get(t.id)!==ie,o=null;if(a&&r?.renderApproval){let e=t.id,a=(t,n)=>{let r=ka.current?.getMessages().find(t=>t.id===e);r?.approval&&(v(r.approval)?ka.current?.resolveWebMcpApproval(r.id,t):ka.current?.resolveApproval(r.approval,t,n))};o=r.renderApproval({message:t,defaultRenderer:()=>n.createApprovalBubble(t,i,l),config:i,approve:e=>a(`approved`,e),deny:e=>a(`denied`,e)})}if(a&&o===null)e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),ys.delete(t.id),O=n.createApprovalBubble(t,i,l);else{let e=jl(t.id,t.role);e.setAttribute(`data-approval-plugin-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(e),w.push({messageId:t.id,fingerprint:ie,bubble:o});return}}else if(ce){if(t.variant===`reasoning`&&t.reasoning&&ce.renderReasoning){if(!ut)return;O=ce.renderReasoning({message:t,defaultRenderer:()=>fc(t,i,s),config:i})}else if(t.variant===`tool`&&t.toolCall&&ce.renderToolCall){if(!dt)return;O=ce.renderToolCall({message:t,defaultRenderer:()=>Cc(t,i,o),config:i})}else ce.renderMessage&&(O=ce.renderMessage({message:t,defaultRenderer:()=>{let e=xs(t,n,le,i.messageActions,mn,{loadingIndicatorRenderer:d,widgetConfig:i,actionEligibility:T});return t.role!==`user`&&se(e,t,i,Q),e},config:i}))}if(!O&&c){let r=hu(t);if(r){let a=vs.get(t.id),o=a!==ie,s=i.wrapComponentDirectiveInBubble!==!1&&Ge.getOptions(r.component)?.bubbleChrome!==!1,c=null;if(o){let a=fu(r,{config:i,message:t,transform:n});if(a&&r.component===`PersonaArtifactInline`){let n=a.hasAttribute(`data-artifact-inline`)?a:a.querySelector(`[data-artifact-inline]`),r=n?.getAttribute(`data-artifact-inline`)??``,i=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(r):r,o=r?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${i}"]`)??null:null;n&&o&&o!==n&&Hc()?.hasLiveInlineArtifactBlock(o)&&(n===a?a=o:n.replaceWith(o))}if(a){if(s){let e=document.createElement(`div`);if(e.className=[`persona-message-bubble`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-p-4`].join(` `),e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-mb-3 persona-text-sm persona-leading-relaxed`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}else{let e=document.createElement(`div`);if(e.className=`persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch`,e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),e.setAttribute(`data-persona-component-directive`,`true`),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}}}if(c||a!=null){let e=jl(t.id,t.role);e.setAttribute(`data-component-directive-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),u.appendChild(e),b.push({messageId:t.id,fingerprint:ie,bubble:c});return}}}if(!O){if(t.variant===`reasoning`&&t.reasoning){if(!ut)return;O=fc(t,i,s)}else if(t.variant===`tool`&&t.toolCall){if(!dt)return;O=Cc(t,i,o)}else if(t.variant===`approval`&&t.approval){if(i.approval===!1)return;let e=re();if(!e)return;O=e.createApprovalBubble(t,i,l)}else{let e=i.layout?.messages;O=e?.renderUserMessage&&t.role===`user`?e.renderUserMessage({message:t,config:i,streaming:!!t.streaming}):e?.renderAssistantMessage&&t.role===`assistant`?e.renderAssistantMessage({message:t,config:i,streaming:!!t.streaming}):xs(t,n,e,i.messageActions,mn,{loadingIndicatorRenderer:d,widgetConfig:i,actionEligibility:T}),t.role!==`user`&&O&&se(O,t,i,Q)}}let ue=jl(t.id,t.role);ue.appendChild(O),uo(gs,t.id,ie,ue),u.appendChild(ue)}),R.composerOverlay&&R.composerOverlay.querySelectorAll(`[data-persona-ask-sheet-for]`).forEach(e=>{let t=e.getAttribute(`data-persona-ask-sheet-for`);t&&!g.has(t)&&Xe(R.composerOverlay,t)}),i.features?.toolCallDisplay?.grouped){let e=[],n=[],a=i.features.toolCallDisplay.groupedMode===`summary`;t.forEach(t=>{if(t.variant===`tool`&&t.toolCall&&dt){if(ae&&t.toolCall.status===`complete`&&!t.toolCall.interrupted)return;n.push(t)}else(t.variant!==`reasoning`||ut&&(t.reasoning?.status!==`complete`||!ie(t.reasoning)))&&((n.length>1||a&&n.length>0)&&e.push(n),n=[])}),(n.length>1||a&&n.length>0)&&e.push(n),e.forEach(e=>{let t=e.map(e=>Array.from(u.children).find(t=>t instanceof HTMLElement&&t.getAttribute(`data-wrapper-id`)===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let n=jl(`tool-group-${e[0].id}`,`assistant`);if(n.setAttribute(`data-persona-tool-group-row`,`true`),i.features?.toolCallDisplay?.groupedMode===`collapsible`){let a=`tool-group-${e[0].id}`,s=e.some(e=>e.toolCall?.status!==`complete`),l={...e[0],id:a,toolCall:{id:a,name:`${e.length} tools`,status:s?`running`:`complete`,chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>e.toolCall?.success===!1),interrupted:!s&&e.some(e=>e.toolCall?.interrupted)}};r.add(a),c.observe(l,`tool`,o,i.features.toolCallDisplay);let u=l.toolCall?.interrupted?`${e.length} tools · Interrupted`:`${s?`Using`:`Used`} ${e.length} tools`,d=i.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:u,config:i}),f=Sn(l,i,o.has(a),d??u);f.bubble.classList.add(`persona-tool-group`),f.body.dataset.personaToolGroupStack=`true`,t[0].before(n),n.appendChild(f.bubble),t.forEach((e,t)=>{e.style.setProperty(`--persona-message-row-max-width`,`100%`),e.style.setProperty(`--persona-activity-stagger`,`${t*40}ms`),e.classList.add(`persona-activity-group-child`),f.body.appendChild(e)});return}let s=document.createElement(`div`);s.className=`persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2`,s.setAttribute(`data-persona-tool-group`,`true`);let l=document.createElement(`div`);l.className=`persona-tool-group-summary persona-text-xs persona-text-persona-muted`,l.id=`tool-group-summary-${e[0].id}`;let d=`${e.length} ${e.length===1?`tool`:`tools`}`,f=e.some(e=>e.toolCall?.interrupted)?`${d} · Interrupted`:`Called ${d}`,m=i.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:f,config:i});p(l,m)||(l.textContent=f);let h=document.createElement(`div`);h.className=`persona-tool-group-stack persona-flex persona-flex-col`,h.id=`tool-group-stack-${e[0].id}`,h.setAttribute(`data-persona-tool-group-stack`,`true`),s.appendChild(l),a||s.appendChild(h),n.appendChild(s),t[0].before(n),t.forEach((e,n)=>{if(a){e.remove();return}e.style.setProperty(`--persona-message-row-max-width`,`100%`);let r=document.createElement(`div`);r.className=`persona-tool-group-item persona-relative`,r.setAttribute(`data-persona-tool-group-item`,`true`),n<t.length-1&&r.setAttribute(`data-persona-tool-group-connector`,`true`),r.appendChild(e),h.appendChild(r)})})}c.prune(r),fo(gs,m);let O=e=>e.variant===`tool`&&!dt||e.variant===`reasoning`&&!ut||oe(e),ce=t.some(e=>e.role===`assistant`&&e.streaming&&!O(e)),le=t.length-1;for(;le>=0&&O(t[le]);)le--;let ue=le>=0?t[le]:void 0,de=le<t.length-1,fe=ue?.role===`assistant`&&!ue.streaming&&ue.variant!==`approval`&&!de;if(ms&&t.some(e=>e.role===`user`)&&!ce&&!fe){let e={config:i,streaming:!0,location:`standalone`,defaultRenderer:ds},t=f.find(e=>e.renderLoadingIndicator),n=null;if(t?.renderLoadingIndicator&&(n=t.renderLoadingIndicator(e)),n===null&&i.loadingIndicator?.render&&(n=i.loadingIndicator.render(e)),n===null&&(n=ds()),n){let e=document.createElement(`div`),t=i.loadingIndicator?.showBubble!==!1,r=i.layout?.messages?.layout??`bubble`;e.className=t?hs(`assistant`,r).join(` `):[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-text`].join(` `),e.setAttribute(`data-typing-indicator`,`true`),t&&(e.style.color=`var(--persona-message-assistant-text, var(--persona-text))`,r!==`flat`&&(e.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,e.style.borderColor=`var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))`)),e.appendChild(n);let a=jl(`typing-indicator`,`assistant`);a.appendChild(e),u.appendChild(a)}}if(!ms&&t.length>0){let e=t[t.length-1],n={config:i,lastMessage:e,messageCount:t.length},r=f.find(e=>e.renderIdleIndicator),a=null;if(r?.renderIdleIndicator&&(a=r.renderIdleIndicator(n)),a===null&&i.loadingIndicator?.renderIdle&&(a=i.loadingIndicator.renderIdle(n)),a){let e=document.createElement(`div`);e.className=i.loadingIndicator?.showBubble===!1?[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-primary`].join(` `):[`persona-rounded-2xl`,`persona-text-sm`,`persona-leading-relaxed`,`persona-shadow-sm`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-primary`,`persona-px-5`,`persona-py-3`].join(` `),e.setAttribute(`data-idle-indicator`,`true`),e.appendChild(a);let t=jl(`idle-indicator`,`assistant`);t.appendChild(e),u.appendChild(t)}}if(An(u),ro(e,u),Mn(e),te){let{messageId:t,element:n}=te,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(Al(r,h.get(t)??`user`),r.replaceChildren(n))}if(y.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of y){let i=e.querySelector(`#wrapper-${t}`);i&&(Al(i,h.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),_s.set(t,n)))}if(_s.size>0)for(let e of _s.keys())m.has(e)||_s.delete(e);if(b.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of b){let i=e.querySelector(`#wrapper-${t}`);i&&(Al(i,h.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),vs.set(t,n)))}if(vs.size>0)for(let e of vs.keys())m.has(e)||vs.delete(e);if(w.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of w){let i=e.querySelector(`#wrapper-${t}`);i&&(Al(i,h.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),ys.set(t,n)))}if(ys.size>0)for(let e of ys.keys())m.has(e)||ys.delete(e)},Il=!1,Ll=()=>{Il||(Il=!0,In().catch(()=>{}),Ue().catch(()=>{Il=!1}))},Bl=(e,t,n)=>{t.length>0&&Ll(),Fl(e,t,n),ma()},Vl=null,Ul=()=>{if(Vl)return;let e=e=>{let t=e.composedPath();t.includes(I)||vn&&t.includes(vn)||ou(!1,`user`)};Vl=e,(t.ownerDocument??document).addEventListener(`pointerdown`,e,!0)},Gl=()=>{Vl&&=((t.ownerDocument??document).removeEventListener(`pointerdown`,Vl,!0),null)};Z.push(()=>Gl());let ql=null,Jl=()=>{if(ql)return;let e=e=>{e.key===`Escape`&&(e.isComposing||ou(!1,`user`))};ql=e,(t.ownerDocument??document).addEventListener(`keydown`,e,!0)},Yl=()=>{ql&&=((t.ownerDocument??document).removeEventListener(`keydown`,ql,!0),null)};Z.push(()=>Yl());let Ql=!1,$l=/* @__PURE__ */ new Set,eu=()=>i.launcher?.composerBar?.peek?.streamAnimation||i.features?.streamAnimation,nu=()=>{if(!P())return;let e=R.peekBanner,n=R.peekTextNode;if(!e||!n)return;if(F){e.classList.remove(`persona-pill-peek--visible`);return}let r=Q?.getMessages()??[],i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.role===`assistant`&&t.content){i=t;break}}if(!i){e.classList.remove(`persona-pill-peek--visible`);return}let a=i.content,o=!!i.streaming,s=eu(),c=Bt(s),l=c.type===`none`?null:Uo(c.type,s?.plugins),u=l?.isAnimating?.(i)===!0,d=l!==null&&(o||u);d&&l&&!$l.has(l.name)&&(Wt(l,t),$l.add(l.name));let f=d&&l?.containerClass?l.containerClass:null,p=n.dataset.personaPeekStreamClass??null;p&&p!==f&&(n.classList.remove(p),delete n.dataset.personaPeekStreamClass),f&&p!==f&&(n.classList.add(f),n.dataset.personaPeekStreamClass=f),d?(n.style.setProperty(`--persona-stream-step`,`${c.speed}ms`),n.style.setProperty(`--persona-stream-duration`,`${c.duration}ms`)):(n.style.removeProperty(`--persona-stream-step`),n.style.removeProperty(`--persona-stream-duration`));let m=d?Ut(a,c.buffer,l,i,o):a;if(d&&c.placeholder===`skeleton`&&o&&(!m||!m.trim())){let e=document.createElement(`div`),t=Gt();t.classList.add(`persona-pill-peek__skeleton`),e.appendChild(t),ro(n,e)}else{let t=Math.max(0,m.length-100),r=m.length>100?m.slice(-100):m,a=Le(r);if(!d||!l){let e=m.length>100?`…${r}`:r;n.textContent!==e&&(n.textContent=e)}else{let o=a;(l.wrap===`char`||l.wrap===`word`)&&(o=Jt(a,l.wrap,`peek-${i.id}`,{skipTags:l.skipTags,startIndex:t}));let s=document.createElement(`div`);if(s.innerHTML=o,l.useCaret&&r.length>0){let e=Vt(),t=s.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];n?.parentNode?n.parentNode.insertBefore(e,n.nextSibling):s.appendChild(e)}ro(n,s),l.onAfterRender?.({container:n,bubble:e,messageId:i.id,message:i,speed:c.speed,duration:c.duration})}}let h=ms||Ql;e.classList.toggle(`persona-pill-peek--visible`,h)};if(P()){let e=R.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),ou(!0,`user`)};e.addEventListener(`pointerdown`,t),Z.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{Ql||(Ql=!0,nu())},n=()=>{Ql&&(Ql=!1,nu())};L.addEventListener(`pointerenter`,t),L.addEventListener(`pointerleave`,n),Z.push(()=>{L.removeEventListener(`pointerenter`,t),L.removeEventListener(`pointerleave`,n)}),vn&&(vn.addEventListener(`pointerenter`,t),vn.addEventListener(`pointerleave`,n),Z.push(()=>{vn.removeEventListener(`pointerenter`,t),vn.removeEventListener(`pointerleave`,n)}))}let ru=e=>{let t=i.launcher?.composerBar??{},n=t.expandedSize??`anchored`,r=t.bottomOffset??`16px`,a=t.collapsedMaxWidth,o=t.expandedMaxWidth??`880px`,s=t.expandedTopOffset??`5vh`,c=t.modalMaxWidth??`880px`,l=t.modalMaxHeight??`min(90vh, 800px)`,u=`calc(100vw - 32px)`,d=I.style;if(d.left=``,d.right=``,d.top=``,d.bottom=``,d.transform=``,d.width=``,d.maxWidth=``,d.height=``,d.maxHeight=``,vn){let e=vn.style;e.bottom=r,e.width=a??``}e&&n!==`fullscreen`&&(n===`modal`?(d.top=`50%`,d.left=`50%`,d.transform=`translate(-50%, -50%)`,d.bottom=`auto`,d.right=`auto`,d.width=c,d.maxWidth=u,d.maxHeight=l,d.height=l):(d.left=`50%`,d.transform=`translateX(-50%)`,d.bottom=`calc(${r} + var(--persona-pill-area-height, 80px))`,d.top=s,d.width=o,d.maxWidth=u))},au=()=>{if(F&&Ll(),!it())return;if(P()){let e=(i.launcher?.composerBar??{}).expandedSize??`anchored`,t=F?`expanded`:`collapsed`;I.dataset.state=t,I.dataset.expandedSize=e,vn&&(vn.dataset.state=t,vn.dataset.expandedSize=e),I.style.removeProperty(`display`),I.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),L.classList.remove(`persona-scale-95`,`persona-opacity-0`,`persona-scale-100`,`persona-opacity-100`),ru(F),z.style.display=F?`flex`:`none`,va(),F?(Ul(),Jl()):(Gl(),Yl()),nu();return}let e=xo(i),n=t.ownerDocument.defaultView??window,r=i.launcher?.mobileBreakpoint??640,a=i.launcher?.mobileFullscreen??!0,o=n.innerWidth<=r,s=a&&o&&Be,c=Co(i).reveal;F?(I.style.removeProperty(`display`),I.style.display=e?`flex`:``,I.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),L.classList.remove(`persona-scale-95`,`persona-opacity-0`),L.classList.add(`persona-scale-100`,`persona-opacity-100`),wp?(wp.setPanelOpen(!0),wp.element.style.display=`none`):Tp&&(Tp.style.display=`none`)):(e?e&&(c===`overlay`||c===`push`)&&!s?(I.style.removeProperty(`display`),I.style.display=`flex`,I.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),L.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(I.style.setProperty(`display`,`none`,`important`),I.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),L.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(I.style.display=``,I.classList.add(`persona-pointer-events-none`,`persona-opacity-0`),L.classList.remove(`persona-scale-100`,`persona-opacity-100`),L.classList.add(`persona-scale-95`,`persona-opacity-0`)),wp?(wp.setPanelOpen(!1),wp.element.style.display=e?`none`:``):Tp&&(Tp.style.display=e?`none`:``))},ou=(e,n=`user`)=>{if(!it()||F===e)return;let r=F;F=e,au();let a=(()=>{let e=i.launcher?.sidebarMode??!1,n=t.ownerDocument.defaultView??window,r=i.launcher?.mobileFullscreen??!0,a=i.launcher?.mobileBreakpoint??640,o=n.innerWidth<=a,s=xo(i)&&r&&o,c=P()&&(i.launcher?.composerBar?.expandedSize??`fullscreen`)===`fullscreen`;return e||r&&o&&Be||s||c})();if(F&&a){if(!Fo){let e=t.getRootNode(),n=e instanceof ShadowRoot?e.host:t.closest(`.persona-host`);n&&(Fo=go(n,i.launcher?.zIndex??1e5))}Io||=yo(t.ownerDocument)}else F||(Fo?.(),Fo=null,Io?.(),Io=null);F&&(kp(),fl()||(tr()===`follow`?al(!0):cl()));let o={open:F,source:n,timestamp:Date.now()};F&&!r?O.emit(`widget:opened`,o):!F&&r&&O.emit(`widget:closed`,o),O.emit(`widget:state`,{open:F,launcherEnabled:Be,voiceActive:$.active,streaming:Q.isStreaming()})},su={inputDisabled:!1,sendDisabled:!1},cu=()=>su.inputDisabled,pu=()=>Cn(i.voiceRecognition?.provider)&&!!Q&&(Q.isBargeInActive()||[`listening`,`processing`,`speaking`].includes(Q.getVoiceStatus())),gu=()=>su.inputDisabled||su.sendDisabled,Su=()=>(su.inputDisabled?su.inputReason:void 0)??(su.sendDisabled?su.sendReason:void 0);function ju(){if(!U)return;if(J.getState().phase===`streaming`){U.disabled=!1;return}let e=Mr?!Mr.isReady():!1;U.disabled=gu()||e}function Nu(){if(!Wn)return;let e=J.getState(),t=i.sendButton?.visibility===`when-text`&&e.phase!==`streaming`&&e.text.trim().length===0&&e.attachments.length===0;Wn.toggleAttribute(`data-persona-send-hidden`,t)}function Pu(){let e=Su();if(P()){let t=Dn??K;e?t.setAttribute(`title`,e):t.removeAttribute(`title`),K.toggleAttribute(bu,!!e)}else if(e)W.setAttribute(`role`,`status`),W.setAttribute(`aria-live`,`polite`),W.setAttribute(bu,``),W.removeAttribute(xu),W.textContent=e,w(W,i.statusIndicator??{},`idle`);else if(W.hasAttribute(bu)&&(W.removeAttribute(`role`),W.removeAttribute(`aria-live`),W.removeAttribute(bu),g)){let e=Q.getStatus();gn(W,hn(e),i.statusIndicator??{},e)}}function Fu(){let e=de(i.composer?.inputDisabled),t=de(i.composer?.sendDisabled);su={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},J.setInputDisabled(e.disabled),J.setSendDisabled(t.disabled);let n=J.getState().phase===`streaming`,r=e.disabled,a=n||r;H&&(H instanceof HTMLTextAreaElement?H.disabled=r:H.setAttribute(`contenteditable`,r?`false`:`true`),H.setAttribute(`aria-disabled`,r?`true`:`false`)),qn&&(qn.disabled=r),Yn&&(Yn.disabled=r);for(let e of Nr?.affordanceButtons??[])e.querySelectorAll(`button`).forEach(e=>{e.disabled=r});q&&(q.disabled=r||n&&!pu()),Zo.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement||e.setAttribute(`aria-disabled`,a?`true`:`false`)}),e.buttons.forEach(e=>{e.disabled=a})}),Qu.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute(`aria-disabled`,a?`true`:`false`),e.querySelectorAll(`button`).forEach(e=>{e.disabled=a})}),K.dataset.personaComposerStreaming=n?`true`:`false`,K.dataset.personaComposerInputDisabled=r?`true`:`false`,K.dataset.personaComposerSendDisabled=gu()?`true`:`false`,K.querySelectorAll(`[data-persona-composer-disable-when-streaming]`).forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=n)}),ju(),Pu()}let Iu=e=>{J.setStreaming(e),Gn(e?`stop`:`send`),Fu()},Lu=()=>{$.active||H&&H.focus()};O.on(`widget:opened`,()=>{i.autoFocusInput&&setTimeout(()=>Lu(),200)});let Ru=null,zu=!1,Bu=!On.hidden,Vu=null,Hu=!_e,Uu=null;Z.push(()=>{Uu?.cancel(),Uu=null});let Wu=e=>{let n=Bs(e);if(n===Sr)return;Sr=n,t.setAttribute(`data-persona-conversation-state`,n);let r=wr();Ar(),Hu&&(Uu?.cancel(),Uu=Fs(K,n===`active`?r:wr(),n===`active`?`drop`:`rise`,xr().layout===`centered`?320:260)),bl()},Gu=null,Ku,qu=null,Ju=null,Yu=!1,Xu=e=>{let t=xr(),n=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??`bottom`}|${t.align??``}|${t.iconPlacement}|${t.kicker??``}|${t.title}|${t.subtitle}`;(n!==Gu||t.icon!==Ku)&&(Gu=n,Ku=t.icon,Ts({host:On,iconHolder:kn,kicker:Nn,title:Pn,subtitle:Fn,starterSuggestions:wn},t));let r=t.message===void 0?null:`${i.layout?.messages?.layout??`bubble`}|${t.message}`;r!==qu&&(qu=r,Ms(jn,t.message,i));let a=e??(Q?Q.getMessages():i.initialMessages);Wu(a);let o=zu,s=!o&&Vs(t,a),c=s!==Bu;if(Bu=s,Ju){Vu?.cancel(),Vu=null,o!==Yu&&(Yu=o,o?As(B,On,null):ks(B,On,Ju)),ws(B,On,!o);return}if(c&&!s&&!o&&t.dismiss===`on-first-message`&&Hu){Vu=Ps(On,e=>{Vu===e&&(Vu=null),!Bu&&!Ju&&(ws(B,On,!1),bl()),e?.cancel()});return}if(Vu){if(!s&&!o)return;Vu.cancel(),Vu=null}let l=!On.hidden;ws(B,On,s),!s&&l&&bl()},Zu=[],Qu=[],$u=!1,ed=null,td,nd=()=>{Qu.length=0;let e=Zu.splice(0,Zu.length);for(let t of e)try{t()}catch(e){console.warn(`[persona] renderWelcome cleanup threw`,e)}};Z.push(nd);let rd=(e,t)=>{let n=To(e,t);if(!n)return i.debug===!0&&console.warn(`[persona] renderStarter received a suggestion with no label`),M(`span`);let r=i.suggestions?.starters,a=ko({item:{...n,behavior:n.behavior??r?.behavior??`send`},index:t,surface:`starter`,source:`config`,variant:r?.variant??`card`,streaming:g?Q.isStreaming():!1,config:i,plugins:f,chipsConfig:i.suggestionChipsConfig,session:Q,getTextarea:()=>H,eventTarget:On,submitPrompt:Tf});return Qu.push(a),a},id=()=>{if($u)return;$u=!0;let e=xr();ed=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`,td=e.icon;try{nd(),As(B,On,Ju),Ju=null,Yu=!1;let t=Q?Q.getMessages():i.initialMessages,n=Vs(e,t),r=0,a=null;for(let t of f)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:n,defaultRenderer:()=>On,sendMessage:e=>{if(!Q||Q.isStreaming())return;let t=e.trim();t&&Q.sendMessage(t)},requestRender:()=>id(),renderStarter:e=>rd(e,r++),storage:_(t.id),onCleanup:e=>{Zu.push(e)}}),a))break;a&&a!==On&&(Ju=a,ks(B,On,a))}finally{$u=!1}Xu()},ad=()=>{let e=xr();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`!==ed||e.icon!==td)&&id()},od=()=>{Xu(),hi||(H.placeholder=Gi(J.getState().activeModeIds,i.composer?.modes)??i.copy?.inputPlaceholder??`How can I help...`,!(i.sendButton?.useIcon??!1)&&!Q?.isStreaming()&&(U.textContent=i.copy?.sendButtonLabel??`Send`)),H.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,H.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`},sd=!!i.setStoredConversationId,cd=e=>Ne(t=>{let n={...t};return delete n[e],n}),ld=e=>{let t=pe[e];return typeof t==`string`?t:null},ud=()=>{let e=pe.durableResume;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.executionId==`string`&&t.executionId.length>0&&typeof t.after==`string`&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};i.clientToken&&(i={...i,getStoredSessionId:()=>ld(`sessionId`),setStoredSessionId:e=>{Ne(t=>({...t,sessionId:e}))},clearStoredSessionId:i.clearStoredSessionId??(()=>cd(`sessionId`)),getStoredConversationId:i.getStoredConversationId??(()=>ld(`conversationId`)),setStoredConversationId:i.setStoredConversationId??(e=>{Ne(t=>({...t,conversationId:e}))}),clearStoredConversationId:i.clearStoredConversationId??(()=>cd(`conversationId`))});let dd=()=>i.clientToken??null,fd=e=>tu(e,_t(),i.persistState===!1),pd=dd(),md=pd?fd(pd):null,hd=()=>{let e=pe.pendingDisplayProjections;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.conversationId!=`string`||!Array.isArray(t.messageIds)?null:{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>typeof e==`string`)}},gd={...md?{visitorStore:md}:{},historyBootstrapReady:i.features?.history?.enabled===!0&&!uu()?Promise.all([ye,Se]).then(()=>{}):ye,getStoredMessageCursor:()=>ld(`historyMessageCursor`),setStoredMessageCursor:e=>{e===null?cd(`historyMessageCursor`):Ne(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:hd,setPendingDisplayProjections:e=>{e?Ne(t=>({...t,pendingDisplayProjections:e})):cd(`pendingDisplayProjections`)},getStoredResumableHandle:ud,setStoredResumableHandle:e=>{e?Ne(t=>({...t,durableResume:e})):cd(`durableResume`)},shouldResumeDurableConversation:()=>k&&ud()!==null,...sd?{}:{getStoredConversationRevision:()=>ld(`conversationRevision`),setStoredConversationRevision:e=>{e===null?cd(`conversationRevision`):Ne(t=>({...t,conversationRevision:e}))}}};if(k){let e=i.onExecutionState,n=t.ownerDocument.defaultView,r=!1,a=()=>r=!0,o=()=>r=!1;n?.addEventListener(`pagehide`,a),n?.addEventListener(`pageshow`,o),Z.push(()=>{n?.removeEventListener(`pagehide`,a),n?.removeEventListener(`pageshow`,o)}),i={...i,reconnectStream:i.reconnectStream??(e=>Q.getClient().reconnectClientTokenStream(e)),onExecutionState:t=>{(t||!r)&&gd.setStoredResumableHandle?.(t?{executionId:t.executionId,after:t.lastEventId}:null),e?.(t)}}}let _d=()=>{let e=dd();if(e&&md?.matches(e,_t(),i.persistState===!1)||!e&&!md)return;md?.destroy(),md=e?fd(e):null;let t={...gd};md?t.visitorStore=md:delete t.visitorStore,gd=t,Q.setHistoryInternals(gd)},vd=null,yd=()=>{vd??=setInterval(()=>{let e=V.querySelectorAll(`[data-tool-elapsed]`);if(e.length===0){clearInterval(vd),vd=null;return}let t=Date.now();e.forEach(e=>{let n=Number(e.getAttribute(`data-tool-elapsed`));n&&(e.textContent=e.closest(`.persona-activity-row`)?bn(t-n):h(t-n))})},100)},bd=(e,t)=>{if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>bd(e,t[n]));let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.prototype.hasOwnProperty.call(r,e)&&bd(n[e],r[e]))},xd=e=>{let{content:t,rawContent:n,llmContent:r,...i}=e;return i},Sd=e=>e.role===`assistant`&&e.streaming===!0&&!e.variant&&!e.toolCall&&!e.tools&&!e.approval&&!e.reasoning&&!e.contentParts&&!e.stopReason&&!mu(e),Cd=(e,t,n)=>{if(e.length!==t.length)return!1;let r=e[n.index],i=t[n.index];return!r||!i||r.id!==n.id||i.id!==n.id?!1:(!Object.is(r.content,i.content)||!Object.is(r.rawContent,i.rawContent)||!Object.is(r.llmContent,i.llmContent))&&Sd(r)&&Sd(i)&&bd(xd(r),xd(i))},wd=null,Td=null,Ed=null,Dd=null,Od=null,kd=e=>{if(!k)return Dc(e);Od=e,queueMicrotask(()=>{Od===e&&(Od=null,Dc(e))})},Ad=e=>{wd=e;let t,n;Td=null;for(let r=e.length-1;r>=0;--r){let i=e[r];if(!t&&i.role===`user`&&(t=i),!n&&i.role===`assistant`&&(n=i),!Td&&Sd(i)&&(Td={index:r,id:i.id}),t&&n&&Td)break}Bl(V,e,lt),Hc()?.updateInlineArtifactBlocks(V,xa.artifacts,{suppressTransition:ms}),yd(),Xu(e),us(e),al(!ms),kl(e),e.length===0&&(gl(),Xs=!0,Zs=!1,Qs=null,$s=!1),!qs||Js?(qs=!0,Ys=t?.id??null,tc=n?.id??null):t&&t.id!==Ys?(Ys=t.id,Cl(t.id)):n&&n.id!==tc&&wl(),n&&(tc=n.id),Ol(e);let r=$.lastUserMessageId;t&&t.id!==r&&($.lastUserMessageId=t.id,O.emit(`user:message`,t)),$.lastUserMessageWasVoice=!!t?.viaVoice,kd(e),nu()},jd=()=>{Dd!==null&&(cancelAnimationFrame(Dd),Dd=null);let e=Ed;Ed=null,e&&Ad(e)},Md=()=>{Dd!==null&&cancelAnimationFrame(Dd),Dd=null,Ed=null},Nd=e=>{let t=Ed??wd;ms&&t&&Td&&Cd(t,e,Td)?(Ed=e,Dd===null&&(Dd=requestAnimationFrame(()=>{Dd=null;let e=Ed;Ed=null,e&&Ad(e)}))):e.length===0?(Md(),Ad(e)):(jd(),Ad(e))};Q=new Jr(i,{onMessagesChanged(e){Nd(e)},onStatusChanged(e){let t=i.statusIndicator??{};gn(W,(e=>e===`idle`?t.idleText??xt.idle:e===`connecting`?t.connectingText??xt.connecting:e===`connected`?t.connectedText??xt.connected:e===`error`?t.errorText??xt.error:e===`paused`?t.pausedText??xt.paused:e===`resuming`?t.resumingText??xt.resuming:xt[e])(e),t,e),fn()},onStreamingChanged(e){e||(Q?.getMessages().length===0?Md():jd()),ms=e,Iu(e),fn(),Q&&Bl(V,Q.getMessages(),lt),e||(al(!0),hl(),cs=!0,Q&&ls(Q.getMessages(),et(i))),nl(),yr(e?`Responding…`:`Response complete.`),nu()},onVoiceStatusChanged(e){if(O.emit(`voice:status`,{status:e,timestamp:Date.now()}),e!==`disconnected`&&!Cn(i.voiceRecognition?.provider))return;let t=Q.getVoiceNotice();switch(t&&mf(t,1e4),e){case`listening`:if(!cc){let e=Q.getVoiceDisclosure();e&&(cc=!0,P()?(lc=H.placeholder,H.placeholder=e,yr(e)):mf(e,1e4))}lp(),op();break;case`processing`:lp(),sp();break;case`speaking`:lp(),cp();break;default:e===`idle`&&Q.isBargeInActive()?(lp(),op(),q?.setAttribute(`aria-label`,`End voice session`)):($.active=!1,cc=!1,lc!==null&&(H.placeholder=lc,lc=null),lp(),gc(`system`),hc||vc())}},onArtifactsState(e){xa=e,e.artifacts.length===0&&(Ea=!1),Hc()?.updateInlineArtifactBlocks(V,e.artifacts,{suppressTransition:ms}),vo(),Dc()},onHistoryStateChanged(e){un(e)},onHistoryNotice(e){dn(e)},onReconnect(e){let{executionId:t,lastEventId:n}=e.handle;e.phase===`paused`?O.emit(`stream:paused`,{executionId:t,after:n}):e.phase===`resuming`?O.emit(`stream:resuming`,{executionId:t,after:n,attempt:e.attempt??1}):O.emit(`stream:resumed`,{executionId:t,after:n})}},gd),ka.current=Q,Z.push(()=>Q.cancel()),Z.push(()=>{Q.destroy(),md?.destroy(),md=null});let Pd=null;if(Q.onReadAloudChange((e,t)=>{ua=e,da=t,ma();let n=e??Pd;e&&(Pd=e);let r=n?Q.getMessages().find(e=>e.id===n)??null:null;O.emit(`message:read-aloud`,{messageId:n,message:r,state:t,timestamp:Date.now()}),t===`idle`&&(Pd=null)}),g=!0,qs=!0,i.voiceRecognition?.enabled===!0&&Cn(i.voiceRecognition.provider))try{Q.setupVoice()}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Runtype voice setup failed:`,e)}let Fd=null,Id=null,Ld=!1,Rd=Q.getHistoryState(),zd=()=>i.features?.history?.enabled===!0,Bd=e=>{e&&(gr.textContent=``,gr.textContent=e)},Vd=()=>{m.forEach(e=>e()),m=[];let e=Fd,n=e?.railCollapseShortcut();e&&n&&m.push(p.register({id:`history-rail-collapse`,combo:n.combo,scope:i.features?.history?.rail?.collapseShortcutScope===`page`?`page`:`widget`,when:()=>on&&sn===`rail`&&e.railCollapsible()||e.railTriggerApplies(),run:()=>e.railOverlayMode()?e.toggleRailPinned():e.toggleRailCollapsed()}));for(let e of i.layout?.header?.trailingActions??[])e.shortcut&&m.push(p.register({id:`header-action-${e.id}`,combo:e.shortcut,run:()=>{let n=t.querySelector(`[data-persona-header-action="${e.id}"]`);n?n.click():i.layout?.header?.onAction?.(e.id)}}));for(let e of f)for(let t of e.shortcuts??[])m.push(p.register({...t,id:`${e.id}:${t.id}`}))};Vd();let Hd=null,Ud=!1,Wd=()=>{if(!Rn)return;let e=i.layout?.header?.titleSource===`conversation`,t=e&&Hd?.trim()||null;Rn.textContent=t??i.launcher?.title??`Chat Assistant`;let n=Rn.closest(`.persona-combo-btn`);if(!n)return;let r=!e||Q.getActiveConversationId()!==null;n.setAttribute(`data-persona-menu-locked`,r?`false`:`true`),n.setAttribute(`aria-haspopup`,r?`true`:`false`),r||n.setAttribute(`aria-expanded`,`false`),n.style.cursor=r?`pointer`:`default`;let a=n.querySelector(`svg`);a&&(a.style.display=r?``:`none`)},Gd=e=>{e!==Hd&&(Hd=e,Wd())},Kd=e=>{Ud=e?.starred===!0,Gd(e&&e.title.trim()||null),Wd()};Wd(),z.addEventListener(`persona:title-menu-builtin`,e=>{let t=e.detail?.actionId,n=Q.getActiveConversationId();n&&(t===`delete`?Xd(e=>e.requestDeleteConversation(n)):t===`star`&&Q.canUpdateConversations()&&Xd(e=>e.updateHistoryConversation(n,{starred:!Ud})).catch(()=>{}))}),un=e=>{Rd=e,Fd?.historySurface?.view.setNewConversationRequired(e.recovery===`new_conversation_required`),Iu(e.sendBlocked||ms),Fd?.syncEarlierMessagesPill()},dn=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(gs.clear(),gl(),il()),Bd(e.message),Fd?.historySurface?.view.refresh()};let qd={get actionManager(){return ze},get activeConversationTitle(){return Hd},announceHistory:Bd,get applyRailChrome(){return ln},set applyRailChrome(e){ln=e},get artifactSplitRoot(){return Ra},get body(){return B},get config(){return i},get container(){return z},get conversationOpenPendingEl(){return Ru},set conversationOpenPendingEl(e){Ru=e},get conversationOpenTakeover(){return zu},set conversationOpenTakeover(e){zu=e},currentKeyPrefix:_t,destroyCallbacks:Z,eventBus:O,get footer(){return K},get header(){return Bn},get historyChromeSync(){return fn},set historyChromeSync(e){fn=e},historyFeatureEnabled:zd,get historyInternals(){return gd},set historyInternals(e){gd=e},get historyPresentation(){return sn},set historyPresentation(e){sn=e},get historySessionState(){return Rd},get historyVisible(){return on},set historyVisible(e){on=e},get isStreaming(){return ms},jumpToBottomInstant:cl,get lastAppliedMessages(){return wd},set lastAppliedMessages(e){wd=e},get launcherEnabled(){return Be},get launcherSurfaceInstance(){return wp},maybeFocusInput:Lu,messageCache:gs,get messagesWrapper(){return V},mount:t,get open(){return F},panel:L,panelElements:R,get persistentMetadata(){return pe},set persistentMetadata(e){pe=e},plugins:f,get reapplyHistoryHostChrome(){return cn},set reapplyHistoryHostChrome(e){cn=e},repinAnchoredMessage:bl,resetAnchorState:gl,restoreScrollPosition:fl,resumeAutoScroll:il,runStorageMutation:Ec,get session(){return Q},setActiveConversationSummary:Kd,storageAdapter:fe,get suppressScrollSend(){return Js},set suppressScrollSend(e){Js=e},syncScrollToBottomButton:nl,updateWelcome:Xu,getHistoryProviderFactory:du,historyErrors:{HistoryClientError:Qn,HistoryProviderError:Ct},isDockedMountMode:xo,renderLucideIcon:N,loadHistoryView:iu,createHeaderIconButton:Po,attachTooltip:S},Jd=e=>(!Fd&&!Ld&&(Fd=e.createHistoryShell(qd),Fd.railCollapseShortcut()&&Vd()),Fd),Yd=()=>{if(Fd)return Promise.resolve(Fd);let e=uu();return e?Promise.resolve(Jd(e)):(Id??=lu().then(Jd,e=>{throw Id=null,e}),Id)},Xd=e=>{let t=uu(),n=Fd??(t?Jd(t):null);return n?e(n):Yd().then(t=>{if(!t)throw Error(`[AgentWidget] The widget was destroyed`);return e(t)})},Zd=()=>{Fd?.syncHistoryPresentation()};Z.push(()=>{Ld=!0}),zd()&&Yd().catch(()=>{}).finally(A),i.clientToken&&(i.features?.history?.enabled===!0||i.sessionInit===`mount`)&&Q.initClientSession().then(()=>{let e=Fd;if(e?.historyAvailable())return Q.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Fd?.syncEarlierMessagesPill()}).catch(e=>{i.debug&&console.warn(`[AgentWidget] Pre-init client session failed:`,e)});let Qd=()=>Q.warmClientSession(),$d=e=>{let t=i.sessionInit??`input`,n=Y?.input??H,r=e.target;n&&(e.type===`input`?(t===`input`||t===`focus`)&&r===n&&e.inputType&&n.value.trim():t===`focus`&&(e.type===`keyup`?r===n&&e.key===`Tab`:(Y?.form??Dn)?.contains(r)))&&Qd()},ef=[`input`,`pointerdown`,`keyup`];ef.forEach(e=>t.addEventListener(e,$d));let tf,nf,rf=()=>{let e=nf;nf=void 0;try{typeof e==`function`&&e()}catch{}},af=()=>{let e=i.clientToken&&typeof i.sessionInit==`function`?i.sessionInit:void 0;if(e!==tf){rf(),tf=e;try{nf=e?.({warm:Qd,mount:t})}catch{}}};af(),Z.push(()=>{ef.forEach(e=>t.removeEventListener(e,$d)),rf()}),(ft||i.onSSEEvent)&&Q.setSSEEventCallback((e,t)=>{i.onSSEEvent?.(e,t),rn(e,t)});let of=()=>{let e=i.resume??(k?gd.getStoredResumableHandle?.():null);e&&typeof i.reconnectStream==`function`&&Q.resumeFromHandle(e)};_e?_e.then(e=>{if(e){if(e.metadata&&(pe=Du(e.metadata),ze.syncFromMetadata()),e.messages?.length){Js=!0;try{Q.hydrateMessages(e.messages)}finally{Js=!1}Ll()}e.artifacts?.length&&Q.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),Ic(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Hu=!0,ve(),of()}):(Ic(Te),of());let sf=()=>{P()&&(F||(i.launcher?.composerBar?.expandOnSubmit??!0)&&ou(!0,`auto`))},cf=(e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[n,r]=await Promise.allSettled([e.finalize(),t.finalize()]),i=[];return n.status===`fulfilled`?i.push(n.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,n.reason),r.status===`fulfilled`?i.push(r.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,r.reason),Mu(i)}}:e:t,lf=()=>{let e=H.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>e.kind===`mention`)?e.contentSegments:void 0},uf=!1,df=null,ff=()=>{H.value=``,H.style.height=`auto`,Ir(),jf()},pf=null;function mf(e,t=4e3){yr(e),!P()&&W&&(W.hasAttribute(bu)||(W.setAttribute(xu,``),W.setAttribute(`role`,`status`),W.setAttribute(`aria-live`,`polite`),W.textContent=e,w(W,i.statusIndicator??{},`idle`),pf&&clearTimeout(pf),pf=setTimeout(()=>{if(pf=null,W?.hasAttribute(xu)&&(W.removeAttribute(xu),W.removeAttribute(`role`),W.removeAttribute(`aria-live`),g)){let e=Q.getStatus();gn(W,hn(e),i.statusIndicator??{},e)}},t)))}function hf(){let e=J.getState().pendingSubmission;e&&(ni(void 0),H&&(H.value=e.text,H.dispatchEvent(new Event(`input`,{bubbles:!0})),Ir()),e.options.selectedModelId&&(J.setSelectedModelId(e.options.selectedModelId),Gr?.repaint()),e.options.activeModeIds?.length&&Ur(e.options.activeModeIds),e.options.quote&&Zr(e.options.quote),H?.focus())}let gf=e=>{typeof console<`u`&&console.error(`[AgentWidget] composer.onBeforeSend failed; the draft was preserved:`,e)},_f=(e={})=>{let t=(e.overrideText??H?.value??``).trim();return e.resolveInlineCommand&&t?(Nr?.takeInlineCommand(t)??Promise.resolve(null)).then(n=>vf(e,t,n)):vf(e,t,null)},vf=(e,t,n)=>{if(n?.kind===`action`){ff(),Nr?.clear(),Lr();return}let r=n?.kind===`server`?n.mentions:null,a=n?.kind===`prompt`?n.sendText:t,o=e.pending?.contentParts;if(!ra({text:a,hasAttachments:(Mr?.hasAttachments()??!1)||(o?.length??0)>0,attachmentsReady:Mr?.isReady()??!0,hasMentions:Nr?.hasMentions()??!1,hasServerMentions:!!r,inputDisabled:cu(),sendDisabled:gu()}))return;let s=Q.isStreaming()?$r():`block`;if(s===`defer-one`&&!e.pending){if(J.getState().pendingSubmission){mf(`One message is already queued. Edit or remove it first.`);return}yf({intent:e,sendText:a,serverMentions:r});return}let c={text:a,mentionRefs:[...Nr?.getMentionRefs()??[],...r?.refs??[]],contentSegments:n?.kind===`prompt`?void 0:lf(),options:{...J.getState().selectedModelId&&{selectedModelId:J.getState().selectedModelId},...J.getState().activeModeIds.length>0&&{activeModeIds:[...J.getState().activeModeIds]},...J.getState().quote&&{quote:{...J.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(c.options={...e.pending.options},c.contentSegments=e.pending.contentSegments,c.mentionRefs=[...e.pending.mentionRefs],c.viaVoice=e.pending.viaVoice);let l=()=>{if(o?.length)return[...o];if(!Mr?.hasAttachments())return;let e=[...Mr.getContentParts()];return c.text&&e.push(st(c.text)),e};c.contentParts=l();let u=()=>{Cs(),sf();let t=Nr?.collectForSubmit()??null,n=cf(t,r),a=l();e.consumeDraft!==!1&&ff();let o={selectedModelId:c.options.selectedModelId,activeModeIds:c.options.activeModeIds},u=s===`interrupt`;u&&Q.cancel(),Q.sendMessage(c.text,{contentParts:a,mentions:n??void 0,contentSegments:c.contentSegments,viaVoice:c.viaVoice,composerOptions:o,...c.options.quote&&{quote:c.options.quote},...u&&{interrupt:!0}}),Mr?.hasAttachments()&&Mr.clearAttachments(),t&&Nr?.clear(),Lr();let d=J.getState().activeModeIds,f=Wi(d,i.composer?.modes);f.length!==d.length&&Ur(f),J.getState().quote&&Zr(void 0),Lc(),Li.release(),Vi()},d=i.composer?.onBeforeSend;if(!d){u();return}let f=new AbortController;df=f;let p=e=>{df=null,e.status===`error`?gf(e.error):e.status===`proceed`&&u()},m=oa(d,c,f.signal);if(!(m instanceof Promise))p(m);else return J.setPreparing(!0),m.then(p).finally(()=>J.setPreparing(!1))};function yf(e){let t=J.getState(),n=Mr?.hasAttachments()??!1,r=n?[...Mr.getContentParts()]:[];n&&e.sendText&&r.push(st(e.sendText)),ni(na({text:e.sendText,contentParts:r.length?r:void 0,mentionRefs:[...Nr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:lf(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),e.intent.consumeDraft!==!1&&ff(),n&&Mr.clearAttachments(),Nr?.clear(),Lr(),t.quote&&Zr(void 0),Lc(),Li.release(),Vi(),yr(`Message queued. It sends when the response finishes.`)}function bf(){let e=J.getState().pendingSubmission;e&&(ni(void 0),Ef(e.text,{consumeDraft:!1,pending:e}))}function xf(e){if(i.messageActions?.showEdit!==!0)return;let t=Q.getMessages().find(t=>t.id===e);t&&Dr(t)&&bs!==e&&(Cs(),bs=e,Ss=Yi({messageId:e,initialText:t.content,onSave:t=>Sf(e,t),onCancel:()=>Cs()}),gs.delete(e),Bl(V,Q.getMessages(),lt),Ss.focus())}function Sf(e,t){let n=Ss;bs=null,Ss=null,n?.destroy(),gs.delete(e),Q.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?bl():Bl(V,Q.getMessages(),lt)}function Cf(e){if(Q.isStreaming())return;let t=Tr(Q.getMessages(),e);t&&(Cs(),Q.resubmitFrom(t,{reason:`retry`})&&bl())}ha={regenerate:Cf,edit:xf,quote:e=>{let t=Q.getMessages().find(t=>t.id===e)?.content?.trim();t&&(Zr({text:t,messageId:e}),H?.focus())}};let wf=async e=>{if(!uf){uf=!0;try{await _f({resolveInlineCommand:!0,...e})}finally{uf=!1}}};function Tf(e){gu()||(ff(),Ef(e,{consumeDraft:!1}))}let Ef=(e,t)=>{if(uf)return;uf=!0;let n=()=>{uf=!1};try{let r=_f({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},Df=e=>{e.preventDefault(),Q.isStreaming()?(Q.cancel(),wt?.reset(),Xt?.update()):uf||wf()},Of=()=>i.features?.composerHistory!==!1,kf={...ao},Af=!1,jf=()=>{kf={...ao}},Mf=()=>Q.getMessages().filter(e=>e.role===`user`).map(e=>e.content??``).filter(e=>e.length>0),Nf=e=>{if(!H)return;Af=!0,H.value=e,H.dispatchEvent(new Event(`input`,{bubbles:!0})),Af=!1;let t=H.value.length;H.setSelectionRange(t,t)},Pf=e=>{Af||(e.isComposing||Nr?.handleInput(e.inputType??void 0),jf())},Ff=()=>({submitKey:i.composer?.submitKey,insertNewlineOnTouchEnter:i.composer?.insertNewlineOnTouchEnter,coarsePointer:De(H)}),If=e=>{if(H&&!cu()&&(e.isComposing||!Nr?.handleKeydown(e))){if(Of()&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.isComposing){let t=H.selectionStart===0&&H.selectionEnd===0,n=oo({direction:e.key===`ArrowUp`?`up`:`down`,history:Mf(),currentValue:H.value,atStart:t,state:kf});if(kf=n.state,n.handled){e.preventDefault(),n.value!==void 0&&Nf(n.value);return}}if(Ae(e,Ff())){if(Q.isStreaming()){if(e.preventDefault(),$r()===`block`||uf||gu())return;jf(),wf()}else uf||gu()?e.preventDefault():(jf(),e.preventDefault(),U.click())}}},Lf=e=>{e.key!==`Escape`||e.isComposing||e.composedPath().includes(z)&&(df?(df.abort(),df=null,e.preventDefault(),e.stopImmediatePropagation()):Q.isStreaming()&&(Q.cancel(),wt?.reset(),Xt?.update(),jf(),e.preventDefault(),e.stopImmediatePropagation()))},Rf=async e=>{if(i.attachments?.enabled!==!0||!Mr||cu())return;let t=Cu(e.clipboardData);t.length!==0&&(e.preventDefault(),await Mr.handleFiles(t))},zf=null,Bf=!1,Vf=null,Hf=null,Uf=()=>i.voiceRecognition?.completionBehavior===`review`;function Wf(e){q?.setAttribute(`data-state`,e),e===`recording`?$f():ep()}let Gf=`--persona-voice-level`,Kf=.5,qf=null,Jf=-1,Yf=0,Xf=()=>{let e=[],t=Kn??q?.parentElement??null;return t&&e.push(t),K&&e.push(K),e},Zf=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*100)/100;if(t!==Jf){Jf=t;for(let e of Xf())e.style.setProperty(Gf,String(t))}},Qf=()=>{Jf=-1,Yf=0;for(let e of Xf())e.style.removeProperty(Gf)};function $f(){if(qf!==null)return;if(typeof requestAnimationFrame!=`function`){Zf(g?Q.getVoiceLevel()??Kf:Kf);return}let e=()=>{qf=requestAnimationFrame(e);let t=g?Q.getVoiceLevel():null;t===null?Zf(Kf):(Yf+=(t-Yf)*.3,Zf(Yf))};qf=requestAnimationFrame(e)}function ep(){qf!==null&&(cancelAnimationFrame(qf),qf=null),Qf()}let tp=()=>typeof window>`u`?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,np=(e=`user`)=>{if(Bf||Q.isStreaming())return;let t=tp();if(!t)return;zf=new t;let n=i.voiceRecognition??{},r=n.pauseDuration??2e3;zf.continuous=n.provider?.browser?.continuous??!0,zf.interimResults=!0,zf.lang=n.provider?.browser?.language??`en-US`;let a=H.value;zf.onresult=e=>{let t=``,n=``;for(let r=0;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n=a}let i=a+t+n;H.value=i,Ir(),Vf&&clearTimeout(Vf),(t||n)&&(Vf=window.setTimeout(()=>{if(H.value.trim()&&zf&&Bf){if(rp(),Uf())return;wf({viaVoice:!0})}},r))},zf.onerror=e=>{e.error!==`no-speech`&&rp()},zf.onend=()=>{if(Bf){let e=H.value.trim();!Uf()&&e&&e!==a.trim()&&wf({viaVoice:!0}),rp()}};try{if(zf.start(),Bf=!0,$.active=!0,e!==`system`&&($.manuallyDeactivated=!1),gc(e),vc(),Vi(),q){let e=i.voiceRecognition??{};Hf={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:e.iconName??`mic`,iconSize:parseFloat(e.iconSize??``)||24};let t=e.recordingBackgroundColor,n=e.recordingIconColor,r=e.recordingBorderColor;if(q.classList.add(`persona-voice-recording`),Wf(`recording`),q.style.backgroundColor=t??`var(--persona-voice-recording-bg, #ef4444)`,q.style.color=n??`var(--persona-voice-recording-indicator, #ffffff)`,n){let e=q.querySelector(`svg`);e&&e.setAttribute(`stroke`,n)}r&&(q.style.borderColor=r),q.setAttribute(`aria-label`,`Stop voice recognition`)}}catch{rp(`system`)}},rp=(e=`user`)=>{if(Bf){if(Bf=!1,Vf&&=(clearTimeout(Vf),null),zf){try{zf.stop()}catch{}zf=null}if($.active=!1,gc(e),vc(),Vi(),q){if(q.classList.remove(`persona-voice-recording`),Wf(`idle`),Hf){q.style.backgroundColor=Hf.backgroundColor,q.style.color=Hf.color,q.style.borderColor=Hf.borderColor;let e=q.querySelector(`svg`);e&&e.setAttribute(`stroke`,Hf.color||`currentColor`),Hf=null}q.setAttribute(`aria-label`,`Start voice recognition`)}}},ip=null,ap=e=>{let t=t=>{ip??=t.createMicStateStyles({mic:()=>q,config:()=>i,session:()=>Q,get original(){return Hf},set original(e){Hf=e},setMicState:Wf,renderIcon:N,iconFallbackPx:24}),e(ip)},n=Fr();n?t(n):Pr().then(t,()=>{})},op=()=>ap(e=>e.recording()),sp=()=>ap(e=>e.processing()),cp=()=>ap(e=>e.speaking()),lp=()=>ap(e=>e.reset()),up=()=>{if(!cu()){if(Cn(i.voiceRecognition?.provider)){let e=Q.getVoiceStatus(),t=Q.getVoiceInterruptionMode();if(t===`none`&&(e===`processing`||e===`speaking`))return;if(t===`cancel`&&(e===`processing`||e===`speaking`)){Q.stopVoicePlayback();return}if(Q.isBargeInActive()){Q.stopVoicePlayback(),Q.deactivateBargeIn().then(()=>{$.active=!1,$.manuallyDeactivated=!0,vc(),gc(`user`),lp()});return}Q.toggleVoice().then(()=>{$.active=mc(),$.manuallyDeactivated=!$.active,vc(),gc(`user`),$.active?op():lp()})}else if(Bf){let e=H.value.trim();$.manuallyDeactivated=!0,vc(),rp(`user`),e&&!Uf()&&wf()}else $.manuallyDeactivated=!1,vc(),np(`user`)}};si=up;let dp=()=>Q.prewarmVoice(),fp=()=>{let e=i.voiceRecognition;return e?.enabled===!0?e.prewarm??(i.clientToken?`hover`:!1):!1},pp=e=>{fp()===`hover`&&q?.contains(e.target)&&dp()},mp=[`pointerover`,`pointerdown`,`focusin`];mp.forEach(e=>t.addEventListener(e,pp));let hp,gp=null,_p,vp=()=>{let e=_p;_p=void 0;try{typeof e==`function`&&e()}catch{}},yp=()=>{let e=fp(),n=typeof e==`function`&&q?e:void 0,r=n?q:null;if((n!==hp||r!==gp)&&(vp(),hp=n,gp=r,n&&r))try{_p=n({warm:dp,micButton:r,mount:t})}catch{}};yp(),Z.push(()=>{mp.forEach(e=>t.removeEventListener(e,pp)),vp()}),q&&Z.push(()=>{Cn(i.voiceRecognition?.provider)?(Q.isVoiceActive()&&Q.toggleVoice(),lp()):rp(`system`)});let bp=O.on(`assistant:complete`,()=>{J.getState().pendingSubmission&&setTimeout(()=>{Q.isStreaming()||bf()},0)});Z.push(bp);let xp=O.on(`assistant:complete`,()=>{pc&&($.active||$.manuallyDeactivated||(pc!==`assistant`||$.lastUserMessageWasVoice)&&setTimeout(()=>{!$.active&&!$.manuallyDeactivated&&(Cn(i.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=Q.isVoiceActive(),gc(`auto`),Q.isVoiceActive()&&op()}):np(`auto`))},600))});Z.push(xp);let Sp=O.on(`action:resubmit`,()=>{setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)});Z.push(Sp);let Cp=()=>{ou(!F,`user`)},wp=null,Tp=null;if(Be&&!P()){let{instance:e,element:t}=sc({config:i,plugins:f,onToggle:Cp});wp=e,e||(Tp=t)}wp?t.appendChild(wp.element):Tp&&t.appendChild(Tp),au(),us(),od(),id(),Iu(Q.isStreaming()),fl()||(tr()===`follow`?al(!0):cl()),yc(),We&&(!Be||P()?setTimeout(()=>Lu(),0):F&&setTimeout(()=>Lu(),200));let Ep=null,Dp=()=>{Ep&&(Ep.disconnect(),Ep.observe(K),Ep.observe(z),Ep.observe(On))},Op=br(),kp=()=>{if(P()){Or(),au();return}let e=xo(i),n=i.launcher?.sidebarMode??!1,r=t.ownerDocument.defaultView??window,a=i.launcher?.mobileFullscreen??!0,o=i.launcher?.mobileBreakpoint??640,s=r.innerWidth<=o,c=a&&s&&Be;try{if(c){va(),ya=_o();return}let t=!1;Ye&&(Ye=!1,va(),t=!0);let r=_o();if(!t&&r!==ya&&(va(),t=!0),ya=r,t&&Ha(),!Be&&!e){L.style.height=``,L.style.width=``;return}if(!n&&!e){let e=Us(i);L.style.width=e.width,L.style.maxWidth=e.maxWidth}po(),Mo()}finally{Or(),Ar();let e=br();if(e!==Op&&(Op=e,Xu(),us()),au(),F&&Be){let e=(t.ownerDocument.defaultView??window).innerWidth<=(i.launcher?.mobileBreakpoint??640),n=i.launcher?.sidebarMode??!1,r=i.launcher?.mobileFullscreen??!0,a=xo(i)&&r&&e,o=n||r&&e&&Be||a;if(o&&!Io){let e=t.getRootNode(),n=e instanceof ShadowRoot?e.host:t.closest(`.persona-host`);n&&!Fo&&(Fo=go(n,i.launcher?.zIndex??1e5)),Io=yo(t.ownerDocument)}else o||(Fo?.(),Fo=null,Io?.(),Io=null)}}};kp();let Ap=t.ownerDocument.defaultView??window;if(Ap.addEventListener(`resize`,kp),Z.push(()=>Ap.removeEventListener(`resize`,kp)),typeof ResizeObserver<`u`){Ep=new ResizeObserver(()=>{Ar()}),Dp(),Z.push(()=>{Ep?.disconnect(),Ep=null});let e=new ResizeObserver(()=>{Zd()});e.observe(z),Z.push(()=>e.disconnect())}Ap.addEventListener(`resize`,Zd),Z.push(()=>Ap.removeEventListener(`resize`,Zd)),js=B.scrollTop;let jp=Mt(B),Mp=()=>{Do();let e=B.scrollTop,t=Mt(B),n=t<jp;if(jp=t,!nr()){js=e,nl();return}let{action:r,nextLastScrollTop:i}=jt({following:Os.isFollowing(),currentScrollTop:e,lastScrollTop:js,nearBottom:Lt(B,24),userScrollThreshold:4,isAutoScrolling:Is||Ls||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});js=i,r===`resume`?dl()||il():r===`pause`&&rl()};if(B.addEventListener(`scroll`,Mp,{passive:!0}),Z.push(()=>B.removeEventListener(`scroll`,Mp)),typeof ResizeObserver<`u`){let e=new ResizeObserver(()=>{Sl(),Mn(V)});e.observe(V),e.observe(B),Z.push(()=>e.disconnect())}let Np=()=>{nr()&&Os.isFollowing()&&dl()&&rl()},Pp=B.ownerDocument;Pp.addEventListener(`selectionchange`,Np),Z.push(()=>{Pp.removeEventListener(`selectionchange`,Np)});let Fp=/* @__PURE__ */ new Set([`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`]),Ip=e=>{Fp.has(e.key)&&(ec(),ar()&&nr()&&Os.isFollowing()&&rl())},Lp=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&(ec(),ar()&&nr()&&Os.isFollowing()&&rl())};B.addEventListener(`keydown`,Ip),B.addEventListener(`focusin`,Lp),Z.push(()=>{B.removeEventListener(`keydown`,Ip),B.removeEventListener(`focusin`,Lp)});let Rp=e=>{if(e.deltaY!==0&&ec(),!nr())return;let t=Nt({following:Os.isFollowing(),deltaY:e.deltaY,nearBottom:Lt(B,24),resumeWhenNearBottom:!0});t===`pause`?rl():t===`resume`&&!dl()&&il()};B.addEventListener(`wheel`,Rp,{passive:!0}),B.addEventListener(`touchmove`,ec,{passive:!0}),B.addEventListener(`pointerdown`,ec,{passive:!0}),Z.push(()=>{B.removeEventListener(`touchmove`,ec),B.removeEventListener(`pointerdown`,ec)}),Z.push(()=>B.removeEventListener(`wheel`,Rp)),lr.addEventListener(`click`,()=>{gl(),B.scrollTop=B.scrollHeight,js=B.scrollTop,il(),al(!0),nl()}),Z.push(()=>lr.remove()),Z.push(()=>{Gc(),gl()});let zp=()=>{G&&(Qo&&=(G.removeEventListener(`click`,Qo),null),it()?(G.style.display=``,Qo=()=>{ou(!1,`user`)},G.addEventListener(`click`,Qo)):G.style.display=`none`)};zp(),(()=>{let{clearChatButton:e}=R;e&&e.addEventListener(`click`,()=>{let e=Fd;if(e?.historyAvailable()){e.startNewConversation({focusComposer:!0}).catch(e=>{i.debug&&console.warn(`[AgentWidget] New conversation failed:`,e)});return}Q.clearMessages(),i.layout?.topFade&&(B.scrollTop=0),B.removeAttribute(`data-persona-top-fade`),gs.clear(),il(),Xe(R.composerOverlay);try{localStorage.removeItem(yu),i.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${yu}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(i.clearChatHistoryStorageKey&&i.clearChatHistoryStorageKey!==yu)try{localStorage.removeItem(i.clearChatHistoryStorageKey),i.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${i.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let t=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(t),fe?.clear&&Ec(()=>fe.clear(),`[AgentWidget] Failed to clear storage adapter:`),pe={},ze.syncFromMetadata(),Mr?.clearAttachments(),Lc(),ni(void 0),Zr(void 0),Cs(),St?.clear(),wt?.reset(),Xt?.update()})})();let Bp=[[`keydown`,If],[`input`,Pf],[`input`,Ir],[`input`,Lr],[`keyup`,Lr],[`paste`,Rf],[`focus`,wi]],Vp=e=>{if(e)for(let[t,n]of Bp)Y?.addListener(e,t,n)},Hp=e=>{if(e)for(let[t,n]of Bp)Y?.removeListener(e,t,n)},Up=()=>{Y&&(Y.addListener(Y.form,`submit`,Df),Y.addListener(Y.footer,`click`,Lr),Vp(H),q&&Y.addListener(q,`click`,up),yp())};Up();let Wp=()=>{Nr?.onComposerSwap((e,t)=>{Hp(t),H=e,Y&&(Y.input=e),Vp(e),yi(),Fu(),Ir()})};Wp();let Gp=!1;function Kp(){if(!Gp){Gp=!0;try{let e=H?.value??``,t=K.ownerDocument??document,n=H?t.activeElement===H:!1;ep(),Y?.destroy(),Y=null,Nr?.destroy(),Nr=null;let r=null,a=()=>(r=P()?Yo({config:i}):qo({config:i}),r.footer),o=gi(a)??a();_n.replaceComposer(o),K=_n.composer.footer;let s=r!==null&&o===r.footer;hi=!s,Gn=s?r.setSendButtonMode:()=>{},mi(K),bi(K),Si(),Ci(),Ti(),Wp(),ki(),ji(),Mi(),Up();let c=Zo.indexOf(Go);if(Go.destroy(),Go=Ao(En),c>=0&&(Zo[c]=Go),H&&(H.value=e),Ir(),Lr(),od(),us(),Iu(Q.isStreaming()),i.statusIndicator?.mode===`transient`&&!P()){let e=Q.getStatus();gn(W,hn(e),i.statusIndicator,e)}$.active&&Wf(`recording`),va(),Dp(),Or(),Vi(),Nu(),n&&H?.focus()}finally{Gp=!1}}}let qp=t.ownerDocument??document;qp.addEventListener(`keydown`,Lf,!0);let Jp=()=>{Fc()},Yp=()=>{qp.visibilityState===`hidden`&&Fc()};typeof window<`u`&&(window.addEventListener(`pagehide`,Jp),qp.addEventListener(`visibilitychange`,Yp),Z.push(()=>{window.removeEventListener(`pagehide`,Jp),qp.removeEventListener(`visibilitychange`,Yp)}));let Xp=`persona-attachment-drop-active`,Zp=0,Qp=()=>{Zp=0,z.classList.remove(Xp)},$p=()=>i.attachments?.enabled===!0&&Mr!==null&&!cu(),em=e=>{wu(e.dataTransfer)&&$p()&&(Zp++,Zp===1&&z.classList.add(Xp))},tm=e=>{wu(e.dataTransfer)&&$p()&&(Zp--,Zp<=0&&Qp())},nm=e=>{wu(e.dataTransfer)&&$p()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},rm=e=>{if(!wu(e.dataTransfer)||!$p())return;e.preventDefault(),e.stopPropagation(),Qp();let t=Array.from(e.dataTransfer.files??[]);t.length!==0&&Mr.handleFiles(t)};z.addEventListener(`dragenter`,em,!0),z.addEventListener(`dragleave`,tm,!0),t.addEventListener(`dragover`,nm,!0),t.addEventListener(`drop`,rm,!0);let im=t.ownerDocument,am=e=>{$p()&&e.preventDefault()},om=e=>{$p()&&e.preventDefault()};im.addEventListener(`dragover`,am),im.addEventListener(`drop`,om),Z.push(()=>{Y?.destroy(),Y=null,ep(),Ei?.destroy(),Ei=null,qr?.destroy(),qr=null,Xr?.destroy(),Xr=null,ti?.destroy(),ti=null,Gr=null,Kr=null,Fc(),Nc.destroy(),pf&&clearTimeout(pf),Cs(),df?.abort(),df=null,Mr?.destroy(),Mr=null,J.destroy(),qp.removeEventListener(`keydown`,Lf,!0),Nr?.destroy()}),Z.push(()=>{z.removeEventListener(`dragenter`,em,!0),z.removeEventListener(`dragleave`,tm,!0),t.removeEventListener(`dragover`,nm,!0),t.removeEventListener(`drop`,rm,!0),im.removeEventListener(`dragover`,am),im.removeEventListener(`drop`,om),Qp()}),Z.push(()=>{Q.cancel()}),wp?Z.push(()=>{wp?.destroy()}):Tp&&Z.push(()=>{Tp?.remove()});let sm={update(e){let n=i.future?.v5Defaults===!0,r=i.toolCall,a=i.messageActions,o=i.layout?.messages,s=i.colorScheme,c=i.loadingIndicator,l=i.iterationDisplay,p=i.features?.showReasoning,m=i.features?.showToolCalls,h=i.features?.toolCallDisplay,g=i.features?.reasoningDisplay,_=i.features?.streamAnimation?.type,v=i.features?.history?.enabled===!0,y=i.features?.history?.provider,x=i.getIdentityProof,T=i.clientToken,E=i.contextMentions;i=Rl({...i,features:d},e),d=i.features,i=xl(i),u(),bo(),Za(t,i),Xc(t,i),Zc(t,i),ln(),vo(),i.colorScheme!==s&&zo();let D=Pl.getForInstance(i.plugins);f.length=0,f.push(...D),Vd(),Be=i.launcher?.enabled??!0,He=i.launcher?.autoExpand??!1,ut=i.features?.showReasoning??!0,dt=i.features?.showToolCalls??!0,mt=i.features?.scrollToBottom??{};let ee=tr();ht=i.features?.scrollBehavior??{},ee!==tr()&&(gl(),il()),rc(),jr(),nl();let te=ft;if(ft=i.features?.showEventStreamToggle??!1,ft&&!te){if(St||(an(),Q.setSSEEventCallback((e,t)=>{i.onSSEEvent?.(e,t),rn(e,t)})),!fi&&Bn){let e=i.features?.eventStream?.classNames,t=`persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1`+(e?.toggleButton?` `+e.toggleButton:``);fi=M(`button`,t),fi.style.width=`28px`,fi.style.height=`28px`,fi.style.color=Lo.actionIconColor,fi.type=`button`,fi.setAttribute(`aria-label`,`Event Stream`),fi.title=`Event Stream`;let n=b(Yt,`18px`,`currentColor`,1.5);n&&fi.appendChild(n);let r=R.clearChatButtonWrapper,a=R.closeButtonWrapper,o=r||a;o&&o.parentNode===Bn?Bn.insertBefore(fi,o):Bn.appendChild(fi),fi.addEventListener(`click`,()=>{Qt?di():ui()})}}else!ft&&te&&(di(),fi&&=(fi.remove(),null),St?.clear(),yt?.destroy(),St=null,yt=null,wt?.reset(),wt=null,Et=null);if(i.launcher?.enabled===!1&&wp&&(wp.destroy(),wp=null),i.launcher?.enabled===!1&&Tp&&(Tp.remove(),Tp=null),i.launcher?.enabled!==!1&&!wp&&!Tp){let{instance:e,element:n}=sc({config:i,plugins:f,onToggle:Cp});wp=e,e||(Tp=n),t.appendChild(n)}wp&&wp.update(i),Wd(),zn&&i.launcher?.subtitle!==void 0&&(zn.textContent=i.launcher.subtitle);let ne=i.layout?.header;if(ne?.layout!==Je&&Bn){let e=ne?Ko(i,ne,{showClose:it(),onClose:()=>ou(!1,`user`)}):Bo({config:i,showClose:it(),onClose:()=>ou(!1,`user`)});_n.replaceHeader(e),Bn=_n.header.element,Ln=_n.header.iconHolder,Rn=_n.header.headerTitle,zn=_n.header.headerSubtitle,G=_n.header.closeButton,Je=ne?.layout,Wd()}else if(ne){if(Ln&&(Ln.style.display=ne.showIcon===!1?`none`:``),Rn&&(Rn.style.display=ne.showTitle===!1?`none`:``),zn&&(zn.style.display=ne.showSubtitle===!1?`none`:``),G){let e=it()&&ne.showCloseButton!==!1;G.style.display=e?``:`none`}if(R.clearChatButtonWrapper){let e=ne.showClearChat;if(e!==void 0){R.clearChatButtonWrapper.style.display=e?``:`none`;let{closeButtonWrapper:t}=R;t&&!t.classList.contains(`persona-absolute`)&&(e?t.classList.remove(`persona-ml-auto`):t.classList.add(`persona-ml-auto`))}}}let re=i.layout?.showHeader!==!1;Bn&&(Bn.style.display=re?``:`none`);let ie=i.layout?.showFooter!==!1;K&&(K.style.display=ie?``:`none`),Or(),nl(),Be===qe?He!==Ke&&ou(He,`auto`):Be?ou(He,`auto`):(F=!0,au()),Ke=He,qe=Be,kp(),zp();let ae=JSON.stringify(i.toolCall)!==JSON.stringify(r),oe=JSON.stringify(i.messageActions)!==JSON.stringify(a),se=JSON.stringify(i.layout?.messages)!==JSON.stringify(o),ce=i.loadingIndicator?.render!==c?.render||i.loadingIndicator?.renderIdle!==c?.renderIdle||i.loadingIndicator?.showBubble!==c?.showBubble,le=i.iterationDisplay!==l,de=(i.features?.showReasoning??!0)!==(p??!0)||(i.features?.showToolCalls??!0)!==(m??!0)||JSON.stringify(i.features?.toolCallDisplay)!==JSON.stringify(h)||JSON.stringify(i.features?.reasoningDisplay)!==JSON.stringify(g);(i.future?.v5Defaults===!0!==n||ae||oe||se||ce||le||de)&&Q&&(Es++,Bl(V,Q.getMessages(),lt));let fe=i.features?.streamAnimation?.type;if(fe!==_&&fe&&fe!==`none`){let e=Uo(fe,i.features?.streamAnimation?.plugins);e&&Wt(e,t)}let k=i.launcher??{},pe=k.headerIconHidden??!1,me=i.layout?.header?.showIcon,he=pe||me===!1,ge=k.headerIconName,_e=k.headerIconSize??`40px`;if(Ln){let e=Bn,t=e?.querySelector(`.persona-flex-col`);if(he)Ln.style.display=`none`,e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(Ln.style.display=``,Ln.style.height=_e,Ln.style.width=_e,e&&t&&(e.contains(Ln)?Ln.nextSibling!==t&&(Ln.remove(),e.insertBefore(Ln,t)):e.insertBefore(Ln,t)),ge){let e=parseFloat(_e)||24,t=N(ge,e*.6,`currentColor`,1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,Ln.replaceChildren(t)):Ln.textContent=k.agentIconText??`💬`}else if(k.iconUrl){let e=Ln.querySelector(`img`);if(e)e.src=k.iconUrl,e.style.height=_e,e.style.width=_e;else{let e=document.createElement(`img`);e.src=k.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=_e,e.style.width=_e,Ln.replaceChildren(e)}}else{let e=Ln.querySelector(`svg`),t=Ln.querySelector(`img`);(e||t)&&Ln.replaceChildren(),Ln.textContent=k.agentIconText??`💬`}let n=Ln.querySelector(`img`);n&&(n.style.height=_e,n.style.width=_e)}}let ve=i.layout?.header?.showTitle,ye=i.layout?.header?.showSubtitle;if(Rn&&(Rn.style.display=ve===!1?`none`:``),zn&&(zn.style.display=ye===!1?`none`:``),G){let e=it()&&i.layout?.header?.showCloseButton!==!1;if(G.style.display=e?``:`none`,!P()){let e=k.closeButtonSize??``;G.style.height=e,G.style.width=e,G.style.minWidth=e,G.style.minHeight=e}let t=k.closeButtonPlacement??`inline`,{closeButtonWrapper:n}=R,r=t===`top-right`,a=n?.classList.contains(`persona-absolute`);if(n&&r!==a){if(n.remove(),r){n.className=`persona-absolute persona-top-4 persona-right-4 persona-z-50`;let e=Fd?.railColumn??z;e.style.position=`relative`,e.appendChild(n)}else{let e=k.clearChat?.placement??`inline`;n.className=(k.clearChat?.enabled??!0)&&e===`inline`?``:`persona-ml-auto`,Bn&&Bn.appendChild(n)}}if(G.style.color=k.closeButtonColor||Lo.actionIconColor,k.closeButtonBackgroundColor?(G.style.backgroundColor=k.closeButtonBackgroundColor,G.classList.remove(`hover:persona-bg-gray-100`)):(G.style.backgroundColor=``,G.classList.add(`hover:persona-bg-gray-100`)),k.closeButtonBorderWidth||k.closeButtonBorderColor){let e=k.closeButtonBorderWidth||`0px`,t=k.closeButtonBorderColor||`transparent`;G.style.border=`${e} solid ${t}`,G.classList.remove(`persona-border-none`)}else G.style.border=``,G.classList.add(`persona-border-none`);k.closeButtonBorderRadius?(G.style.borderRadius=k.closeButtonBorderRadius,G.classList.remove(`persona-rounded-full`)):(G.style.borderRadius=``,G.classList.add(`persona-rounded-full`)),k.closeButtonPaddingX?(G.style.paddingLeft=k.closeButtonPaddingX,G.style.paddingRight=k.closeButtonPaddingX):(G.style.paddingLeft=``,G.style.paddingRight=``),k.closeButtonPaddingY?(G.style.paddingTop=k.closeButtonPaddingY,G.style.paddingBottom=k.closeButtonPaddingY):(G.style.paddingTop=``,G.style.paddingBottom=``),No(G,k.closeButtonIconName??`x`,{iconSize:P()?Gs:void 0,iconText:k.closeButtonIconText??`×`});let o=k.closeButtonTooltipText??`Close chat`,s=k.closeButtonShowTooltip??!0;G.setAttribute(`aria-label`,o),n&&S({anchor:G,trigger:n,text:()=>G?.getAttribute(`aria-label`)??o,enabled:s})}let{clearChatButton:A,clearChatButtonWrapper:be}=R;if(A){let e=k.clearChat??{},t=e.enabled??!0,n=i.layout?.header?.showClearChat,r=n===void 0?t:n,a=e.placement??`inline`;if(be){be.style.display=r?``:`none`;let{closeButtonWrapper:e}=R;!P()&&e&&!e.classList.contains(`persona-absolute`)&&(r?e.classList.remove(`persona-ml-auto`):e.classList.add(`persona-ml-auto`));let t=a===`top-right`,n=be.classList.contains(`persona-absolute`);if(!P()&&t!==n&&r){if(be.remove(),t){be.className=`persona-absolute persona-top-4 persona-z-50`,be.style.right=`48px`;let e=Fd?.railColumn??z;e.style.position=`relative`,e.appendChild(be)}else{be.className=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,be.style.right=``;let e=R.closeButtonWrapper;Bn&&e&&e.parentElement===Bn?Bn.insertBefore(be,e):Bn&&Bn.appendChild(be)}let e=R.closeButtonWrapper;e&&!e.classList.contains(`persona-absolute`)&&(t?e.classList.add(`persona-ml-auto`):e.classList.remove(`persona-ml-auto`))}}if(r){if(!P()){let t=e.size??``;A.style.height=t,A.style.width=t,A.style.minWidth=t,A.style.minHeight=t}let t=e.iconColor??``;if(A.style.color=t||Lo.actionIconColor,No(A,e.iconName??`refresh-cw`,{iconSize:P()?Ks:void 0}),e.backgroundColor?(A.style.backgroundColor=e.backgroundColor,A.classList.remove(`hover:persona-bg-gray-100`)):(A.style.backgroundColor=``,A.classList.add(`hover:persona-bg-gray-100`)),e.borderWidth||e.borderColor){let t=e.borderWidth||`0px`,n=e.borderColor||`transparent`;A.style.border=`${t} solid ${n}`,A.classList.remove(`persona-border-none`)}else A.style.border=``,A.classList.add(`persona-border-none`);e.borderRadius?(A.style.borderRadius=e.borderRadius,A.classList.remove(`persona-rounded-full`)):(A.style.borderRadius=``,A.classList.add(`persona-rounded-full`)),e.paddingX?(A.style.paddingLeft=e.paddingX,A.style.paddingRight=e.paddingX):(A.style.paddingLeft=``,A.style.paddingRight=``),e.paddingY?(A.style.paddingTop=e.paddingY,A.style.paddingBottom=e.paddingY):(A.style.paddingTop=``,A.style.paddingBottom=``);let n=e.tooltipText??`Clear chat`,r=e.showTooltip??!0;A.setAttribute(`aria-label`,n),be&&S({anchor:A,trigger:be,text:()=>A?.getAttribute(`aria-label`)??n,enabled:r})}}let Se=i.actionParsers&&i.actionParsers.length?i.actionParsers:[Hl],Ce=i.actionHandlers&&i.actionHandlers.length?i.actionHandlers:[Wl.message,Wl.messageAndClick];ze=Kl({parsers:Se,handlers:Ce,getSessionMetadata:j,updateSessionMetadata:Ne,emit:O.emit,documentRef:typeof document<`u`?document:null}),lt=ku(i,ze,ct),_d(),Q.updateConfig(i),af(),(i.features?.history?.enabled===!0!==v||i.features?.history?.provider!==y||i.getIdentityProof!==x||i.clientToken!==T)&&(Fd?.closeHistory({restoreFocus:!1}),Fd?.installHistoryProvider()),Fd?.syncHistoryChromeImpl(),Zd(),zd()&&!Fd&&Yd().catch(()=>{}),Bl(V,Q.getMessages(),lt),us(),od(),ad(),Iu(Q.isStreaming()),E!==i.contextMentions&&Kp();let Te=i.voiceRecognition?.enabled===!0,De=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),Oe=Cn(i.voiceRecognition?.provider);if(Te&&(De||Oe)){if(!q||!Kn){let e=Ee(i);if(e){q=e.button,Kn=e.wrapper;let t=Wn&&Wn.parentElement===Un?Wn:null;Un?Un.insertBefore(Kn,t):Dn?.appendChild(Kn),Y&&(Y.micButton=q),Y?.addListener(q,`click`,up),q.disabled=cu()||Q.isStreaming()&&!pu()}}else{let e=i.voiceRecognition??{},t=i.sendButton??{},n=e.iconName??`mic`,r=e.iconSize,a=parseFloat(r??``)||24;q.classList.add(ue),q.classList.toggle(xe,!r),q.style.width=r??``,q.style.height=r??``,q.style.minWidth=r??``,q.style.minHeight=r??``;let o=e.iconColor??t.textColor;q.innerHTML=``;let s=N(n,a,o||`currentColor`,1.5);s?q.appendChild(s):q.textContent=`🎤`;let c=e.backgroundColor??t.backgroundColor;c?q.style.backgroundColor=c:q.style.backgroundColor=``,o?q.style.color=o:q.style.color=`var(--persona-text, #111827)`,e.borderWidth?(q.style.borderWidth=e.borderWidth,q.style.borderStyle=`solid`):(q.style.borderWidth=``,q.style.borderStyle=``),e.borderColor?q.style.borderColor=e.borderColor:q.style.borderColor=``,e.paddingX?(q.style.paddingLeft=e.paddingX,q.style.paddingRight=e.paddingX):(q.style.paddingLeft=``,q.style.paddingRight=``),e.paddingY?(q.style.paddingTop=e.paddingY,q.style.paddingBottom=e.paddingY):(q.style.paddingTop=``,q.style.paddingBottom=``);let l=e.tooltipText??`Start voice recognition`,u=e.showTooltip??!1;q.setAttribute(`aria-label`,l),Kn&&S({anchor:q,trigger:Kn,text:()=>q?.getAttribute(`aria-label`)??l,enabled:u}),Kn.style.display=``,q.disabled=cu()||Q.isStreaming()&&!pu()}}else q&&Kn&&(Kn.style.display=`none`,Cn(i.voiceRecognition?.provider)?Q.isVoiceActive()&&Q.toggleVoice():Bf&&rp());if(yp(),i.attachments?.enabled===!0){if(!Jn||!qn){let e=i.attachments??{};Xn||(Xn=M(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),Xn.style.display=`none`,(H.parentElement??Dn).insertBefore(Xn,H)),Yn||(Yn=document.createElement(`input`),Yn.type=`file`,Yn.accept=(e.allowedTypes??pt).join(`,`),Yn.multiple=(e.maxFiles??4)>1,Yn.style.display=`none`,Yn.setAttribute(`aria-label`,`Attach files`),(H.parentElement??Dn).insertBefore(Yn,H)),Jn=M(`div`,`persona-send-button-wrapper`),qn=M(`button`,`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ue} ${xe}`),qn.type=`button`,qn.setAttribute(`aria-label`,e.buttonTooltipText??`Attach file`);let t=e.buttonIconName??`paperclip`;qn.style.fontSize=`18px`,qn.style.lineHeight=`1`;let n=N(t,24,`currentColor`,1.5);n?qn.appendChild(n):qn.textContent=`📎`,qn.addEventListener(`click`,e=>{e.preventDefault(),Yn?.click()}),Jn.appendChild(qn);let r=e.buttonTooltipText??`Attach file`;S({anchor:qn,trigger:Jn,text:()=>qn?.getAttribute(`aria-label`)??r}),Hn?Hn.append(Jn):Dn.appendChild(Jn),Y&&(Y.attachmentButton=qn,Y.attachmentInput=Yn??void 0,Y.attachmentPreviews=Xn??void 0),!Mr&&Yn&&Xn&&(Mr=ei.fromConfig(e,zr),Mr.setPreviewsContainer(Xn),Y?.addListener(Yn,`change`,async()=>{Mr&&Yn?.files&&(await Mr.handleFileSelect(Yn.files),Yn.value=``)}))}else{Jn.style.display=``;let e=i.attachments??{};Yn&&(Yn.accept=(e.allowedTypes??pt).join(`,`),Yn.multiple=(e.maxFiles??4)>1),Mr&&Mr.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}if(z.querySelector(`.persona-attachment-drop-overlay`)?.remove(),z.appendChild(Au(i.attachments?.dropOverlay)),qn){let e=i.attachments??{},t=e.buttonTooltipText??`Attach file`;qn.setAttribute(`aria-label`,t),qn.textContent=``;let n=N(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);n?qn.appendChild(n):qn.textContent=`📎`,Jn&&S({anchor:qn,trigger:Jn,text:()=>qn?.getAttribute(`aria-label`)??t})}}else Jn&&(Jn.style.display=`none`),Mr&&Mr.clearAttachments(),z.querySelector(`.persona-attachment-drop-overlay`)?.remove();let ke=i.sendButton??{},Ae=ke.useIcon??!1,je=ke.iconText??`↑`,Me=ke.iconName,Pe=ke.tooltipText??`Send message`,Fe=ke.showTooltip??!1,Ie=ke.size,Le=parseFloat(Ie??``)||40,Re=ke.backgroundColor,Ve=ke.textColor;if(Ae){if(U.style.width=Ie??``,U.style.height=Ie??``,U.style.minWidth=Ie??``,U.style.minHeight=Ie??``,U.style.fontSize=`18px`,U.style.lineHeight=`1`,Ve?U.style.color=Ve:U.style.color=`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`,!Q.isStreaming()){if(U.innerHTML=``,Me){let e=parseFloat(ke.iconSize??``)||Math.round(Le*.5),t=Ve?.trim()||`currentColor`,n=ke.iconStrokeWidth??2,r=N(Me,e,t,n),i=N(ke.stopIconName??`square`,e,t,n);r&&i?U.appendChild(we(r,i)):r?U.appendChild(r):U.textContent=je}else U.textContent=je}U.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${ue}`,Re?(U.style.backgroundColor=Re,U.classList.remove(`persona-bg-persona-primary`)):(U.style.backgroundColor=``,U.classList.add(`persona-bg-persona-primary`))}else U.textContent=i.copy?.sendButtonLabel??`Send`,U.style.width=``,U.style.height=``,U.style.minWidth=``,U.style.minHeight=``,U.style.fontSize=``,U.style.lineHeight=``,U.className=`persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer`,Re?(U.style.backgroundColor=Re,U.classList.remove(`persona-bg-persona-accent`)):U.classList.add(`persona-bg-persona-accent`),Ve?U.style.color=Ve:U.classList.add(`persona-text-white`);ke.borderWidth?(U.style.borderWidth=ke.borderWidth,U.style.borderStyle=`solid`):(U.style.borderWidth=``,U.style.borderStyle=``),ke.borderColor?U.style.borderColor=ke.borderColor:U.style.borderColor=``,ke.paddingX?(U.style.paddingLeft=ke.paddingX,U.style.paddingRight=ke.paddingX):(U.style.paddingLeft=``,U.style.paddingRight=``),ke.paddingY?(U.style.paddingTop=ke.paddingY,U.style.paddingBottom=ke.paddingY):(U.style.paddingTop=``,U.style.paddingBottom=``),Q.isStreaming()||U.setAttribute(`aria-label`,Pe),Nu(),Wn&&S({anchor:U,trigger:Wn,text:()=>U.getAttribute(`aria-label`)??Pe,enabled:Fe}),ia(),Oo();let Ue=Ui(J.getState().activeModeIds,i.composer?.modes);J.setActiveModeIds(Ue),Vr().length>0!=!!qr&&ji(),qr?.render(Ue,Vr());for(let e of[...Yr.keys()])Ri(e,i.composer?.modeGroups)||Yr.delete(e);Yr.forEach(e=>e.repaint()),Gr?.repaint(),Ei?.resolve();let We=$a(i,P());if(wo(),We){V.style.maxWidth=We,V.style.marginLeft=`auto`,V.style.marginRight=`auto`,V.style.width=`100%`,jn.style.maxWidth=We,jn.style.marginLeft=`auto`,jn.style.marginRight=`auto`,jn.style.width=`100%`;for(let e of[Dn,En,Xn,W])e&&(e.style.maxWidth=We,e.style.marginLeft=`auto`,e.style.marginRight=`auto`,e.style.width=`100%`)}else{V.style.maxWidth=``,V.style.marginLeft=``,V.style.marginRight=``,V.style.width=``,jn.style.maxWidth=``,jn.style.marginLeft=``,jn.style.marginRight=``,jn.style.width=``;for(let e of[Dn,En,Xn,W])e&&(e.style.maxWidth=``,e.style.marginLeft=``,e.style.marginRight=``,e.style.width=``)}let Ge=i.statusIndicator??{};if(C(W,Dn,Ge),w(W,Ge,Q?.getStatus()??`idle`),Q){let e=Q.getStatus();gn(W,(e=>e===`idle`?Ge.idleText??xt.idle:e===`connecting`?Ge.connectingText??xt.connecting:e===`connected`?Ge.connectedText??xt.connected:e===`error`?Ge.errorText??xt.error:e===`paused`?Ge.pausedText??xt.paused:e===`resuming`?Ge.resumingText??xt.resuming:xt[e])(e),Ge,e)}W.classList.remove(`persona-text-left`,`persona-text-center`,`persona-text-right`);let Ye=Ge.align===`left`?`persona-text-left`:Ge.align===`center`?`persona-text-center`:`persona-text-right`;W.classList.add(Ye),yi(),Fu(),Vi(),cn()},open(){it()&&ou(!0,`api`)},close(){it()&&ou(!1,`api`)},toggle(){it()&&ou(!F,`api`)},reconnect(){Q.reconnectNow()},clearChat(){Sa=!1,c.clear(),o.clear(),s.clear(),l.clear(),Q.clearMessages(),i.layout?.topFade&&(B.scrollTop=0),B.removeAttribute(`data-persona-top-fade`),gs.clear(),il();try{localStorage.removeItem(yu),i.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${yu}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(i.clearChatHistoryStorageKey&&i.clearChatHistoryStorageKey!==yu)try{localStorage.removeItem(i.clearChatHistoryStorageKey),i.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${i.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let e=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(e),fe?.clear&&Ec(()=>fe.clear(),`[AgentWidget] Failed to clear storage adapter:`),pe={},ze.syncFromMetadata(),Mr?.clearAttachments(),Lc(),ni(void 0),Zr(void 0),Cs(),St?.clear(),wt?.reset(),Xt?.update()},setMessage(e){return!H||Q.isStreaming()||cu()?!1:(!F&&it()&&ou(!0,`system`),H.value=e,H.dispatchEvent(new Event(`input`,{bubbles:!0})),!0)},submitMessage(e){if(Q.isStreaming()||gu())return!1;let t=e?.trim()||H.value.trim();return t?(!F&&it()&&ou(!0,`system`),H.value=``,H.style.height=`auto`,Ir(),Ef(t,{consumeDraft:!1}),!0):!1},getComposerState(){return J.getState()},setQuote(e){let t=e?.text?.trim();t&&Zr({...e,text:t})},clearQuote(){Zr(void 0)},startVoiceRecognition(){return Q.isStreaming()?!1:Cn(i.voiceRecognition?.provider)?(Q.isVoiceActive()||Q.isBargeInActive()||(!F&&it()&&ou(!0,`system`),$.manuallyDeactivated=!1,vc(),Q.toggleVoice().then(()=>{$.active=mc(),vc(),gc(`user`),$.active&&op()})),!0):Bf?!0:tp()?(!F&&it()&&ou(!0,`system`),$.manuallyDeactivated=!1,vc(),np(`user`),!0):!1},stopVoiceRecognition(){return Cn(i.voiceRecognition?.provider)?!Q.isVoiceActive()&&!Q.isBargeInActive()?!1:((Q.isBargeInActive()?Q.deactivateBargeIn():Q.toggleVoice()).then(()=>{$.active=!1,$.manuallyDeactivated=!0,vc(),gc(`user`),lp()}),!0):Bf?($.manuallyDeactivated=!0,vc(),rp(`user`),!0):!1},injectMessage(e){return!F&&it()&&ou(!0,`system`),Q.injectMessage(e)},injectAssistantMessage(e){!F&&it()&&ou(!0,`system`);let t=Q.injectAssistantMessage(e);return at&&(at=!1,ot&&=(clearTimeout(ot),null),setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)),t},injectUserMessage(e){return!F&&it()&&ou(!0,`system`),Q.injectUserMessage(e)},injectSystemMessage(e){return!F&&it()&&ou(!0,`system`),Q.injectSystemMessage(e)},injectMessageBatch(e){return!F&&it()&&ou(!0,`system`),Q.injectMessageBatch(e)},injectComponentDirective(e){return!F&&it()&&ou(!0,`system`),Q.injectComponentDirective(e)},injectTestMessage(e){!F&&it()&&ou(!0,`system`),Q.injectTestEvent(e)},async connectStream(e,t){return Q.connectStream(e,t)},__pushEventStreamEvent(e){ft&&(an(),rn(e.type,e.payload))},showEventStream(){ft&&ui()},hideEventStream(){Qt&&di()},isEventStreamVisible(){return Qt},listConversations(e){return Q.listConversations(e)},getActiveConversationId(){return Q.getActiveConversationId()},openConversation(e,t){return Xd(n=>n.openHistoryConversation(e,{focusComposer:t?.focus===!0}))},startNewConversation(e){return Xd(t=>t.startNewConversation({focusComposer:e?.focus===!0}))},warmSession(){Qd()},deleteConversation(e){return Xd(t=>t.deleteHistoryConversation(e))},renameConversation(e,t){return Xd(n=>n.updateHistoryConversation(e,{title:t}))},setConversationStarred(e,t){return Xd(n=>n.updateHistoryConversation(e,{starred:t}))},clearConversationHistory(e){return Xd(t=>t.clearConversationHistory(e))},resetHistoryIdentity(){return Xd(e=>e.resetHistoryIdentity())},async getVisitorToken(){let e=md;if(!e)return null;let t=await e.get();return e===md?t:null},getHistoryIdentityStatus(){let e=Fd?.historyProvider;return e?e.getIdentityStatus():zd()?{state:`unavailable`,reason:`ineligible_mode`}:{state:`unavailable`,reason:`history_disabled`}},showHistory(e){return zd()?Xd(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...e?.focus===void 0?{}:{focus:e.focus}})):Promise.resolve()},hideHistory(e){Fd?.closeHistory(e?.restoreFocus===void 0?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible(){return on},showArtifacts(){Wc(i)&&(Sa=!1,Ea=!0,vo(),X?.setMobileOpen(!0))},hideArtifacts(){Wc(i)&&(Sa=!0,vo())},upsertArtifact(e){return Wc(i)?(rt(i.features?.artifacts,{artifactType:e.artifactType,...e.artifactType===`markdown`&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})===`panel`&&(Sa=!1,Ea=!0),Q.upsertArtifact(e)):null},selectArtifact(e){Wc(i)&&Q.selectArtifact(e)},clearArtifacts(){Wc(i)&&Q.clearArtifacts()},getArtifacts(){return Q?.getArtifacts()??[]},getSelectedArtifactId(){return Q?.getSelectedArtifactId()??null},focusInput(){return Be&&!F&&!P()||!H?!1:(H.focus(),!0)},async resolveApproval(e,t,n){let r=Q.getMessages().find(t=>t.variant===`approval`&&t.approval?.id===e);if(!r?.approval)throw Error(`Approval not found: ${e}`);if(v(r.approval))Q.resolveWebMcpApproval(r.id,t);else return Q.resolveApproval(r.approval,t,n)},setFollowUpSuggestions(e){ps(e)},clearFollowUpSuggestions(){fs()},getMessages(){return Q.getMessages()},getStatus(){return Q.getStatus()},getPersistentMetadata(){return{...pe}},updatePersistentMetadata(e){Ne(e)},on(e,t){return O.on(e,t)},off(e,t){O.off(e,t)},isOpen(){return it()&&F},isVoiceActive(){return $.active},toggleReadAloud(e){Q.toggleReadAloud(e)},stopReadAloud(){Q.stopSpeaking()},getReadAloudState(e){return Q.getReadAloudState(e)},onReadAloudChange(e){return Q.onReadAloudChange(e)},getState(){return{open:it()&&F,launcherEnabled:Be,voiceActive:$.active,streaming:Q.isStreaming()}},showCSATFeedback(e){!F&&it()&&ou(!0,`system`);let t=V.querySelector(`.persona-feedback-container`);t&&t.remove();let n=_u({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitCSATFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});V.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},showNPSFeedback(e){!F&&it()&&ou(!0,`system`);let t=V.querySelector(`.persona-feedback-container`);t&&t.remove();let n=vu({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitNPSFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});V.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},async submitCSATFeedback(e,t){return Q.submitCSATFeedback(e,t)},async submitNPSFeedback(e,t){return Q.submitNPSFeedback(e,t)},destroy(){jd(),vd!=null&&(clearInterval(vd),vd=null),c.clear(),o.clear(),s.clear(),l.clear(),Z.forEach(e=>e()),I.remove(),vn?.remove(),wp?.destroy(),Tp?.remove(),Qo&&G.removeEventListener(`click`,Qo)}};if(((r?.debugTools??!1)||i.debug)&&typeof window<`u`){let e=window.AgentWidgetBrowser,t={controller:sm,getMessages:sm.getMessages,getStatus:sm.getStatus,getMetadata:sm.getPersistentMetadata,updateMetadata:sm.updatePersistentMetadata,clearHistory:()=>sm.clearChat(),setVoiceActive:e=>e?sm.startVoiceRecognition():sm.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Z.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<`u`){let e=t.getAttribute(`data-persona-instance`)||t.id||`persona-`+Math.random().toString(36).slice(2,8),n=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.focusInput()};if(window.addEventListener(`persona:focusInput`,n),Z.push(()=>{window.removeEventListener(`persona:focusInput`,n)}),ft){let t=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.showEventStream()},n=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.hideEventStream()};window.addEventListener(`persona:showEventStream`,t),window.addEventListener(`persona:hideEventStream`,n),Z.push(()=>{window.removeEventListener(`persona:showEventStream`,t),window.removeEventListener(`persona:hideEventStream`,n)})}let r=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.showHistory()},i=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.hideHistory()};window.addEventListener(`persona:showHistory`,r),window.addEventListener(`persona:hideHistory`,i),Z.push(()=>{window.removeEventListener(`persona:showHistory`,r),window.removeEventListener(`persona:hideHistory`,i)});let a=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.showArtifacts()},o=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.hideArtifacts()},s=t=>{let n=t.detail;n?.instanceId&&n.instanceId!==e||n?.artifact&&sm.upsertArtifact(n.artifact)},c=t=>{let n=t.detail;n?.instanceId&&n.instanceId!==e||typeof n?.id==`string`&&sm.selectArtifact(n.id)},l=t=>{let n=t.detail;(!n?.instanceId||n.instanceId===e)&&sm.clearArtifacts()};window.addEventListener(`persona:showArtifacts`,a),window.addEventListener(`persona:hideArtifacts`,o),window.addEventListener(`persona:upsertArtifact`,s),window.addEventListener(`persona:selectArtifact`,c),window.addEventListener(`persona:clearArtifacts`,l),Z.push(()=>{window.removeEventListener(`persona:showArtifacts`,a),window.removeEventListener(`persona:hideArtifacts`,o),window.removeEventListener(`persona:upsertArtifact`,s),window.removeEventListener(`persona:selectArtifact`,c),window.removeEventListener(`persona:clearArtifacts`,l)})}let cm=Tu(i.persistState);if(cm&&it()){let e=Eu(cm.storage),n=`${cm.keyPrefix}widget-open`,r=`${cm.keyPrefix}widget-voice`,i=`${cm.keyPrefix}widget-voice-mode`;if(e){let a=cm.persist?.openState&&e.getItem(n)===`true`,o=cm.persist?.voiceState&&e.getItem(r)===`true`,s=cm.persist?.voiceState&&e.getItem(i)===`true`;if(a&&(wp?.setPanelOpen(!0,`auto`),setTimeout(()=>{sm.open(),setTimeout(()=>{if(o||s)sm.startVoiceRecognition();else if(cm.persist?.focusInput){let e=t.querySelector(`textarea`);e&&e.focus()}},100)},0)),cm.persist?.openState&&(O.on(`widget:opened`,()=>{e.setItem(n,`true`)}),O.on(`widget:closed`,()=>{e.setItem(n,`false`)})),cm.persist?.voiceState&&(O.on(`voice:state`,t=>{e.setItem(r,t.active?`true`:`false`)}),O.on(`user:message`,t=>{e.setItem(i,t.viaVoice?`true`:`false`)})),cm.clearOnChatClear){let t=()=>{e.removeItem(n),e.removeItem(r),e.removeItem(i)},a=()=>t();window.addEventListener(`persona:clear-chat`,a),Z.push(()=>{window.removeEventListener(`persona:clear-chat`,a)})}}}if(je&&it()&&(wp?.setPanelOpen(!0,`auto`),setTimeout(()=>{sm.open()},0)),nu(),!Ds){let e=Ve(()=>{Q&&(Es++,gs.clear(),Bl(V,Q.getMessages(),lt))});Z.push(e)}ee=()=>{Q&&(Es++,gs.clear(),Bl(V,Q.getMessages(),lt))},Q.getMessages().length>0&&Ll(),oe=()=>{Q&&(Es++,gs.clear(),Bl(V,Q.getMessages(),lt))};let lm=Fe(()=>{Q&&(Es++,gs.clear(),Bl(V,Q.getMessages(),lt))});Z.push(lm);let um=Uc(()=>{Q&&(Es++,gs.clear(),Bl(V,Q.getMessages(),lt),Hc()?.updateInlineArtifactBlocks(V,xa.artifacts,{suppressTransition:!0}),vo())});return Z.push(um),sm},Pu=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let i=/^(\d+(?:\.\d+)?)%$/i.exec(n);return i?Math.max(0,t*parseFloat(i[1])/100):420},Fu=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},Iu=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},Lu=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement(`div`);r.style.cssText=`width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;`,n.appendChild(r);let i=r.offsetHeight>0;r.style.height=`100%`;let a=r.offsetHeight>0;r.remove(),i&&!a&&console.warn(`[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout.`+(t.maxHeight===!1?` The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.`:` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Ru=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className=`persona-host`,e.style.height=n?``:`100%`,e.style.display=n?``:`flex`,e.style.flexDirection=n?``:`column`,e.style.flex=n?``:`1 1 auto`,e.style.minHeight=n?``:`0`,e.style.minWidth=n?``:`0`},zu=e=>{e.style.position=``,e.style.top=``,e.style.bottom=``,e.style.left=``,e.style.right=``,e.style.zIndex=``,e.style.transform=``,e.style.pointerEvents=``},Bu=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,zu(e)},Vu=e=>{e.style.transition=``},Hu=e=>{e.style.display=``,e.style.flexDirection=``,e.style.flex=``,e.style.minHeight=``,e.style.minWidth=``,e.style.width=``,e.style.height=``,e.style.alignItems=``,e.style.transition=``,e.style.transform=``,e.style.marginLeft=``},Uu=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},Wu=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},Gu=(e,t,n,r,i)=>{i?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Ku=(e,t,n,r,i,a)=>{let o=a?t:e;i===`left`?o.firstElementChild!==r&&o.replaceChildren(r,n):o.lastElementChild!==r&&o.replaceChildren(n,r)},qu=e=>{let t=Ya(e),n=t.components?.panel,r=(e,n)=>e==null||e===``?n:Ca(t,e)??e;return{inset:r(n?.inset,la),canvasBackground:r(n?.canvasBackground,ua)}},Ju=(e,t,n,r)=>{t?(e.style.boxSizing=`border-box`,e.style.padding=n,e.style.background=r):(e.style.padding=``,e.style.background=``,e.style.boxSizing=``)},Yu=(e,t,n,r,i,a,o,s)=>{let c=Co(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;Gu(e,t,n,r,l),Ku(e,t,n,r,c.side,l),e.dataset.personaHostLayout=`docked`,e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=o?`true`:`false`,e.style.width=`100%`,e.style.maxWidth=`100%`,e.style.minWidth=`0`,e.style.height=`100%`,e.style.minHeight=`0`,e.style.position=`relative`,n.style.display=`flex`,n.style.flexDirection=`column`,n.style.minHeight=`0`,n.style.position=`relative`,i.className=`persona-host`,i.style.height=`100%`,i.style.minHeight=`0`,i.style.minWidth=`0`,i.style.display=`flex`,i.style.flexDirection=`column`,i.style.flex=`1 1 auto`;let p=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,h=a?.launcher?.mobileBreakpoint??640,g=p!=null&&p.innerWidth<=h;if(m&&g&&o)e.dataset.personaDockMobileFullscreen=`true`,e.removeAttribute(`data-persona-dock-reveal`),Hu(t),Vu(r),Bu(r),Uu(n),Wu(i,r),Ju(r,!1,``,``),e.style.display=`flex`,e.style.flexDirection=`column`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.minWidth=`0`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.position=`fixed`,r.style.inset=`0`,r.style.width=`100%`,r.style.height=`100%`,r.style.maxWidth=`100%`,r.style.minWidth=`0`,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.zIndex=String(a?.launcher?.zIndex??1e5),r.style.transform=`none`,r.style.transition=`none`,r.style.pointerEvents=`auto`,r.style.flex=`none`,l&&(t.style.display=`flex`,t.style.flexDirection=`column`,t.style.width=`100%`,t.style.height=`100%`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.flex=`1 1 auto`,t.style.alignItems=`stretch`,t.style.transform=`none`,t.style.marginLeft=`0`,t.style.transition=`none`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.maxWidth=`100%`,n.style.minWidth=`0`);else if(e.removeAttribute(`data-persona-dock-mobile-fullscreen`),Bu(r),Fu(r,c.maxHeight),Ju(r,u&&o,d,f),c.reveal===`overlay`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`overlay`,Hu(t),Vu(r),Uu(n),Wu(i,r);let a=c.animate?`transform 180ms ease`:`none`,s=c.side===`right`?`translateX(100%)`:`translateX(-100%)`,l=o?`translateX(0)`:s;r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`none`,r.style.position=`absolute`,r.style.top=`0`,r.style.bottom=`0`,r.style.width=c.width,r.style.maxWidth=c.width,r.style.minWidth=c.width,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.transition=a,r.style.transform=l,r.style.pointerEvents=o?`auto`:`none`,r.style.zIndex=`2`,c.side===`right`?(r.style.right=`0`,r.style.left=``):(r.style.left=`0`,r.style.right=``)}else if(c.reveal===`push`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`push`,Vu(r),zu(r),Wu(i,r);let a=Pu(c.width,e.clientWidth),s=Math.max(0,e.clientWidth),l=c.animate?`margin-left 180ms ease`:`none`,u=c.side===`right`?o?-a:0:o?0:-a;t.style.display=`flex`,t.style.flexDirection=`row`,t.style.flex=`0 0 auto`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.alignItems=`stretch`,t.style.height=`100%`,t.style.width=`${s+a}px`,t.style.transition=l,t.style.marginLeft=`${u}px`,t.style.transform=``,n.style.flex=`0 0 auto`,n.style.flexGrow=`0`,n.style.flexShrink=`0`,n.style.width=`${s}px`,n.style.maxWidth=`${s}px`,n.style.minWidth=`${s}px`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 auto`,r.style.flexShrink=`0`,r.style.width=c.width,r.style.minWidth=c.width,r.style.maxWidth=c.width,r.style.position=`relative`,r.style.top=``,r.style.overflow=`hidden`,r.style.transition=`none`,r.style.pointerEvents=o?`auto`:`none`}else{e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=``,Hu(t),zu(r),Uu(n),Wu(i,r);let a=c.reveal===`emerge`;a?e.dataset.personaDockReveal=`emerge`:e.removeAttribute(`data-persona-dock-reveal`);let s=o?c.width:`0px`,l=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?`, padding 180ms ease`:``}`:`none`,f=!o;if(r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 ${s}`,r.style.width=s,r.style.maxWidth=s,r.style.minWidth=s,r.style.minHeight=`0`,Iu(r,c.maxHeight),r.style.overflow=a||f?`hidden`:`visible`,r.style.transition=l,a){r.style.alignItems=c.side===`right`?`flex-start`:`flex-end`;let t=u?`calc(${Pu(c.width,e.clientWidth)}px - (2 * ${d}))`:c.width;i.style.width=t,i.style.minWidth=t,i.style.maxWidth=t,i.style.boxSizing=`border-box`}}},Xu=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return Ru(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){Ru(n,e)},destroy(){n.remove()}}},Zu=(e,t)=>{let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw Error(`Docked widget target must be attached to the DOM`);let i=e.tagName.toUpperCase();if(i===`BODY`||i===`HTML`)throw Error(`Docked widget target must be a concrete container element, not "body" or "html"`);let a=e.nextSibling,o=n.createElement(`div`),s=n.createElement(`div`),c=n.createElement(`div`),l=n.createElement(`aside`),u=n.createElement(`div`),d=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;s.dataset.personaDockRole=`push-track`,c.dataset.personaDockRole=`content`,l.dataset.personaDockRole=`panel`,u.dataset.personaDockRole=`host`,l.appendChild(u),r.insertBefore(o,e),c.appendChild(e);let f=null,p=()=>{f?.disconnect(),f=null},m=null,h=()=>{m=t?.launcher?.detachedPanel===!0?qu(t):null};h();let g=()=>{Yu(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=Qa(()=>{h(),g()}))},y=()=>{p(),Co(t).reveal===`push`&&typeof ResizeObserver<`u`&&(f=new ResizeObserver(()=>{g()}),f.observe(o))},b=!1,x=()=>{g(),y(),d&&!b&&o.dataset.personaDockMobileFullscreen!==`true`&&(b=!0,Lu(o,Co(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),Co(t).reveal===`push`?(s.appendChild(c),s.appendChild(l),o.appendChild(s)):(o.appendChild(c),o.appendChild(l)),x(),v(),{mode:`docked`,host:u,shell:o,syncWidgetState(e){let t=!e.launcherEnabled||e.open;d!==t&&(d=t,x())},updateConfig(e){t=e,(t?.launcher?.enabled??!0)===!1&&(d=!0),h(),x(),v()},destroy(){S?.removeEventListener(`resize`,C),_?.(),_=null,p(),r.isConnected&&(a&&a.parentNode===r?r.insertBefore(e,a):r.appendChild(e)),o.remove()}}},Qu=(e,t)=>xo(t)?Zu(e,t):Xu(e,t),$u={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ed=`persona-preview-shell-theme`,td={load:()=>null,save:()=>{},clear:()=>{}},nd=[`How do I get started?`,`Pricing & plans`,`Talk to support`];function rd(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function id(e){return e===`dark`?{pageBg:`linear-gradient(180deg, #0f172a 0%, #020617 100%)`,chromeBg:`#111827`,chromeBorder:`#1f2937`,dot:`#475569`,skeleton:`#334155`,cardBg:`#1e293b`,cardBorder:`rgba(148, 163, 184, 0.16)`}:{pageBg:`linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)`,chromeBg:`#ffffff`,chromeBorder:`#e5e7eb`,dot:`#cbd5e1`,skeleton:`#e2e8f0`,cardBg:`#e2e8f0`,cardBorder:`rgba(148, 163, 184, 0.18)`}}function ad(e){let t=id(e);return`* { box-sizing: border-box; }
|
|
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{_ 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 a
|
|
|
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{_ 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 a
|
|
|
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};
|