@runtypelabs/persona 4.26.0 → 4.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/approval-ui.d.cts +6 -0
- package/dist/approval-ui.d.ts +6 -0
- package/dist/artifacts-ui.d.cts +6 -0
- package/dist/artifacts-ui.d.ts +6 -0
- package/dist/chunk-GKPCIQPB.js +1 -0
- package/dist/{client-history-YPEG45Q4.js → client-history-GOZWBDA5.js} +1 -1
- package/dist/client-history.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +6 -0
- package/dist/context-mentions.d.ts +6 -0
- package/dist/event-stream-view.d.cts +6 -0
- package/dist/event-stream-view.d.ts +6 -0
- package/dist/forms-ui.d.cts +6 -0
- package/dist/forms-ui.d.ts +6 -0
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +6 -0
- package/dist/session-reconnect.d.ts +6 -0
- package/dist/smart-dom-reader.d.cts +6 -0
- package/dist/smart-dom-reader.d.ts +6 -0
- package/dist/theme-editor-preview.cjs +14 -14
- package/dist/theme-editor-preview.d.cts +6 -0
- package/dist/theme-editor-preview.d.ts +6 -0
- package/dist/theme-editor-preview.js +5 -5
- package/dist/theme-editor.d.cts +6 -0
- package/dist/theme-editor.d.ts +6 -0
- package/dist/voice-runtime-XLU6YK2N.js +17 -0
- package/dist/voice-runtime.cjs +3 -3
- package/dist/voice-runtime.d.cts +6 -0
- package/dist/voice-runtime.d.ts +6 -0
- package/dist/voice-runtime.js +3 -3
- package/package.json +1 -1
- package/src/approval-paused-tool-settle.test.ts +108 -4
- package/src/session.ts +51 -10
- package/src/session.voice.test.ts +1 -0
- package/src/types.ts +6 -0
- package/src/voice/runtype-voice-provider.ts +19 -9
- package/src/voice/voice-delegation.ts +1 -1
- package/src/voice/voice.test.ts +81 -2
- package/dist/chunk-QPPJUSZH.js +0 -1
- package/dist/voice-runtime-UOQOFAFY.js +0 -17
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import{a as Om,b as qa,d as is,e as _m,f as ja,g as Fm,h as Wf,i as Bf,m as Df,n as ms,o as go}from"./chunk-QRKGQPU7.js";import{a as el}from"./chunk-4HPTPUC6.js";import{b as gi,c as Td,e as xf,f as Af,g as Mf}from"./chunk-J4J3Y2P2.js";import{A as uf,B as gf,C as mf,D as Pd,E as Uo,F as Mr,G as ff,H as qn,I as tl,J as nl,K as hf,L as ol,M as gs,N as rl,O as sl,P as il,Q as yf,R as wf,S as Sf,T as Id,a as Sr,b as Em,c as Tm,d as km,e as Pm,f as Lm,g as xr,h as Im,i as Hm,j as Rm,k as $a,l as $o,m as rs,n as za,o as Ar,p as Wm,q as Ua,r as ui,s as vd,t as af,u as lf,v as cf,w as vn,x as df,y as pf,z as kd}from"./chunk-T7QM7YMF.js";import{a as je,c as Bm,d as Dm,e as se}from"./chunk-ZC66NAIR.js";import{a as Za,c as nf,d as zo,f as us,g as Ed,i as of,j as rf,k as sf}from"./chunk-S6PBWE75.js";import{a as cl,b as Hf,c as Rd,d as mi,e as dl,f as fi,g as pl,h as hi,i as Rf,j as yi}from"./chunk-CPVD5P5B.js";import{a as Ef,b as Tf,c as uo,d as Er,e as kf,f as Pf,g as Lf,h as Hd,i as If}from"./chunk-VK6JOIYJ.js";import{a as Ga,b as zm,c as as,d as wd,e as Md}from"./chunk-K6HKIP5K.js";import{c as cs,d as Jm,j as Zm,k as xd}from"./chunk-K7NA7G7J.js";import{a as gt,b as Dt,d as tf}from"./chunk-2ANTRKTV.js";import{a as Ad,d as Ja,e as ef,f as ds}from"./chunk-TR2H475E.js";import{b as Nm,c as Ka,d as Vm,e as Cd,f as $m,g as ls,h as Um,i as qm,j as jm,k as Km,l as Ya,m as Qa,n as Sd,o as Xa,q as Gm,r as Ym,s as Qm,t as Xm}from"./chunk-NQLDCJAP.js";import{a as ps}from"./chunk-
|
|
1
|
+
import{a as Om,b as qa,d as is,e as _m,f as ja,g as Fm,h as Wf,i as Bf,m as Df,n as ms,o as go}from"./chunk-QRKGQPU7.js";import{a as el}from"./chunk-4HPTPUC6.js";import{b as gi,c as Td,e as xf,f as Af,g as Mf}from"./chunk-J4J3Y2P2.js";import{A as uf,B as gf,C as mf,D as Pd,E as Uo,F as Mr,G as ff,H as qn,I as tl,J as nl,K as hf,L as ol,M as gs,N as rl,O as sl,P as il,Q as yf,R as wf,S as Sf,T as Id,a as Sr,b as Em,c as Tm,d as km,e as Pm,f as Lm,g as xr,h as Im,i as Hm,j as Rm,k as $a,l as $o,m as rs,n as za,o as Ar,p as Wm,q as Ua,r as ui,s as vd,t as af,u as lf,v as cf,w as vn,x as df,y as pf,z as kd}from"./chunk-T7QM7YMF.js";import{a as je,c as Bm,d as Dm,e as se}from"./chunk-ZC66NAIR.js";import{a as Za,c as nf,d as zo,f as us,g as Ed,i as of,j as rf,k as sf}from"./chunk-S6PBWE75.js";import{a as cl,b as Hf,c as Rd,d as mi,e as dl,f as fi,g as pl,h as hi,i as Rf,j as yi}from"./chunk-CPVD5P5B.js";import{a as Ef,b as Tf,c as uo,d as Er,e as kf,f as Pf,g as Lf,h as Hd,i as If}from"./chunk-VK6JOIYJ.js";import{a as Ga,b as zm,c as as,d as wd,e as Md}from"./chunk-K6HKIP5K.js";import{c as cs,d as Jm,j as Zm,k as xd}from"./chunk-K7NA7G7J.js";import{a as gt,b as Dt,d as tf}from"./chunk-2ANTRKTV.js";import{a as Ad,d as Ja,e as ef,f as ds}from"./chunk-TR2H475E.js";import{b as Nm,c as Ka,d as Vm,e as Cd,f as $m,g as ls,h as Um,i as qm,j as jm,k as Km,l as Ya,m as Qa,n as Sd,o as Xa,q as Gm,r as Ym,s as Qm,t as Xm}from"./chunk-NQLDCJAP.js";import{a as ps}from"./chunk-GKPCIQPB.js";import{a as bf,b as al,c as Ld,d as vf}from"./chunk-HGUCGM3K.js";import{b as ll}from"./chunk-Q735PSZL.js";import{a as yt}from"./chunk-7NQ4ZTHF.js";import{a as P,c as Y,d as ss}from"./chunk-76IELU7F.js";import{a as Cf}from"./chunk-UPO4GUFC.js";import{Circle as EC,Clock as TC}from"lucide";import{ChevronDown as CC,ChevronUp as wC}from"lucide";var SC=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],xC="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",AC="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",MC=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ul=(t,e)=>{let n=P("div",["persona-message-bubble",t,...SC].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},gl=t=>{let e=P("button",t.expandable?xC:AC);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},Wd=(t,e,n)=>{t.innerHTML="";let o=yt(e?wC:CC,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},fs=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=P("div","persona-flex persona-items-center");Wd(o,n.expanded,n.iconColor);let s=P("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return s.append(o),t.append(e,s),o},ml=t=>{let e=P("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();MC(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},fl=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&Wd(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},hl=(t,e,n)=>{let o=n.stateSet.has(t),s=e.querySelector('button[data-expand-header="true"]'),i=e.querySelector(".persona-border-t"),l=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let u=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");u&&Wd(u,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};function yl(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return{...t,features:{...t?.features,[n]:{...e==="tool"?$o:rs,...t?.future?.v5Defaults===!0?za.features?.[n]:{},...t?.features?.[n]}}}}function qo(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return t?.features?.[n]?.variant??(t?.future?.v5Defaults?"row":"card")}function bi(t){let e=Math.max(0,Math.floor((t??0)/1e3));return e<1?"a moment":e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function mo(t,e,n,o){if(qo(n,o)!=="row")return t;t.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,t.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(t.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let s=t.querySelector(":scope > button");if(!s)return t;s.className="persona-activity-header";let i=o==="tool"?e.toolCall:e.reasoning,l=i?.status!=="complete",c=e.approval?.status??e.toolCall?.approvalStatus,u=c==="denied"?"denied":c==="pending"?"awaiting-approval":e.toolCall?.success===!1?"error":l?i?.status==="pending"?"pending":"running":"done";t.dataset.activityState=u;let p=P("span","persona-activity-icon");p.dataset.activityIcon=u;let g={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},y=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,h=y?se(y,16,"currentColor",2):u==="pending"?yt(EC,16,"currentColor",2):u==="awaiting-approval"?yt(TC,16,"currentColor",2):se(g[u],16,"currentColor",2);h&&p.appendChild(h),s.querySelector(".persona-reasoning-header-icon")?.remove();let C=o==="tool"?"toolCallDisplay":"reasoningDisplay",E=n.features?.[C]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((E==="always"||E==="active"&&u!=="done")&&s.prepend(p),o==="tool"&&i){let k=P("span","persona-activity-duration");l&&i.startedAt&&k.setAttribute("data-tool-elapsed",String(i.startedAt));let R=(o==="tool"?e.toolCall?.duration:void 0)??i.durationMs??(i.completedAt!==void 0&&i.startedAt!==void 0?i.completedAt-i.startedAt:void 0);k.textContent=R===void 0?"":bi(R),s.appendChild(k)}s.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),s.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let L=t.querySelector(":scope > .persona-border-t");return L?.classList.add("persona-activity-body"),L&&(L.id=`activity-details-${e.id}`,s.setAttribute("aria-controls",L.id)),t}function Of(t){let e=new Set,n=new Set,o=new Set,s=new Map,i=l=>{clearTimeout(s.get(l)),s.delete(l)};return{observe(l,c,u,p={}){let g=c==="tool"?l.toolCall:l.reasoning;if(!(!g||n.has(l.id))&&(!e.has(l.id)&&g.status!=="complete"&&g.chunks?.some(Boolean)&&(e.add(l.id),p.autoExpand!==!1&&u.add(l.id)),e.has(l.id)&&g.status==="complete"&&!o.has(l.id))){if(o.add(l.id),p.autoCollapseDelay===!1)return;s.set(l.id,setTimeout(()=>{s.delete(l.id),u.delete(l.id),t(l.id,c)},p.autoCollapseDelay??1e3))}},manual(l){n.add(l),i(l)},prune(l){for(let c of new Set([...e,...n,...o]))l.has(c)||(i(c),e.delete(c),n.delete(c),o.delete(c))},clear(){for(let l of s.keys())i(l);e.clear(),n.clear(),o.clear()}}}function _f(t,e,n,o){let s=P("div","");s.id=`bubble-${t.id}`,s.dataset.messageId=t.id;let i=P("button","");i.type="button",i.dataset.expandHeader="true",i.dataset.bubbleType="tool",i.setAttribute("aria-expanded",String(n));let l=P("div","");typeof o=="string"?l.textContent=o:l.appendChild(o),fs(i,l,{expandable:!0,expanded:n,iconColor:e.toolCall?.toggleTextColor||e.toolCall?.headerTextColor||"currentColor",metaGap:!0});let c=P("div","persona-border-t");return c.id=`activity-details-${t.id}`,c.style.display=n?"":"none",i.setAttribute("aria-controls",c.id),s.append(i,c),mo(s,t,{...e,features:{...e.features,toolCallDisplay:{...e.features?.toolCallDisplay,variant:"row"}}},"tool"),s.dataset.personaToolGroup="true",e.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(s.dataset.activityGroupShimmer="true"),{bubble:s,body:c}}function Ff(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function Nt(t){return t?.type==="runtype"||t?.type==="custom"}var kC=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Nf(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:kC()}catch{return!1}}var Vf=/^\s*\|?[\s:|-]*-[\s:|-]*$/,$f=t=>t.includes("|"),zf=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},PC=t=>`| ${t.join(" | ")} |`,LC=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,IC=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Uf=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
2
2
|
`),n=!1;for(let o=0;o<e.length-1;o++){let s=e[o],i=e[o+1];if(!$f(s)||Vf.test(s)||!Vf.test(i))continue;let l=zf(s).length;if(l<1)continue;let c=LC(l);e[o+1]!==c&&(e[o+1]=c,n=!0);let u=o+2;for(;u<e.length;u++){let p=e[u];if(p.trim()===""||!$f(p))break;let g=PC(IC(zf(p),l));e[u]!==g&&(e[u]=g,n=!0)}o=u-1}return n?e.join(`
|
|
3
|
-
`):t};var qf="var(--persona-md-table-scroll-fade, 24px)",jf=new WeakSet;function Gf(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let s=document.createElement("div");s.className="persona-table-scroll",n.replaceWith(s),s.appendChild(n)})}function Kf(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,s=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":qf),t.style.setProperty("--persona-fade-r",s<=1?"0px":qf)}function Bd(t){jf.has(t)||(jf.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Kf(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Kf)}var{setLoader:UA,load:HC,provide:qA,getSync:RC}=je({fallbackImport:()=>import("./client-stream-42FOI3EC.js")});var Tr=HC;var Yf=RC;var{setLoader:GA,load:WC}=je({fallbackImport:()=>import("./webmcp-runtime-V6ZWW3PI.js")});var Qf=WC;var BC="agent_",DC="flow_";function Xf(t){return t.startsWith(BC)?{kind:"agentId",agentId:t}:t.startsWith(DC)?{kind:"flowId",flowId:t}:null}function Jf(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let l=n.slice(0,o),c=n.slice(o+1);if(l==="runtype"){let p=Xf(c);if(p)return p;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let u=e?.[l];if(!u)throw new Error(`[Persona] No target provider registered for "${l}". Add a \`targetProviders.${l}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:u(c).payload}}let s=Xf(n);if(s)return s;let i=e?.default;if(i)return{kind:"payload",payload:i(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function bl(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function hs(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function Zf(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var OC=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),_C=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),FC=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=OC(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:_C(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},Dd=(t,e)=>{let n=[],o=[],s=[],i="",l,c=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:i,toolCalls:o},{role:"tool",content:"",createdAt:i,toolResults:s}),o=[],s=[])};for(let u of t){let p=FC(u);if(p){let y=u.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(y===void 0||y!==l)&&c(),o.length===0&&(i=u.createdAt,l=y),o.some(h=>h.toolCallId===p.call.toolCallId)||(o.push(p.call),s.push(p.result));continue}let g=e(u);g&&(c(),n.push(g))}return c(),n};var{setLoader:eM,load:NC,provide:tM}=je({fallbackImport:()=>import("./client-history-YPEG45Q4.js")});var fo=NC;var VC="https://api.runtype.com/v1/dispatch",bt=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},eh=t=>"reason"in t?t.reason:void 0,$C="The identity proof was rejected",Od=(t,e)=>t instanceof bt&&t.code===e,_d=t=>t.voiceCaption?!1:!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0),th=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),nh=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function zC(t){switch(t){case"json":return Qm;case"regex-json":return Ym;case"xml":return Xm;default:return Gm}}var vi=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.#N=null;this.clientSession=null;this.#n=null;this.#l=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#h=null;this.#D=!1;this.#O=!1;this.#V=!1;this.#o=null;this.#c=new Set;this.#g=new Set;this.webMcpBridge=null;this.#C=null;this.#me=null;this.#fe=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??VC,this.#t={"Content-Type":"application/json","X-Persona-Version":ps,...e.headers},this.debug=!!e.debug,this.#s=e.streamParser??zC(e.parserType),this.#r=e.contextProviders??[],this.#a=e.requestMiddleware,this.#f=e.customFetch,this.#i=e.parseSSEEvent,this.#u=e.getHeaders,e.webmcp?.enabled===!0&&(this.#C=this.#y(e.webmcp))}#e;#t;#s;#r;#a;#f;#i;#u;#v;#N;#n;#l;#h;#D;#O;#V;#o;#c;#g;#C;#L;#y(e){return Qf().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Nm,getToolDisplayTitle:Ka,loadPolyfill:$m});return this.#L!==void 0&&o.setConfirmHandler(this.#L),this.webMcpBridge=o,o}).catch(n=>(this.#C=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#d(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#C||(this.#C=this.#y(this.config.webmcp)),this.#C)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#v=e}setWebMcpConfirmHandler(e){this.#L=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.#d().then(s=>s?s.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#v}isClientTokenMode(){return!!this.config.clientToken}#x(){let{agentId:e,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:e,flowId:n};let i=Jf(o,s);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#x().agentId)}#E(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||tf}#b(e){return`${this.#E()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let s=n.conversationId,i=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!s||!i)throw new bt("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.#E()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),u=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":ps,"X-Visitor-Token":i},signal:e.signal});if(u.status===401&&!o){o=!0;let p=await fo();n=await p.recoverFromUnauthorized(this.#T(),await p.readErrorCode(this.#T(),u),null,!0);continue}if(!u.ok)throw await(await fo()).historyErrorFor(this.#T(),u,!0);return u}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#n||e&&new Date<e.expiresAt||this.#l===e?null:(this.#l=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#n)return this.#n;let e=this.#n=this.#z().then(n=>this.#n!==e?this.initSession():(this.clientSession=n,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#n===e&&(this.#n=null)});return e}#m(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#D}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#re(){if(!this.#D){this.#$({state:"unavailable",reason:"history_disabled"}),this.#D=!0,!this.#O&&typeof console<"u"&&(this.#O=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#g])e(!1)}}getHistoryIdentityStatus(){return this.#o??this.#se()}subscribeHistoryIdentityStatus(e){return this.#c.add(e),()=>{this.#c.delete(e)}}subscribeHistoryAvailability(e){return this.#g.add(e),this.#D&&e(!1),()=>{this.#g.delete(e)}}#se(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#D?{state:"unavailable",reason:"history_disabled"}:this.#K():{state:"unavailable",reason:"ineligible_mode"}}#K(){let e=this.#o;return e?.state==="browser_only"?e:this.#I()}#I(){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"}}#$(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&eh(n)===eh(e);if(this.#o=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.#c])s(e)}}async#S(e){let n=this.#m()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.#x(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,u={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.#b("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(u),signal:e.signal});if(!p.ok){let y=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&y.error==="visitor_history_disabled"){if(this.#re(),c)throw new bt("history_disabled","Visitor history is disabled for this surface");return this.#S({...e,omitVisitorFields:!0})}throw p.status===403&&y.error==="durable_recovery_disabled"?new bt("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&y.error==="visitor_required"?new bt("visitor_required","Visitor credential no longer resolves"):c&&p.status===404?new bt("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${y.hint||y.error}`):p.status===403?new Error(`Origin not allowed: ${y.hint||y.error}`):new Error(y.error||"Failed to initialize session")}let g=await p.json();return g.visitor?.token&&await this.historyInternals.visitorStore?.set(g.visitor.token),{sessionId:g.sessionId,expiresAt:new Date(g.expiresAt),flow:g.flow,...g.conversationId?{conversationId:g.conversationId}:{},...g.targetId?{targetId:g.targetId}:{},...g.conversationRevision?{conversationRevision:g.conversationRevision}:{},...g.durableRecovery?{durableRecovery:g.durableRecovery}:{},...g.visitor?{visitor:g.visitor}:{},config:{welcomeMessage:g.config.welcomeMessage,placeholder:g.config.placeholder,theme:g.config.theme}}}async#z(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#m()&&!n)return this.#te(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.#S({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#H(s,e,!1)}catch(s){if(!Od(s,"not_found")&&!Od(s,"visitor_required")&&!Od(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#te(e,!0)}return this.#te(e,!1)}async#te(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#ie(e,n)):this.#ie(e,n)}async#ie(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.#S({storedSessionId:o}),i=await this.#Y(s);return this.#H(i,e,n)}async#G(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.#S({storedSessionId:n,identityProof:e}),i=this.#H(s,o,!1);return this.clientSession=i,this.#n=null,this.#l=!1,this.resetClientToolsFingerprint(),i}async#Y(e){if(!e.visitor?.token||this.#V||!this.#m()&&e.durableRecovery?.enabled!==!0)return e;this.#V=!0;try{return await this.#S({storedSessionId:e.sessionId})}catch{return e}finally{this.#V=!1}}#H(e,n,o){let s=e.conversationId;return s&&n&&(o||s!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:s}),this.config.setStoredSessionId?.(e.sessionId),s&&(this.config.setStoredConversationId?.(s),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#ne(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.#l=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#m())throw new bt("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new bt("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.#S({conversationId:e,identityProof:o});return this.#ne(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#S({});return this.#ne(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#m()&&this.#$(this.#I())}clearClientSession(){this.clientSession=null,this.#n=null,this.#l=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#h=null}#U(){return`${this.#E()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let s={...e,...this.config.clientToken&&{token:this.config.clientToken}},i=await fetch(this.#U(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(s)});if(!i.ok){let l=await i.json().catch(()=>({error:"Feedback submission failed"}));throw i.status===401?(this.clientSession=null,this.#l=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async#R(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let s,i;try{let l=Promise.resolve().then(()=>o());s=e?await Promise.race([l,new Promise((c,u)=>{i=()=>u(e.reason),e.addEventListener("abort",i,{once:!0}),e.aborted&&i()})]):await l}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{i&&e?.removeEventListener("abort",i)}if(typeof s!="string"||!s.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:s}}#me;#ae(){let e=this;return this.#me??={get config(){return e.config},headers:this.#t,getHeaders:this.#u,debug:this.debug,clientApiBase:()=>e.#E(),getClientApiUrl:n=>e.#b(n),getWebMcpBridge:()=>e.#d(),sendWithClientToolsDiff:(n,o,s,i)=>e.#W(n,o,s,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#fe;#T(){let e=this;return this.#fe??={HistoryClientError:bt,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#E(),setHistoryIdentityStatus:n=>e.#$(n),browserOnlyStatus:()=>e.#K(),derivedBrowserOnly:()=>e.#I(),reinitWithProof:n=>e.#G(n),isHistoryCapable:()=>e.#m(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await fo()).listConversations(this.#T(),e)}async getConversation(e,n){return(await fo()).getConversation(this.#T(),e,n)}async finalizeDisplayProjections(e,n){return(await fo()).finalizeDisplayProjections(this.#T(),e,n)}async deleteConversation(e,n){return(await fo()).deleteConversation(this.#T(),e,n)}async deleteAllConversations(e){return(await fo()).deleteAllConversations(this.#T(),e)}async resetVisitor(){return(await fo()).resetVisitor(this.#T())}async dispatch(e,n){return e.signal?.throwIfAborted(),Tr().catch(()=>{}),this.isClientTokenMode()?this.#le(e,n):this.isAgentMode()?this.#de(e,n):this.#ce(e,n)}async#le(e,n){let o=Zf();this.#N=o;let s=()=>this.#N===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=()=>{if(e.signal?.throwIfAborted(),!s())throw new DOMException("Turn superseded","AbortError")},c=this.clientSession??await this.initSession();l();let u=async()=>{l();let L=c,k=L.durableRecovery?.enabled===!0;if(k&&(!L.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");l();let R=await this.#S({...k||this.#m()?{conversationId:L.conversationId,durableResume:k}:{storedSessionId:L.sessionId},signal:e.signal});if(l(),L.conversationId&&R.conversationId!==L.conversationId||k&&R.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");c=this.#H(R,L.conversationId??null,!1),this.clientSession=c,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await u();let p=await this.#pe(e.messages),g=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,y=this.#m(),h={sessionId:c.sessionId,messages:e.messages.filter(_d).map(L=>{let k=y?gi(L):void 0;return{id:L.id,role:L.role,content:L.contentParts??L.llmContent??L.rawContent??L.content,...k!==void 0&&{displayContent:k}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},C=async()=>{l();let L=c.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return l(),this.#W(c.sessionId,p.clientTools,async k=>{l();let R=await this.#R(e.signal);l();let B={...h,sessionId:c.sessionId,...k,...R&&{identityProof:R}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...B,...R&&{identityProof:{provider:R.provider,token:"[REDACTED]"}}}),fetch(this.#b("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps,...L?{"X-Visitor-Token":L}:{}},body:JSON.stringify(B),signal:e.signal})})},E=await C();if(l(),E.response.status===401){let L=await E.response.clone().json().catch(()=>null);l(),L?.error==="Session not found or expired"&&(await u(),E=await C(),l())}let{response:A,commit:I}=E;if(!A.ok){let L=await A.json().catch(()=>({error:"Chat request failed"}));if(A.status===401&&L.error==="invalid_identity_proof"){let R=new bt("invalid_identity_proof",$C);throw i({type:"error",error:R}),R}if(A.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let R=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:R}),R}if(A.status===429){let R=new Error(L.hint||"Message limit reached for this session.");throw i({type:"error",error:R}),R}if(A.status===410&&L.error==="conversation_deleted"){let R=new bt("conversation_deleted","This conversation was deleted");throw i({type:"error",error:R}),R}let k=new Error(L.error||"Failed to send message");throw i({type:"error",error:k}),k}if(!A.body){let L=new Error("No response body received");throw i({type:"error",error:L}),L}I(),i({type:"status",status:"connected"});try{await this.#F(A.body,i,e.assistantMessageId)}finally{i({type:"status",status:"idle"})}}catch(l){let c=l instanceof Error?l:new Error(String(l));throw!(c instanceof bt)&&!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&i({type:"error",error:c}),c}}async#ce(e,n){n({type:"status",status:"connecting"});let o=await this.#pe(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.#t};if(this.#u)try{let l=await this.#u();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#f)try{i=await this.#f(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.#F(i.body,n)}finally{n({type:"status",status:"idle"})}}async#de(e,n){n({type:"status",status:"connecting"});let o=await this.#he(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.#t};if(this.#u)try{let l=await this.#u();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#f)try{i=await this.#f(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.#F(i.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,s){n({type:"status",status:"connected"});try{await this.#F(e,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){return(await Tr()).resolveApproval(this.#ae(),e,n)}async#W(e,n,o,s){let i=!!(n&&n.length>0),l=i?Vm(n):void 0,c=this.clientToolsFingerprintSessionId===e,u=i&&c&&this.lastSentClientToolsFingerprint===l,p=!i&&s?.emptyMeansReplace===!0&&this.#h===e,g=!1,y;for(let h=0;;h++){if(y=await o({...i&&(g||!u)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),y.status===409&&h===0&&i&&(await y.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:y,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.#h=e:p&&(this.#h=null)}}}async resumeFlow(e,n,o){return(await Tr()).resumeFlow(this.#ae(),e,n,o)}#k(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async#A(e){let n={};this.#r.length&&await Promise.all(this.#r.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.#k(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#w(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}#_(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(i=>i.id===o)?{...e,model:o}:e}async#he(e,n){let o=this.#x().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=Dd(th(e),p=>_d(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?nh(p):null),i=this.#w(n),l={agent:this.#_(this.config.agent??{agentId:o},i),messages:s,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};i&&(l.composerOptions=i);let c=[...Md(this.config),...await(await this.#d())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let u=await this.#A(e);return u&&(l.context=u),l}async#pe(e,n){let o=Dd(th(e),p=>_d(p)?nh(p):null),s=this.#x(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[p,g]of Object.entries(s.targetPayload))p!=="messages"&&(i[p]=g);let l=[...Md(this.config),...await(await this.#d())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#A(e);c&&(i.context=c);let u=this.#w(n);if(u&&(i.composerOptions=u),this.#a)try{let p=await this.#a({payload:{...i},config:this.config});if(p&&typeof p=="object"){let g=p;return i.clientTools!==void 0&&!("clientTools"in g)&&(g.clientTools=i.clientTools),g}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return i}async#F(e,n,o,s){let{streamResponse:i}=Yf()??await Tr();return i({config:()=>this.config,createStreamParser:this.#s,parseSSEEvent:this.#i,onSSEEvent:(l,c)=>this.#v?.(l,c)},e,n,o,s)}};var{setLoader:yM,load:UC,provide:bM,getSync:qC}=je({fallbackImport:()=>import("./ui-extras-entry-WAYFKVNW.js")});var vl=UC;var Fd=qC;var{setLoader:wM,load:jC,provide:SM,getSync:KC}=je({fallbackImport:()=>import("./session-actions-ISSKSI66.js")});var Nd=jC;var oh=KC;var GC=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function YC(t){let e=t?.text?.trim()??"";return e?vf(GC(t),e):""}function rh(t){let e=YC(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[zo(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
|
|
3
|
+
`):t};var qf="var(--persona-md-table-scroll-fade, 24px)",jf=new WeakSet;function Gf(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let s=document.createElement("div");s.className="persona-table-scroll",n.replaceWith(s),s.appendChild(n)})}function Kf(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,s=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":qf),t.style.setProperty("--persona-fade-r",s<=1?"0px":qf)}function Bd(t){jf.has(t)||(jf.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Kf(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Kf)}var{setLoader:UA,load:HC,provide:qA,getSync:RC}=je({fallbackImport:()=>import("./client-stream-42FOI3EC.js")});var Tr=HC;var Yf=RC;var{setLoader:GA,load:WC}=je({fallbackImport:()=>import("./webmcp-runtime-V6ZWW3PI.js")});var Qf=WC;var BC="agent_",DC="flow_";function Xf(t){return t.startsWith(BC)?{kind:"agentId",agentId:t}:t.startsWith(DC)?{kind:"flowId",flowId:t}:null}function Jf(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let l=n.slice(0,o),c=n.slice(o+1);if(l==="runtype"){let p=Xf(c);if(p)return p;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let u=e?.[l];if(!u)throw new Error(`[Persona] No target provider registered for "${l}". Add a \`targetProviders.${l}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:u(c).payload}}let s=Xf(n);if(s)return s;let i=e?.default;if(i)return{kind:"payload",payload:i(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function bl(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function hs(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function Zf(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var OC=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),_C=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),FC=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=OC(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:_C(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},Dd=(t,e)=>{let n=[],o=[],s=[],i="",l,c=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:i,toolCalls:o},{role:"tool",content:"",createdAt:i,toolResults:s}),o=[],s=[])};for(let u of t){let p=FC(u);if(p){let y=u.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(y===void 0||y!==l)&&c(),o.length===0&&(i=u.createdAt,l=y),o.some(h=>h.toolCallId===p.call.toolCallId)||(o.push(p.call),s.push(p.result));continue}let g=e(u);g&&(c(),n.push(g))}return c(),n};var{setLoader:eM,load:NC,provide:tM}=je({fallbackImport:()=>import("./client-history-GOZWBDA5.js")});var fo=NC;var VC="https://api.runtype.com/v1/dispatch",bt=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},eh=t=>"reason"in t?t.reason:void 0,$C="The identity proof was rejected",Od=(t,e)=>t instanceof bt&&t.code===e,_d=t=>t.voiceCaption?!1:!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0),th=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),nh=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function zC(t){switch(t){case"json":return Qm;case"regex-json":return Ym;case"xml":return Xm;default:return Gm}}var vi=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.#h=null;this.clientSession=null;this.#p=null;this.#S=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#n=null;this.#x=!1;this.#R=!1;this.#G=!1;this.#D=null;this.#$=new Set;this.#r=new Set;this.webMcpBridge=null;this.#l=null;this.#q=null;this.#me=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??VC,this.#o={"Content-Type":"application/json","X-Persona-Version":ps,...e.headers},this.debug=!!e.debug,this.#m=e.streamParser??zC(e.parserType),this.#t=e.contextProviders??[],this.#i=e.requestMiddleware,this.#s=e.customFetch,this.#a=e.parseSSEEvent,this.#v=e.getHeaders,e.webmcp?.enabled===!0&&(this.#l=this.#A(e.webmcp))}#e;#o;#m;#t;#i;#s;#a;#v;#c;#h;#p;#S;#n;#x;#R;#G;#D;#$;#r;#l;#f;#A(e){return Qf().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Nm,getToolDisplayTitle:Ka,loadPolyfill:$m});return this.#f!==void 0&&o.setConfirmHandler(this.#f),this.webMcpBridge=o,o}).catch(n=>(this.#l=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#P(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#l||(this.#l=this.#A(this.config.webmcp)),this.#l)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#f=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.#P().then(s=>s?s.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#u(){let{agentId:e,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:e,flowId:n};let i=Jf(o,s);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#u().agentId)}#d(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||tf}#M(e){return`${this.#d()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let s=n.conversationId,i=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!s||!i)throw new bt("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.#d()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),u=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":ps,"X-Visitor-Token":i},signal:e.signal});if(u.status===401&&!o){o=!0;let p=await fo();n=await p.recoverFromUnauthorized(this.#I(),await p.readErrorCode(this.#I(),u),null,!0);continue}if(!u.ok)throw await(await fo()).historyErrorFor(this.#I(),u,!0);return u}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#p||e&&new Date<e.expiresAt||this.#S===e?null:(this.#S=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#p)return this.#p;let e=this.#p=this.#re().then(n=>this.#p!==e?this.initSession():(this.clientSession=n,this.#S=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#p===e&&(this.#p=null)});return e}#C(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#x}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#y(){if(!this.#x){this.#z({state:"unavailable",reason:"history_disabled"}),this.#x=!0,!this.#R&&typeof console<"u"&&(this.#R=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#r])e(!1)}}getHistoryIdentityStatus(){return this.#D??this.#L()}subscribeHistoryIdentityStatus(e){return this.#$.add(e),()=>{this.#$.delete(e)}}subscribeHistoryAvailability(e){return this.#r.add(e),this.#x&&e(!1),()=>{this.#r.delete(e)}}#L(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#x?{state:"unavailable",reason:"history_disabled"}:this.#oe():{state:"unavailable",reason:"ineligible_mode"}}#oe(){let e=this.#D;return e?.state==="browser_only"?e:this.#Y()}#Y(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}#z(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&eh(n)===eh(e);if(this.#D=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.#$])s(e)}}async#w(e){let n=this.#C()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.#u(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,u={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.#M("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(u),signal:e.signal});if(!p.ok){let y=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&y.error==="visitor_history_disabled"){if(this.#y(),c)throw new bt("history_disabled","Visitor history is disabled for this surface");return this.#w({...e,omitVisitorFields:!0})}throw p.status===403&&y.error==="durable_recovery_disabled"?new bt("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&y.error==="visitor_required"?new bt("visitor_required","Visitor credential no longer resolves"):c&&p.status===404?new bt("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${y.hint||y.error}`):p.status===403?new Error(`Origin not allowed: ${y.hint||y.error}`):new Error(y.error||"Failed to initialize session")}let g=await p.json();return g.visitor?.token&&await this.historyInternals.visitorStore?.set(g.visitor.token),{sessionId:g.sessionId,expiresAt:new Date(g.expiresAt),flow:g.flow,...g.conversationId?{conversationId:g.conversationId}:{},...g.targetId?{targetId:g.targetId}:{},...g.conversationRevision?{conversationRevision:g.conversationRevision}:{},...g.durableRecovery?{durableRecovery:g.durableRecovery}:{},...g.visitor?{visitor:g.visitor}:{},config:{welcomeMessage:g.config.welcomeMessage,placeholder:g.config.placeholder,theme:g.config.theme}}}async#re(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#C()&&!n)return this.#W(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.#w({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#O(s,e,!1)}catch(s){if(!Od(s,"not_found")&&!Od(s,"visitor_required")&&!Od(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(e,!0)}return this.#W(e,!1)}async#W(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#V(e,n)):this.#V(e,n)}async#V(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.#w({storedSessionId:o}),i=await this.#ge(s);return this.#O(i,e,n)}async#ue(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.#w({storedSessionId:n,identityProof:e}),i=this.#O(s,o,!1);return this.clientSession=i,this.#p=null,this.#S=!1,this.resetClientToolsFingerprint(),i}async#ge(e){if(!e.visitor?.token||this.#G||!this.#C()&&e.durableRecovery?.enabled!==!0)return e;this.#G=!0;try{return await this.#w({storedSessionId:e.sessionId})}catch{return e}finally{this.#G=!1}}#O(e,n,o){let s=e.conversationId;return s&&n&&(o||s!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:s}),this.config.setStoredSessionId?.(e.sessionId),s&&(this.config.setStoredConversationId?.(s),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#U(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.#S=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#C())throw new bt("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new bt("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.#w({conversationId:e,identityProof:o});return this.#U(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#w({});return this.#U(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#C()&&this.#z(this.#Y())}clearClientSession(){this.clientSession=null,this.#p=null,this.#S=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#n=null}#Q(){return`${this.#d()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let s={...e,...this.config.clientToken&&{token:this.config.clientToken}},i=await fetch(this.#Q(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(s)});if(!i.ok){let l=await i.json().catch(()=>({error:"Feedback submission failed"}));throw i.status===401?(this.clientSession=null,this.#S=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async#ae(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let s,i;try{let l=Promise.resolve().then(()=>o());s=e?await Promise.race([l,new Promise((c,u)=>{i=()=>u(e.reason),e.addEventListener("abort",i,{once:!0}),e.aborted&&i()})]):await l}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{i&&e?.removeEventListener("abort",i)}if(typeof s!="string"||!s.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:s}}#q;#B(){let e=this;return this.#q??={get config(){return e.config},headers:this.#o,getHeaders:this.#v,debug:this.debug,clientApiBase:()=>e.#d(),getClientApiUrl:n=>e.#M(n),getWebMcpBridge:()=>e.#P(),sendWithClientToolsDiff:(n,o,s,i)=>e.#se(n,o,s,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#me;#I(){let e=this;return this.#me??={HistoryClientError:bt,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#d(),setHistoryIdentityStatus:n=>e.#z(n),browserOnlyStatus:()=>e.#oe(),derivedBrowserOnly:()=>e.#Y(),reinitWithProof:n=>e.#ue(n),isHistoryCapable:()=>e.#C(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await fo()).listConversations(this.#I(),e)}async getConversation(e,n){return(await fo()).getConversation(this.#I(),e,n)}async finalizeDisplayProjections(e,n){return(await fo()).finalizeDisplayProjections(this.#I(),e,n)}async deleteConversation(e,n){return(await fo()).deleteConversation(this.#I(),e,n)}async deleteAllConversations(e){return(await fo()).deleteAllConversations(this.#I(),e)}async resetVisitor(){return(await fo()).resetVisitor(this.#I())}async dispatch(e,n){return e.signal?.throwIfAborted(),Tr().catch(()=>{}),this.isClientTokenMode()?this.#fe(e,n):this.isAgentMode()?this.#le(e,n):this.#he(e,n)}async#fe(e,n){let o=Zf();this.#h=o;let s=()=>this.#h===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=()=>{if(e.signal?.throwIfAborted(),!s())throw new DOMException("Turn superseded","AbortError")},c=this.clientSession??await this.initSession();l();let u=async()=>{l();let L=c,k=L.durableRecovery?.enabled===!0;if(k&&(!L.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");l();let R=await this.#w({...k||this.#C()?{conversationId:L.conversationId,durableResume:k}:{storedSessionId:L.sessionId},signal:e.signal});if(l(),L.conversationId&&R.conversationId!==L.conversationId||k&&R.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");c=this.#O(R,L.conversationId??null,!1),this.clientSession=c,this.#S=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await u();let p=await this.#F(e.messages),g=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,y=this.#C(),h={sessionId:c.sessionId,messages:e.messages.filter(_d).map(L=>{let k=y?gi(L):void 0;return{id:L.id,role:L.role,content:L.contentParts??L.llmContent??L.rawContent??L.content,...k!==void 0&&{displayContent:k}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},C=async()=>{l();let L=c.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return l(),this.#se(c.sessionId,p.clientTools,async k=>{l();let R=await this.#ae(e.signal);l();let B={...h,sessionId:c.sessionId,...k,...R&&{identityProof:R}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...B,...R&&{identityProof:{provider:R.provider,token:"[REDACTED]"}}}),fetch(this.#M("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps,...L?{"X-Visitor-Token":L}:{}},body:JSON.stringify(B),signal:e.signal})})},E=await C();if(l(),E.response.status===401){let L=await E.response.clone().json().catch(()=>null);l(),L?.error==="Session not found or expired"&&(await u(),E=await C(),l())}let{response:A,commit:I}=E;if(!A.ok){let L=await A.json().catch(()=>({error:"Chat request failed"}));if(A.status===401&&L.error==="invalid_identity_proof"){let R=new bt("invalid_identity_proof",$C);throw i({type:"error",error:R}),R}if(A.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let R=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:R}),R}if(A.status===429){let R=new Error(L.hint||"Message limit reached for this session.");throw i({type:"error",error:R}),R}if(A.status===410&&L.error==="conversation_deleted"){let R=new bt("conversation_deleted","This conversation was deleted");throw i({type:"error",error:R}),R}let k=new Error(L.error||"Failed to send message");throw i({type:"error",error:k}),k}if(!A.body){let L=new Error("No response body received");throw i({type:"error",error:L}),L}I(),i({type:"status",status:"connected"});try{await this.#X(A.body,i,e.assistantMessageId)}finally{i({type:"status",status:"idle"})}}catch(l){let c=l instanceof Error?l:new Error(String(l));throw!(c instanceof bt)&&!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&i({type:"error",error:c}),c}}async#he(e,n){n({type:"status",status:"connecting"});let o=await this.#F(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.#o};if(this.#v)try{let l=await this.#v();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#s)try{i=await this.#s(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.#X(i.body,n)}finally{n({type:"status",status:"idle"})}}async#le(e,n){n({type:"status",status:"connecting"});let o=await this.#b(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.#o};if(this.#v)try{let l=await this.#v();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#s)try{i=await this.#s(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.#X(i.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,s){n({type:"status",status:"connected"});try{await this.#X(e,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){return(await Tr()).resolveApproval(this.#B(),e,n)}async#se(e,n,o,s){let i=!!(n&&n.length>0),l=i?Vm(n):void 0,c=this.clientToolsFingerprintSessionId===e,u=i&&c&&this.lastSentClientToolsFingerprint===l,p=!i&&s?.emptyMeansReplace===!0&&this.#n===e,g=!1,y;for(let h=0;;h++){if(y=await o({...i&&(g||!u)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),y.status===409&&h===0&&i&&(await y.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:y,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.#n=e:p&&(this.#n=null)}}}async resumeFlow(e,n,o){return(await Tr()).resumeFlow(this.#B(),e,n,o)}#ce(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async#_(e){let n={};this.#t.length&&await Promise.all(this.#t.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.#ce(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#E(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}#T(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(i=>i.id===o)?{...e,model:o}:e}async#b(e,n){let o=this.#u().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=Dd(th(e),p=>_d(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?nh(p):null),i=this.#E(n),l={agent:this.#T(this.config.agent??{agentId:o},i),messages:s,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};i&&(l.composerOptions=i);let c=[...Md(this.config),...await(await this.#P())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let u=await this.#_(e);return u&&(l.context=u),l}async#F(e,n){let o=Dd(th(e),p=>_d(p)?nh(p):null),s=this.#u(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[p,g]of Object.entries(s.targetPayload))p!=="messages"&&(i[p]=g);let l=[...Md(this.config),...await(await this.#P())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#_(e);c&&(i.context=c);let u=this.#E(n);if(u&&(i.composerOptions=u),this.#i)try{let p=await this.#i({payload:{...i},config:this.config});if(p&&typeof p=="object"){let g=p;return i.clientTools!==void 0&&!("clientTools"in g)&&(g.clientTools=i.clientTools),g}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return i}async#X(e,n,o,s){let{streamResponse:i}=Yf()??await Tr();return i({config:()=>this.config,createStreamParser:this.#m,parseSSEEvent:this.#a,onSSEEvent:(l,c)=>this.#c?.(l,c)},e,n,o,s)}};var{setLoader:yM,load:UC,provide:bM,getSync:qC}=je({fallbackImport:()=>import("./ui-extras-entry-WAYFKVNW.js")});var vl=UC;var Fd=qC;var{setLoader:wM,load:jC,provide:SM,getSync:KC}=je({fallbackImport:()=>import("./session-actions-ISSKSI66.js")});var Nd=jC;var oh=KC;var GC=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function YC(t){let e=t?.text?.trim()??"";return e?vf(GC(t),e):""}function rh(t){let e=YC(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[zo(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
|
|
4
4
|
|
|
5
|
-
`)}:{}}function Cl(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function sh(t,e){let n=t.findIndex(s=>s.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function Vd(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function ih(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return Vd(t,n.id)?n.id:null}return null}function $d(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}function zd(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(s=>s.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Ci=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(e.text),i=o.getVoices();if(e.voice){let l=i.find(c=>c.name===e.voice);l&&(s.voice=l)}else i.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(i):zd(i));e.rate!==void 0&&(s.rate=e.rate),e.pitch!==void 0&&(s.pitch=e.pitch),s.onend=()=>n.onEnd?.(),s.onerror=l=>{let c=l.error;c==="canceled"||c==="interrupted"?n.onEnd?.():n.onError?.(new Error(c||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var wl=class{#e=null;#
|
|
5
|
+
`)}:{}}function Cl(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function sh(t,e){let n=t.findIndex(s=>s.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function Vd(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function ih(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return Vd(t,n.id)?n.id:null}return null}function $d(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}function zd(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(s=>s.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Ci=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(e.text),i=o.getVoices();if(e.voice){let l=i.find(c=>c.name===e.voice);l&&(s.voice=l)}else i.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(i):zd(i));e.rate!==void 0&&(s.rate=e.rate),e.pitch!==void 0&&(s.pitch=e.pitch),s.onend=()=>n.onEnd?.(),s.onerror=l=>{let c=l.error;c==="canceled"||c==="interrupted"?n.onEnd?.():n.onError?.(new Error(c||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var wl=class{#e=null;#o=null;#m="idle";#t=new Set;#i=0;#s;constructor(e){this.#s=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#o===e?this.#m:"idle"}activeMessageId(){return this.#o}onChange(e){return this.#t.add(e),()=>this.#t.delete(e)}toggle(e,n){if(this.#o===e){if(this.#m==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#a(e,"paused")):this.stop();return}if(this.#m==="paused"){this.#e?.resume(),this.#a(e,"playing");return}if(this.#m==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.#i;this.#e?.stop(),this.#a(e,"loading");try{if(!this.#e){let s=await this.#s();if(o!==this.#i)return;if(!s){this.#a(null,"idle");return}this.#e=s}this.#e.speak(n,{onStart:()=>{o===this.#i&&this.#a(e,"playing")},onEnd:()=>{o===this.#i&&this.#a(null,"idle")},onError:()=>{o===this.#i&&this.#a(null,"idle")}})}catch{o===this.#i&&this.#a(null,"idle")}}stop(){this.#i++,this.#e?.stop(),this.#a(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#t.clear()}#a(e,n){this.#o=n==="idle"?null:e,this.#m=n;for(let o of this.#t)o(this.#o,this.#m)}};var wi=class{#e;#o=!1;start(e){this.#e=e,this.#o=!1}cancel(){this.#o=!0}accepts(e){return!this.#o&&(!e||!this.#e||e===this.#e)}};var{setLoader:HM,load:QC,getSync:XC}=je({fallbackImport:()=>import("./voice-runtime-XLU6YK2N.js")});var Si=QC,ah=XC;function Ud(t){if(!t)return"";let e=JC(t);return lh(e!==null?e:t)}function JC(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function lh(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
6
6
|
`),e=e.replace(/\n{2,}/g,`
|
|
7
7
|
`),e.trim()}var ch=null;var qd=()=>ch?ch():import("./runtype-tts-entry-NFBVWR7N.js");var{setLoader:OM,load:ZC}=je({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var dh=ZC;var ew=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function tw(t,e){return ew.some(n=>t[n]!==e[n])}var jn=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function jd(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
8
8
|
|
|
9
|
-
_Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.#e=Date.now();this.clientSession=null;this.agentExecution=null;this.#t=null;this.#s=null;this.#r=!1;this.#a=null;this.#f=null;this.#i=null;this.artifacts=new Map;this.#u=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#v=0;this.webMcpApprovalResolvers=new Map;this.#N=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#n=null;this.#l=null;this.#h=0;this.#D=0;this.#O=!1;this.#V="disconnected";this.#o=null;this.#c=null;this.#g=null;this.#C=0;this.#L=!1;this.#y=null;this.#d=!1;this.#x=null;this.#E=new Map;this.#b=null;this.#m=new Map;this.#re=null;this.#se=null;this.#K=!1;this.#I=null;this.#$=null;this.#S=!1;this.#z=null;this.#G=null;this.#Y=null;this.#H=new wi;this.#ne=Promise.resolve();this.#U=null;this.#R=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new wl(()=>this.#me());this.#Qe=null;this.#q=0;this.handleEvent=e=>{let n=this.#R;if(n&&(e.type==="error"||e.type==="status"&&e.status==="error"?n.failed=!0:e.type==="message"&&e.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id))),e.type==="message"){this.upsertMessage(e.message),e.message.variant==="approval"&&e.message.approval&&e.message.approval.status!=="pending"&&this.#Be(e.message.id),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.#s=e.message.id),(e.message.variant==="approval"||e.message.agentMetadata?.awaitingLocalTool===!0)&&Nd().catch(()=>{});let o=e.message.toolCall,s=!!o?.name&&(Cd(o.name)||o.name===Ad&&ds(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&s&&this.#Xe(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.#nt(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.#ot()){this.#we();return}if(this.#P(e.status),e.status==="connecting")this.#p(!0);else if(e.status==="idle"||e.status==="error"){this.#We()||this.#ge(),this.webMcpResolveControllers.size===0&&(this.#p(!1),this.abortController=null,this.#Ue(),this.#$e());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.#Je()}}else e.type==="error"?(this.#P("error"),this.#ge(),this.webMcpResolveControllers.size===0&&(this.#p(!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.#tt(e)};this.historyInternals=this.#de(o),this.messages=[...e.initialMessages??[]].map(s=>({...s,sequence:s.sequence??this.#M()})),this.messages=this.#j(this.messages),this.client=new vi(e,this.historyInternals),this.#Ee(),this.#He();for(let s of e.initialArtifacts??[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.#u=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Z(),this.callbacks.onStatusChanged(this.status),this.#ie(),this.#te()}#e;#t;#s;#r;#a;#f;#i;#u;#v;#N;#n;#l;#h;#D;#O;#V;#o;#c;#g;#C;#L;#y;#d;#x;#E;#b;#m;#re;#se;#K;#I;#$;#S;#z;#te(){this.config.voiceRecognition?.provider&&Si().catch(()=>{})}#ie(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||qd().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Nf(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#O}getVoiceStatus(){return this.#V}getVoiceDisclosure(){return this.#n?.getDisclosure?.()??null}getVoiceLevel(){return this.#n?.onLevel?this.#D:null}getVoiceInterruptionMode(){return this.#n?.getInterruptionMode?this.#n.getInterruptionMode():"none"}stopVoicePlayback(){this.#n?.stopPlayback&&(this.#H.cancel(),this.#U?.cancel(),this.#n.stopPlayback())}isBargeInActive(){return this.#n?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#n?.deactivateBargeIn&&await this.#n.deactivateBargeIn()}#G;#Y;#H;#ne;#U;#R;#me(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Ci.isSupported()?new Ci({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,s=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,l=e.browserFallback!==!1;if(o&&s&&i)return qd().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:u})=>{let p=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new u(p,n,{onFallback:g=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${g.message}`)}):p});if(l&&n)return i&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#ne,s=++this.#h;this.#l=Si().then(async i=>{await o,s===this.#h&&this.#ae(i,i.createVoiceProvider(n))}).catch(i=>{console.error("Failed to setup voice:",i)}).finally(()=>{s===this.#h&&(this.#l=null)})}catch(n){console.error("Failed to setup voice:",n)}}#ae(e,n){this.#n=n;let o=this;e.wireSessionVoice({session:this,provider:()=>o.#n,generation:()=>o.#h,get keyed(){return o.#U},set keyed(s){o.#U=s},get pendingUser(){return o.#G},set pendingUser(s){o.#G=s},get pendingAssistant(){return o.#Y},set pendingAssistant(s){o.#Y=s},turns:()=>o.#H,busy:()=>o.#fe(),setStreaming:s=>o.#p(s),setDelegation:s=>{o.#R=s},setLevel:s=>{o.#D=s},setStatus:s=>{o.#V=s,o.#O=s==="listening"},settlePending:s=>o.#le(s)},n,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#n&&this.#l&&await this.#l,!this.#n){console.error("Voice not configured");return}if(this.#O)await this.#n.stopListening();else{this.stopSpeaking();try{await this.#n.startListening()}catch(e){console.error("Failed to start voice:",e)}}}prewarmVoice(){if(!Nt(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#h,n=()=>{let o=this.#n;!o?.prewarm||e!==this.#h||this.#O||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#n&&this.#l){this.#l.then(n,()=>{});return}n()}#fe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#r||this.status==="resuming"}cleanupVoice(){let e=this.#n!==null;if(this.#h++,this.#l=null,this.#n){let n=this.#n;this.#n=null,this.#ne=this.#T(n)}this.#O=!1,this.#V="disconnected",this.#le(!0),this.#U?.settle(),this.#U=null,this.#H=new wi,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#T(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#le(e){let n=e?this.#G:null,o=this.#Y;!n&&!o||(o&&this.#H.cancel(),e&&(this.#G=null),this.#Y=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(s=>s.id!==n&&s.id!==o?[s]:s.id===o&&!s.content.trim()?[]:[{...s,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.#p(!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.#se=this.historyInternals.getStoredConversationRevision?.()??null,this.#K=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,e)})}setClientSession(e,n){this.clientSession=e,this.#ce(e,n)}#ce(e,n=!this.messages.length){if(this.#L||!e.config.welcomeMessage||!n)return;let o=this.messages[0],s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.#M()};this.#B(s)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.#de(e),this.client.setHistoryInternals(this.historyInternals),this.#Ee()}destroy(){this.cleanupVoice(),this.#I?.(),this.#I=null,this.#$=null}#de(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.#Oe(o),n?.(o)}}}get#W(){return this.historyInternals.historyProvider??null}#k(){let e=this.#W;if(!e)throw new jn("history_unavailable","No conversation history provider is installed");return e}#A(e){let n=this.#k(),o=e??this.config.features?.history?.scope,s=this.config.getIdentityProof?"verified-user":"browser",i=o??(n.capabilities.scopes.includes(s)?s:n.capabilities.scopes[0]??s);if(!n.capabilities.scopes.includes(i))throw new el("unsupported_scope","This history scope is not supported.");return{scope:i}}getHistoryState(){return{activeConversationId:this.#o,conversationRevision:this.#c,nextMessageCursor:this.#g,recovery:this.#y,sendBlocked:this.#d}}getActiveConversationId(){return this.#o}#w(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#_(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.#x;e&&await e.catch(()=>{});let n=this.#b;n&&await n.catch(()=>{})}#he(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new jn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#k().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.#A(e?.scope)})}async openConversation(e,n){let o=this.#k();this.#he();let s=this.#A(n?.scope);await this.awaitHistorySettled();let i=++this.#C,l=await o.getPage(e,{context:s});if(i!==this.#C)throw new jn("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.#C)throw c.discard(),new jn("superseded","A later selection won");this.#L=!0;try{await this.#Ae(c)}finally{this.#L=!1}this.#o=c.conversationId||e,this.#c=c.conversationRevision||l.conversationRevision||null,this.#g=l.nextCursor,this.#y=null,this.#d=!1,this.#Me();for(let u of l.messages)this.#m.set(u.id,u.content);return this.#ye(),this.hydrateMessages(l.messages),this.#w(),{summary:l.summary,nextMessageCursor:l.nextCursor}}loadOlderMessages(e,n,o){let s=this.#k(),i=this.#A(o?.scope),l=n??this.#g;if(!l)return Promise.resolve({messages:[],nextMessageCursor:null});let c=`${e} ${l}`,u=this.#E.get(c);if(u)return u;let p=this.#pe(s,e,l,i).finally(()=>{this.#E.delete(c)});return this.#E.set(c,p),p}async#pe(e,n,o,s){let i=this.messages[0]?.createdAt,l=await e.getPage(n,{cursor:o,...i?{beforeCreatedAt:i}:{},context:s});if(this.#o&&this.#o!==n)return{messages:[],nextMessageCursor:l.nextCursor};let c=Td(this.messages,l.messages);this.messages=this.#j(c.map(u=>this.#oe(u))),this.#g=l.nextCursor;for(let u of l.messages)this.#m.set(u.id,u.content);return this.historyInternals.setStoredMessageCursor?.(l.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#w(),{messages:l.messages,nextMessageCursor:l.nextCursor}}async startNewConversation(e){let n=this.#k(),o=this.#A(e?.scope);await this.awaitHistorySettled();let s=++this.#C,i=await n.prepareStartNew({context:o});if(s!==this.#C)throw i.discard(),new jn("superseded","A later action won");await this.#F(i)}async#F(e){this.#Q(),await this.#Ae(e),this.#o=e.conversationId||null,this.#c=e.conversationRevision||null,this.#g=null,this.#y=null,this.#d=!1,this.#ye(),this.#w()}async deleteConversation(e,n){let o=this.#k(),s=this.#A(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:s}),e===this.#o&&await this.#Se(s)}async updateConversation(e,n,o){let s=this.#k();if(!s.update)throw new jn("history_unavailable","This history provider cannot update conversations");let i=this.#A(o?.scope);return await this.awaitHistorySettled(),s.update(e,n,{context:i})}canUpdateConversations(){return typeof this.#W?.update=="function"}async clearConversationHistory(e){let n=this.#k(),o=this.#A(e?.scope);await this.awaitHistorySettled();let s=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.#Se(o),s}async resetHistoryDevice(){let e=this.#k();if(!e.resetDevice)throw new jn("history_unavailable","This history provider cannot reset the device");this.#C+=1,this.#b=null;try{return await e.resetDevice()}finally{this.#Q(),this.#o=null,this.#c=null,this.#g=null,this.#y=null,this.#d=!1,this.#w()}}async#Se(e){this.#C+=1,this.#b=null,this.#Q(),this.#o=null,this.#c=null,this.#g=null,this.#d=!0,this.#y=null,this.#w(),await this.#xe(e)}async#xe(e){let n=this.#W;if(!n){this.#d=!1,this.#w();return}try{let o=await n.prepareStartNew({context:e});await this.#F(o)}catch{this.#d=!0,this.#y="new_conversation_required",this.#w(),this.#_("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#De(){if(!(this.#y!=="new_conversation_required"||!this.#W)&&(this.#y=null,await this.#xe(this.#A()),this.#y==="new_conversation_required"))throw new jn("new_conversation_required","A new conversation is required before sending")}async#Ae(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#o=e.conversationId,this.#c=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#L||this.#ce(e)}#ye(){this.#o?this.config.setStoredConversationId?.(this.#o):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#c),this.historyInternals.setStoredMessageCursor?.(this.#g)}#Me(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ce(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#m.clear(),this.#X(null)}#Q(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ee(),this.#J(),this.#q++,this.messages=[],this.#Me(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#p(!1),this.#P("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Oe(e){this.#C+=1,this.#b=null,this.#d=!0,this.#Q(),this.#o=e.conversationId,this.#c=null,this.#g=null,this.#y=null,this.#w(),this.#_("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#x=Promise.resolve().then(()=>{this.#d=!1,this.#x=null,this.#w()})}#Ee(){let e=this.historyInternals.visitorStore??null;e!==this.#$&&(this.#I?.(),this.#I=null,this.#$=e,e&&(this.#I=e.subscribe(n=>this.#_e(n))))}#_e(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#C+=1,this.#b=null,this.#S=!0,this.#z=null;let n=this.messages.length>0;n||this.#o!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#Q():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#X(null)),this.#o=null,this.#c=null,this.#g=null,this.#y=null,this.#w(),n&&this.#_("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Fe(){return this.#S?(this.#z||(this.#z=this.#Ne().finally(()=>{this.#z=null})),this.#z):Promise.resolve()}async#Ne(){if(!this.isClientTokenMode()){this.#S=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#S=!1}catch{}}reconcileBootConversation(e){let n=this.#W,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#o;if(!n||!o)return Promise.resolve();let s=this.#A(e?.scope);this.#d=!0,this.#w();let i=this.#Ve(n,o,s).finally(()=>{this.#d=this.#y!==null,this.#x===i&&(this.#x=null),this.#w()});return this.#x=i,i}async#Ve(e,n,o){this.#o=n;let s=this.clientSession?.conversationRevision??this.#c??null,i=this.#K?this.#se:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#K=!1,this.#g=this.historyInternals.getStoredMessageCursor?.()??this.#g,await this.replayPendingProjections(),s&&i&&s===i){this.#c=s;return}let l=await e.getPage(n,{context:o}),c=new Set(l.messages.map(y=>y.id)),u=this.messages.some(y=>c.has(y.id)),p=l.messages[0]?.createdAt,g;if(!u)g=l.messages.map(y=>this.#oe(y));else{let y=this.#t?this.#s:null,h=this.messages.filter(C=>c.has(C.id)||C.id===y?!0:p!==void 0&&C.createdAt<p);g=Td(h,l.messages).map(C=>this.#oe(C))}this.#g=l.nextCursor,this.#c=l.conversationRevision||s||null,this.#m.clear();for(let y of l.messages)this.#m.set(y.id,y.content);this.#ye(),this.messages=this.#j(g),this.callbacks.onMessagesChanged([...this.messages])}#be(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#X(e){this.#re=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Te(){return this.historyInternals.getPendingDisplayProjections?.()??this.#re}#ke(e){if(this.#be())for(let n of e){let o=gi(n);o!==void 0&&this.#m.set(n.id,o)}}#$e(){if(!this.#be())return;let e=this.#o;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let s=gi(o);s!==void 0&&this.#m.get(o.id)!==s&&n.push({id:o.id,displayContent:s})}n.length!==0&&(this.#X({conversationId:e,messageIds:n.map(o=>o.id)}),this.#Pe(e,n))}#Pe(e,n){let s=(this.#b??Promise.resolve()).catch(()=>{}).then(()=>this.#Le(e,n,!1)).finally(()=>{this.#b===s&&(this.#b=null)});this.#b=s}async#Le(e,n,o){if(this.#o!==e)return;let s=n.filter(i=>this.#m.get(i.id)!==i.displayContent);if(s.length===0){this.#ve(e,n);return}try{let{conversationRevision:i}=await this.client.finalizeDisplayProjections(e,s);for(let l of s)this.#m.set(l.id,l.displayContent);this.#o===e&&i&&(this.#c=i),this.#ve(e,n)}catch(i){if(!o&&this.#ze(i)){await this.#Le(e,s,!0);return}if(i instanceof bt&&(i.code==="not_found"||i.code==="conversation_deleted")){this.#ve(e,n);return}this.#_("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#ze(e){return e instanceof bt?e.code==="request_failed":e instanceof Error}#ve(e,n){let o=this.#Te();if(!o||o.conversationId!==e)return;let s=new Set(n.map(l=>l.id)),i=o.messageIds.filter(l=>!s.has(l));this.#X(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#be())return;let e=this.#Te();if(!e)return;if(this.#o&&e.conversationId!==this.#o){this.#X(null);return}let n=[];for(let o of e.messageIds){let s=this.messages.find(i=>i.id===o);!s||typeof s.content!="string"||n.push({id:o,displayContent:s.content})}if(n.length===0){this.#X(null);return}this.#Pe(e.conversationId,n),await this.#b?.catch(()=>{})}#Ue(){this.#o&&(this.#c=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Ie(){await this.awaitHistorySettled(),await this.#Fe(),this.#y==="new_conversation_required"&&await this.#De()}static#qe(e){return e instanceof bt&&e.code==="conversation_deleted"}async#je(e,n,o,s,i){this.#ke(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions,interrupt:i?.interrupt},this.handleEvent);return}catch(l){if(!t.#qe(l))throw l;let c=await this.#Ke(s);if(!c)throw l;this.#ke([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions},this.handleEvent)}}async#Ke(e){let n=this.messages.find(s=>s.id===e);if(!n)return null;let o={...n};this.#C+=1,this.#b=null,this.#Q(),this.#o=null,this.#c=null,this.#g=null,this.#L=!0;try{let s=this.#W;if(s){let i=await s.prepareStartNew({context:this.#A()});await this.#F(i)}else{this.client.clearClientSession();let i=await this.client.initSession();this.bindActivatedSession(i)}}catch{return this.#d=!0,this.#y="new_conversation_required",this.#w(),this.#_("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#L=!1}return this.#B(o),this.#p(!0),this.#_("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(s=>s.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},s=Ff(this.config,o),i=tw(this.config,o);this.config=o,s&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Nt(o.voiceRecognition.provider)&&this.setupVoice());let l=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!i){this.client.updateConfig(o),l&&this.#Re();return}this.#J(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let c=this.client.getSSEEventCallback();this.client=new vi(this.config,this.historyInternals),l&&this.#Re(),this.#He(),c&&this.client.setSSEEventCallback(c)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:s,contentParts:i,id:l,createdAt:c,sequence:u,streaming:p=!1,voiceProcessing:g,voiceCaption:y,rawContent:h}=e,E={id:l??(n==="user"?bl():n==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:u??this.#M(),streaming:p,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...y&&{voiceCaption:y},...h!==void 0&&{rawContent:h}};return this.upsertMessage(E),E}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:s,content:i,llmContent:l,contentParts:c,id:u,createdAt:p,sequence:g,streaming:y=!1,voiceProcessing:h,rawContent:C}=o,A={id:u??(s==="user"?bl():s==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:p??new Date().toISOString(),sequence:g??this.#M(),streaming:y,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...h!==void 0&&{voiceProcessing:h},...C!==void 0&&{rawContent:C}};n.push(A)}return this.messages=this.#j([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:s="",llmContent:i,id:l,createdAt:c,sequence:u}=e,p={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(p),...i!==void 0&&{llmContent:i},...l!==void 0&&{id:l},...c!==void 0&&{createdAt:c},...u!==void 0&&{sequence:u}})}async#Ge(e,n,o){let s;try{s=await o()}catch{return}let i=s.blocks.join(`
|
|
9
|
+
_Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.#e=new Map;this.abortController=null;this.#m=Date.now();this.clientSession=null;this.agentExecution=null;this.#t=null;this.#i=null;this.#s=!1;this.#a=null;this.#v=null;this.#c=null;this.artifacts=new Map;this.#h=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#p=0;this.webMcpApprovalResolvers=new Map;this.#S=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#n=null;this.#x=null;this.#R=0;this.#G=0;this.#D=!1;this.#$="disconnected";this.#r=null;this.#l=null;this.#f=null;this.#A=0;this.#P=!1;this.#u=null;this.#d=!1;this.#M=null;this.#C=new Map;this.#y=null;this.#L=new Map;this.#oe=null;this.#Y=null;this.#z=!1;this.#w=null;this.#re=null;this.#W=!1;this.#V=null;this.#O=null;this.#U=null;this.#Q=new wi;this.#ae=Promise.resolve();this.#q=null;this.#B=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new wl(()=>this.#me());this.#Ze=null;this.#j=0;this.handleEvent=e=>{let n=this.#B;if(n&&(e.type==="error"||e.type==="status"&&e.status==="error"?n.failed=!0:e.type==="message"&&e.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id))),e.type==="message"){this.upsertMessage(e.message),e.message.variant==="approval"&&e.message.approval&&e.message.approval.status!=="pending"&&this.#e.set(e.message.id,this.#o),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant==="approval"||e.message.agentMetadata?.awaitingLocalTool===!0)&&Nd().catch(()=>{});let o=e.message.toolCall,s=!!o?.name&&(Cd(o.name)||o.name===Ad&&ds(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&s&&this.#et(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.#st(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.#it()){this.#Se();return}if(this.#H(e.status),e.status==="connecting")this.#g(!0);else if(e.status==="idle"||e.status==="error"){this.#De()||this.#pe(),this.webMcpResolveControllers.size===0&&(this.#g(!1),this.abortController=null,this.#Ke(),this.#qe());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.#tt()}}else e.type==="error"?(this.#H("error"),this.#pe(),this.webMcpResolveControllers.size===0&&(this.#g(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.#rt(e)};this.historyInternals=this.#ce(o),this.messages=[...e.initialMessages??[]].map(s=>({...s,sequence:s.sequence??this.#k()})),this.messages=this.#K(this.messages),this.client=new vi(e,this.historyInternals),this.#ke(),this.#We();for(let s of e.initialArtifacts??[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.#h=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#te(),this.callbacks.onStatusChanged(this.status),this.#ge(),this.#ue()}#e;#o;#m;#t;#i;#s;#a;#v;#c;#h;#p;#S;#n;#x;#R;#G;#D;#$;#r;#l;#f;#A;#P;#u;#d;#M;#C;#y;#L;#oe;#Y;#z;#w;#re;#W;#V;#ue(){this.config.voiceRecognition?.provider&&Si().catch(()=>{})}#ge(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||qd().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Nf(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#D}getVoiceStatus(){return this.#$}getVoiceDisclosure(){return this.#n?.getDisclosure?.()??null}getVoiceLevel(){return this.#n?.onLevel?this.#G:null}getVoiceInterruptionMode(){return this.#n?.getInterruptionMode?this.#n.getInterruptionMode():"none"}stopVoicePlayback(){this.#n?.stopPlayback&&(this.#Q.cancel(),this.#q?.cancel(),this.#n.stopPlayback())}isBargeInActive(){return this.#n?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#n?.deactivateBargeIn&&await this.#n.deactivateBargeIn()}#O;#U;#Q;#ae;#q;#B;#me(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Ci.isSupported()?new Ci({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,s=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,l=e.browserFallback!==!1;if(o&&s&&i)return qd().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:u})=>{let p=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new u(p,n,{onFallback:g=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${g.message}`)}):p});if(l&&n)return i&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#ae,s=++this.#R;this.#x=Si().then(async i=>{await o,s===this.#R&&this.#I(i,i.createVoiceProvider(n))}).catch(i=>{console.error("Failed to setup voice:",i)}).finally(()=>{s===this.#R&&(this.#x=null)})}catch(n){console.error("Failed to setup voice:",n)}}#I(e,n){this.#n=n;let o=this;e.wireSessionVoice({session:this,provider:()=>o.#n,generation:()=>o.#R,get keyed(){return o.#q},set keyed(s){o.#q=s},get pendingUser(){return o.#O},set pendingUser(s){o.#O=s},get pendingAssistant(){return o.#U},set pendingAssistant(s){o.#U=s},turns:()=>o.#Q,busy:()=>o.#fe(),setStreaming:s=>o.#g(s),setDelegation:s=>{o.#B=s},setLevel:s=>{o.#G=s},setStatus:s=>{o.#$=s,o.#D=s==="listening"},settlePending:s=>o.#le(s)},n,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#n&&this.#x&&await this.#x,!this.#n){console.error("Voice not configured");return}if(this.#D)await this.#n.stopListening();else{this.stopSpeaking();try{await this.#n.startListening()}catch(e){console.error("Failed to start voice:",e)}}}prewarmVoice(){if(!Nt(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#R,n=()=>{let o=this.#n;!o?.prewarm||e!==this.#R||this.#D||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#n&&this.#x){this.#x.then(n,()=>{});return}n()}#fe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#s||this.status==="resuming"}cleanupVoice(){let e=this.#n!==null;if(this.#R++,this.#x=null,this.#n){let n=this.#n;this.#n=null,this.#ae=this.#he(n)}this.#D=!1,this.#$="disconnected",this.#le(!0),this.#q?.settle(),this.#q=null,this.#Q=new wi,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#he(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#le(e){let n=e?this.#O:null,o=this.#U;!n&&!o||(o&&this.#Q.cancel(),e&&(this.#O=null),this.#U=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(s=>s.id!==n&&s.id!==o?[s]:s.id===o&&!s.content.trim()?[]:[{...s,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.#g(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#Y=this.historyInternals.getStoredConversationRevision?.()??null,this.#z=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,e)})}setClientSession(e,n){this.clientSession=e,this.#se(e,n)}#se(e,n=!this.messages.length){if(this.#P||!e.config.welcomeMessage||!n)return;let o=this.messages[0],s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.#k()};this.#N(s)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.#ce(e),this.client.setHistoryInternals(this.historyInternals),this.#ke()}destroy(){this.cleanupVoice(),this.#w?.(),this.#w=null,this.#re=null}#ce(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.#Ne(o),n?.(o)}}}get#_(){return this.historyInternals.historyProvider??null}#E(){let e=this.#_;if(!e)throw new jn("history_unavailable","No conversation history provider is installed");return e}#T(e){let n=this.#E(),o=e??this.config.features?.history?.scope,s=this.config.getIdentityProof?"verified-user":"browser",i=o??(n.capabilities.scopes.includes(s)?s:n.capabilities.scopes[0]??s);if(!n.capabilities.scopes.includes(i))throw new el("unsupported_scope","This history scope is not supported.");return{scope:i}}getHistoryState(){return{activeConversationId:this.#r,conversationRevision:this.#l,nextMessageCursor:this.#f,recovery:this.#u,sendBlocked:this.#d}}getActiveConversationId(){return this.#r}#b(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#F(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.#M;e&&await e.catch(()=>{});let n=this.#y;n&&await n.catch(()=>{})}#X(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new jn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#E().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.#T(e?.scope)})}async openConversation(e,n){let o=this.#E();this.#X();let s=this.#T(n?.scope);await this.awaitHistorySettled();let i=++this.#A,l=await o.getPage(e,{context:s});if(i!==this.#A)throw new jn("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.#A)throw c.discard(),new jn("superseded","A later selection won");this.#P=!0;try{await this.#Ee(c)}finally{this.#P=!1}this.#r=c.conversationId||e,this.#l=c.conversationRevision||l.conversationRevision||null,this.#f=l.nextCursor,this.#u=null,this.#d=!1,this.#Te();for(let u of l.messages)this.#L.set(u.id,u.content);return this.#be(),this.hydrateMessages(l.messages),this.#b(),{summary:l.summary,nextMessageCursor:l.nextCursor}}loadOlderMessages(e,n,o){let s=this.#E(),i=this.#T(o?.scope),l=n??this.#f;if(!l)return Promise.resolve({messages:[],nextMessageCursor:null});let c=`${e} ${l}`,u=this.#C.get(c);if(u)return u;let p=this.#_e(s,e,l,i).finally(()=>{this.#C.delete(c)});return this.#C.set(c,p),p}async#_e(e,n,o,s){let i=this.messages[0]?.createdAt,l=await e.getPage(n,{cursor:o,...i?{beforeCreatedAt:i}:{},context:s});if(this.#r&&this.#r!==n)return{messages:[],nextMessageCursor:l.nextCursor};let c=Td(this.messages,l.messages);this.messages=this.#K(c.map(u=>this.#ie(u))),this.#f=l.nextCursor;for(let u of l.messages)this.#L.set(u.id,u.content);return this.historyInternals.setStoredMessageCursor?.(l.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#b(),{messages:l.messages,nextMessageCursor:l.nextCursor}}async startNewConversation(e){let n=this.#E(),o=this.#T(e?.scope);await this.awaitHistorySettled();let s=++this.#A,i=await n.prepareStartNew({context:o});if(s!==this.#A)throw i.discard(),new jn("superseded","A later action won");await this.#ye(i)}async#ye(e){this.#J(),await this.#Ee(e),this.#r=e.conversationId||null,this.#l=e.conversationRevision||null,this.#f=null,this.#u=null,this.#d=!1,this.#be(),this.#b()}async deleteConversation(e,n){let o=this.#E(),s=this.#T(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:s}),e===this.#r&&await this.#Ae(s)}async updateConversation(e,n,o){let s=this.#E();if(!s.update)throw new jn("history_unavailable","This history provider cannot update conversations");let i=this.#T(o?.scope);return await this.awaitHistorySettled(),s.update(e,n,{context:i})}canUpdateConversations(){return typeof this.#_?.update=="function"}async clearConversationHistory(e){let n=this.#E(),o=this.#T(e?.scope);await this.awaitHistorySettled();let s=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.#Ae(o),s}async resetHistoryDevice(){let e=this.#E();if(!e.resetDevice)throw new jn("history_unavailable","This history provider cannot reset the device");this.#A+=1,this.#y=null;try{return await e.resetDevice()}finally{this.#J(),this.#r=null,this.#l=null,this.#f=null,this.#u=null,this.#d=!1,this.#b()}}async#Ae(e){this.#A+=1,this.#y=null,this.#J(),this.#r=null,this.#l=null,this.#f=null,this.#d=!0,this.#u=null,this.#b(),await this.#Me(e)}async#Me(e){let n=this.#_;if(!n){this.#d=!1,this.#b();return}try{let o=await n.prepareStartNew({context:e});await this.#ye(o)}catch{this.#d=!0,this.#u="new_conversation_required",this.#b(),this.#F("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#Fe(){if(!(this.#u!=="new_conversation_required"||!this.#_)&&(this.#u=null,await this.#Me(this.#T()),this.#u==="new_conversation_required"))throw new jn("new_conversation_required","A new conversation is required before sending")}async#Ee(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#r=e.conversationId,this.#l=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#P||this.#se(e)}#be(){this.#r?this.config.setStoredConversationId?.(this.#r):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#l),this.historyInternals.setStoredMessageCursor?.(this.#f)}#Te(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#we(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#L.clear(),this.#Z(null)}#J(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.messages=[],this.#Te(),this.#C.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#g(!1),this.#H("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Ne(e){this.#A+=1,this.#y=null,this.#d=!0,this.#J(),this.#r=e.conversationId,this.#l=null,this.#f=null,this.#u=null,this.#b(),this.#F("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#M=Promise.resolve().then(()=>{this.#d=!1,this.#M=null,this.#b()})}#ke(){let e=this.historyInternals.visitorStore??null;e!==this.#re&&(this.#w?.(),this.#w=null,this.#re=e,e&&(this.#w=e.subscribe(n=>this.#Ve(n))))}#Ve(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#A+=1,this.#y=null,this.#W=!0,this.#V=null;let n=this.messages.length>0;n||this.#r!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#J():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#C.clear(),this.#Z(null)),this.#r=null,this.#l=null,this.#f=null,this.#u=null,this.#b(),n&&this.#F("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#$e(){return this.#W?(this.#V||(this.#V=this.#ze().finally(()=>{this.#V=null})),this.#V):Promise.resolve()}async#ze(){if(!this.isClientTokenMode()){this.#W=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#W=!1}catch{}}reconcileBootConversation(e){let n=this.#_,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#r;if(!n||!o)return Promise.resolve();let s=this.#T(e?.scope);this.#d=!0,this.#b();let i=this.#Ue(n,o,s).finally(()=>{this.#d=this.#u!==null,this.#M===i&&(this.#M=null),this.#b()});return this.#M=i,i}async#Ue(e,n,o){this.#r=n;let s=this.clientSession?.conversationRevision??this.#l??null,i=this.#z?this.#Y:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#z=!1,this.#f=this.historyInternals.getStoredMessageCursor?.()??this.#f,await this.replayPendingProjections(),s&&i&&s===i){this.#l=s;return}let l=await e.getPage(n,{context:o}),c=new Set(l.messages.map(y=>y.id)),u=this.messages.some(y=>c.has(y.id)),p=l.messages[0]?.createdAt,g;if(!u)g=l.messages.map(y=>this.#ie(y));else{let y=this.#t?this.#i:null,h=this.messages.filter(C=>c.has(C.id)||C.id===y?!0:p!==void 0&&C.createdAt<p);g=Td(h,l.messages).map(C=>this.#ie(C))}this.#f=l.nextCursor,this.#l=l.conversationRevision||s||null,this.#L.clear();for(let y of l.messages)this.#L.set(y.id,y.content);this.#be(),this.messages=this.#K(g),this.callbacks.onMessagesChanged([...this.messages])}#ve(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#Z(e){this.#oe=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Pe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#oe}#Le(e){if(this.#ve())for(let n of e){let o=gi(n);o!==void 0&&this.#L.set(n.id,o)}}#qe(){if(!this.#ve())return;let e=this.#r;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let s=gi(o);s!==void 0&&this.#L.get(o.id)!==s&&n.push({id:o.id,displayContent:s})}n.length!==0&&(this.#Z({conversationId:e,messageIds:n.map(o=>o.id)}),this.#Ie(e,n))}#Ie(e,n){let s=(this.#y??Promise.resolve()).catch(()=>{}).then(()=>this.#He(e,n,!1)).finally(()=>{this.#y===s&&(this.#y=null)});this.#y=s}async#He(e,n,o){if(this.#r!==e)return;let s=n.filter(i=>this.#L.get(i.id)!==i.displayContent);if(s.length===0){this.#Ce(e,n);return}try{let{conversationRevision:i}=await this.client.finalizeDisplayProjections(e,s);for(let l of s)this.#L.set(l.id,l.displayContent);this.#r===e&&i&&(this.#l=i),this.#Ce(e,n)}catch(i){if(!o&&this.#je(i)){await this.#He(e,s,!0);return}if(i instanceof bt&&(i.code==="not_found"||i.code==="conversation_deleted")){this.#Ce(e,n);return}this.#F("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#je(e){return e instanceof bt?e.code==="request_failed":e instanceof Error}#Ce(e,n){let o=this.#Pe();if(!o||o.conversationId!==e)return;let s=new Set(n.map(l=>l.id)),i=o.messageIds.filter(l=>!s.has(l));this.#Z(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ve())return;let e=this.#Pe();if(!e)return;if(this.#r&&e.conversationId!==this.#r){this.#Z(null);return}let n=[];for(let o of e.messageIds){let s=this.messages.find(i=>i.id===o);!s||typeof s.content!="string"||n.push({id:o,displayContent:s.content})}if(n.length===0){this.#Z(null);return}this.#Ie(e.conversationId,n),await this.#y?.catch(()=>{})}#Ke(){this.#r&&(this.#l=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Re(){await this.awaitHistorySettled(),await this.#$e(),this.#u==="new_conversation_required"&&await this.#Fe()}static#Ge(e){return e instanceof bt&&e.code==="conversation_deleted"}async#Ye(e,n,o,s,i){this.#Le(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions,interrupt:i?.interrupt},this.handleEvent);return}catch(l){if(!t.#Ge(l))throw l;let c=await this.#Qe(s);if(!c)throw l;this.#Le([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions},this.handleEvent)}}async#Qe(e){let n=this.messages.find(s=>s.id===e);if(!n)return null;let o={...n};this.#A+=1,this.#y=null,this.#J(),this.#r=null,this.#l=null,this.#f=null,this.#P=!0;try{let s=this.#_;if(s){let i=await s.prepareStartNew({context:this.#T()});await this.#ye(i)}else{this.client.clearClientSession();let i=await this.client.initSession();this.bindActivatedSession(i)}}catch{return this.#d=!0,this.#u="new_conversation_required",this.#b(),this.#F("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#P=!1}return this.#N(o),this.#g(!0),this.#F("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(s=>s.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},s=Ff(this.config,o),i=tw(this.config,o);this.config=o,s&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Nt(o.voiceRecognition.provider)&&this.setupVoice());let l=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!i){this.client.updateConfig(o),l&&this.#Be();return}this.#ee(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let c=this.client.getSSEEventCallback();this.client=new vi(this.config,this.historyInternals),l&&this.#Be(),this.#We(),c&&this.client.setSSEEventCallback(c)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:s,contentParts:i,id:l,createdAt:c,sequence:u,streaming:p=!1,voiceProcessing:g,voiceCaption:y,rawContent:h}=e,E={id:l??(n==="user"?bl():n==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:u??this.#k(),streaming:p,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...y&&{voiceCaption:y},...h!==void 0&&{rawContent:h}};return this.upsertMessage(E),E}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:s,content:i,llmContent:l,contentParts:c,id:u,createdAt:p,sequence:g,streaming:y=!1,voiceProcessing:h,rawContent:C}=o,A={id:u??(s==="user"?bl():s==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:p??new Date().toISOString(),sequence:g??this.#k(),streaming:y,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...h!==void 0&&{voiceProcessing:h},...C!==void 0&&{rawContent:C}};n.push(A)}return this.messages=this.#K([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:s="",llmContent:i,id:l,createdAt:c,sequence:u}=e,p={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(p),...i!==void 0&&{llmContent:i},...l!==void 0&&{id:l},...c!==void 0&&{createdAt:c},...u!==void 0&&{sequence:u}})}async#Xe(e,n,o){let s;try{s=await o()}catch{return}let i=s.blocks.join(`
|
|
10
10
|
|
|
11
11
|
`),l=[i,n].filter(Boolean).join(`
|
|
12
12
|
|
|
13
|
-
`),c=Array.isArray(e.contentParts)&&e.contentParts.length>0,u=s.contentParts.length>0;if(c){let p=[];i&&p.push(zo(i)),p.push(...s.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(u){let p=[];l&&p.push(zo(l)),p.push(...s.contentParts),e.contentParts=p}else i&&(e.llmContent=l);Object.keys(s.context).length>0&&(e.mentionContext=s.context)}async sendMessage(e,n){let o=e.trim(),s=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!s)return;this.#R&&!n?.voiceTurn&&(this.#R.failed=!0,this.#R=null),(this.#x||this.#b||this.#d||this.#S)&&await this.#Ie(),this.stopSpeaking(),this.abortController?.abort(),this.#J(),this.#q++,this.#ee();let i=n?.voiceTurn?.userMessageId,l=i?this.messages.find(C=>C.id===i&&C.role==="user"):void 0,c=l?.id??bl(),u=hs();this.#s=null;let p=n?.contentParts&&nf(n.contentParts)?Za:"",g={id:c,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#M(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};l?(l.viaVoice=!0,delete l.voiceCaption,l.content.trim()!==o&&(l.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#B(g),this.#p(!0);let y=new AbortController;if(this.abortController=y,n?.mentions){let C=this.messages.find(E=>E.id===c)??g;if(await this.#Ge(C,o,n.mentions.finalize),y.signal.aborted||this.abortController!==y)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let C=this.messages.find(A=>A.id===c)??g,E=rh({quote:n.quote,text:C.llmContent??C.content,contentParts:C.contentParts});E.contentParts&&(C.contentParts=E.contentParts),E.llmContent!==void 0&&(C.llmContent=E.llmContent),(E.contentParts||E.llmContent!==void 0)&&(C.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let h=l?[...this.messages.filter(C=>C!==l),{...l,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#je(h,y,u,c,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(C){if(this.status==="resuming"||this.#r)return;this.#R&&(this.#R.failed=!0);let E=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!E){let A=jd(C,this.config.errorMessage);if(A){let I={id:u,role:"assistant",createdAt:new Date().toISOString(),content:A,sequence:this.#M()};this.#B(I)}}this.#P("idle"),this.#p(!1),this.abortController=null,E||(C instanceof Error?this.callbacks.onError?.(C):this.callbacks.onError?.(new Error(String(C))))}}resubmitFrom(e,n){let o=sh(this.messages,e);if(!o)return!1;let s=this.messages[o.start],i=n.replacement,l=i?i.text:s.content,c=i?i.contentParts:s.contentParts;if(!(!!l?.trim()||(c?.length??0)>0||!i&&(s.llmContent?.trim()?.length??0)>0))return!1;let p=i?void 0:{...s.llmContent!==void 0&&{llmContent:s.llmContent},...s.rawContent!==void 0&&{rawContent:s.rawContent},...s.mentionContext&&{mentionContext:s.mentionContext},...s.contextMentions&&{contextMentions:s.contextMentions},...s.quote&&{quote:s.quote}},g=i?this.#Ye(i.options):s.composerOptions,y=i?i.contentSegments:s.contentSegments,h=i?i.options?.quote:void 0,C=i?i.viaVoice:s.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(l??"",{...c?.length?{contentParts:[...c]}:{},...y?.length?{contentSegments:[...y]}:{},...g?{composerOptions:g}:{},...h?{quote:h}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:C===!0}),!0}#Ye(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.#x||this.#b||this.#d||this.#S)&&await this.#Ie(),this.abortController?.abort(),this.#ee();let e=hs();this.#s=null,this.#p(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(s){if(this.status==="resuming"||this.#r)return;let i=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!i){let l=jd(s,this.config.errorMessage);if(l){let c={id:e,role:"assistant",createdAt:new Date().toISOString(),content:l,sequence:this.#M()};this.#B(c)}}this.#P("idle"),this.#p(!1),this.abortController=null,i||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.#s=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.#p(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(i){if(this.status==="resuming"||this.#r)return;this.#P("error"),this.webMcpResolveControllers.size===0&&(this.#p(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}#He(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.#N}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let s=this.messages.find(i=>i.id===e);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}#Qe;#q;#ue(e){let n=this.#Qe??={s:this,setStreaming:i=>this.#p(i),appendMessage:i=>this.#B(i),nextSequence:()=>this.#M(),settleApprovalPausedToolCall:i=>this.#Be(i),resumeAfter:i=>this.#t?.executionId===i?this.#t.lastEventId:void 0},o=oh();if(o)return e(o,n);let s=this.#q;return Nd().then(i=>s===this.#q?e(i,n):void 0,i=>{this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))})}resolveApproval(e,n,o){return this.#ue((s,i)=>s.resolveApproval(i,e,n,o))}resolveAskUserQuestion(e,n){return this.#ue((o,s)=>o.resolveAskUserQuestion(s,e,n))}resolveWebMcpToolCall(e){return this.#ue((n,o)=>n.resolveWebMcpToolCall(o,e))}persistAskUserQuestionProgress(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}#Xe(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let i=this.#v;queueMicrotask(()=>{i===this.#v&&this.resolveWebMcpToolCall(e)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(o)&&(s.seen.add(o),s.snapshots.push(e))}#Je(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#v;queueMicrotask(()=>{if(e===this.#v)for(let n of[...this.webMcpAwaitBatches.keys()])this.#Ze(n)})}#Ze(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.#ue((s,i)=>s.resolveWebMcpToolCallBatch(i,e,o))}#J(){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.#v++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ee(),this.#J(),this.#q++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#p(!1),this.#P("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ee(),this.#J(),this.#q++,this.messages=[],this.agentExecution=null,this.#Ce(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#p(!1),this.#P("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#u}selectArtifact(e){this.#u=e,this.#Z()}clearArtifacts(){this.#Ce()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.#u=n,this.#Z(),e.transcript!==!1&&this.#et(o),o}#et(e){let n=`artifact-ref-${e.id}`,o=as(this.config.features?.artifacts,e),s=wd(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),i=this.messages.find(l=>l.id===n);if(i){i.rawContent=s,i.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:s})}#Re(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(l=>l.id===`artifact-ref-${n.id}`);if(!o)continue;let s=as(this.config.features?.artifacts,n),i=wd(s,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==i&&(o.rawContent=i,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Ce(){this.artifacts.size===0&&this.#u===null||(this.artifacts.clear(),this.#u=null,this.#Z())}#Z(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#u})}#tt(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.#u=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.#Z()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#ee(),this.#J(),this.#q++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#j(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#M()}))),this.#p(!1),this.#P("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.#u=n,this.#Z()}#nt(e){let n=this.agentExecution?.executionId;if(!n||!this.#s||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:e,assistantMessageId:this.#s,status:"running"},this.#at(o)}#ot(){return this.#t!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#We()}#We(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}#we(){this.#r||!this.#t||typeof this.config.reconnectStream!="function"||(this.#r=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#p(!0),this.#P("resuming"),this.#rt().then(e=>{this.#r&&this.#t&&e.begin()}))}#rt(){return this.#a?Promise.resolve(this.#a):(this.#f||(this.#f=dh().then(({createReconnectController:e})=>{let n=e(this.#st());return this.#a=n,n}),this.#f.catch(()=>{this.#f=null})),this.#f)}#st(){let e=this;return{get config(){return e.config},getResumable:()=>e.#t,clearResumable:()=>e.#ge(),getStatus:()=>e.status,setStatus:n=>e.#P(n),setStreaming:n=>e.#p(n),setReconnecting:n=>{e.#r=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,s)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>e.#B(n),nextSequence:()=>e.#M(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>jd(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.#r){this.#a?.wake();return}this.#we()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.#r)return;let n=this.#it();n||(n=hs(),this.#B({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#M()})),this.#s=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#t={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.#we()}#it(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}#ee(){this.#r=!1,this.#a?.teardown(),this.#ge()}#ge(){this.#i&&(clearTimeout(this.#i),this.#i=null);let e=this.#t!==null;this.#t=null,e&&this.config.onExecutionState?.(null)}#at(e){let n=this.config.onExecutionState;if(n){if(e){this.#i&&(clearTimeout(this.#i),this.#i=null),n(this.#t);return}this.#i||(this.#i=setTimeout(()=>{this.#i=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#P(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#p(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(e){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let s=[...this.messages].reverse().find(l=>l.role==="assistant"&&l.content&&!l.voiceProcessing);if(!s||e&&!e.includes(s.id))return;if(this.ttsSpokenMessageIds.has(s.id)){this.ttsSpokenMessageIds.delete(s.id);return}let i=Ud(s.content);i.trim()&&this.readAloud.play(s.id,{text:i,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(e){return zd(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=Ud(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#Be(e){let n=this.messages.find(c=>c.id===e)?.approval,o=n?.toolCallId,s=o&&this.messages.find(c=>c.toolCall?.id===o),i=s&&s.toolCall;if(!i||i.status==="complete"||n.status==="pending")return;let l={...i,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...s,streaming:!1,toolCall:l})}#B(e){let n=this.#oe(e);this.messages=this.#j([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.#oe(e),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.#B(n);return}this.messages=this.messages.map((s,i)=>{if(i!==o)return s;let l={...s,...n};s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(l.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(l.agentMetadata={...l.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let c=s.agentMetadata?.clientToolAnswer;if(c&&l.agentMetadata&&!l.agentMetadata.clientToolAnswer&&(l.agentMetadata={...l.agentMetadata,clientToolAnswer:c}),s.approval&&n.approval&&s.approval.id===n.approval.id){let y=s.approval,h=n.approval;l.approval={...y,...h,executionId:h.executionId||y.executionId,toolName:h.toolName||y.toolName,description:h.description||y.description,toolType:h.toolType??y.toolType,reason:h.reason??y.reason,parameters:h.parameters??y.parameters,toolCallId:h.toolCallId??y.toolCallId}}let u=n.toolCall?.name,p=n.agentMetadata?.executionId,g=n.toolCall?.id;if(u&&ph(u)&&p&&g&&n.agentMetadata?.awaitingLocalTool===!0){let y=`${p}:${g}`,h=this.webMcpInflightKeys.has(y),C=this.webMcpResolvedKeys.has(y),E=s.toolCall?.name,A=s.agentMetadata?.executionId===p&&s.toolCall?.id===g&&E!==void 0&&ph(E)&&s.toolCall?.status==="complete";(h||C||A)&&(l.agentMetadata={...l.agentMetadata??{},awaitingLocalTool:!1},l.toolCall=s.toolCall,l.streaming=s.streaming)}return l}),this.messages=this.#j(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#oe(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.#M()}}#M(){return this.#e++}#j(e){return[...e].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),i=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=n.sequence??0,c=o.sequence??0;return l!==c?l-c:n.id.localeCompare(o.id)})}};import{File as nw,FileCode as ow,FileSpreadsheet as rw,FileText as Kd,X as sw}from"lucide";var iw={add:t=>of(t)},aw=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,xl={allowedTypes:us,maxFileSize:10*1024*1024,maxFiles:4};function lw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cw(t){return t==="application/pdf"?Kd:t.startsWith("text/")?Kd:t.includes("word")?Kd:t.includes("excel")||t.includes("spreadsheet")?rw:t==="application/json"?ow:nw}var xi=class t{constructor(e={}){this.attachments=[];this.#e=null;this.#t=new Map;this.#s=!1;this.config={allowedTypes:e.allowedTypes??xl.allowedTypes,maxFileSize:e.maxFileSize??xl.maxFileSize,maxFiles:e.maxFiles??xl.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#e;#t;#s;#r(){return typeof this.config.adapter?.add=="function"}#a(){return this.#r()?this.config.adapter:iw}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML="";for(let n of this.attachments)this.#N(n)}this.#h()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:xl.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#s)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let s=rf(o,this.config.allowedTypes,this.config.maxFileSize);if(!s.valid){let l=s.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,l);continue}let i={id:lw(),file:o,previewUrl:Ed(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#r()?"uploading":"processing",progress:this.#r()?0:void 0};this.attachments.push(i),this.#N(i),n.push(i)}this.#h(),this.#v(),await Promise.all(n.map(o=>this.#f(o)))}async#f(e){let n=new AbortController;this.#t.set(e.id,n);let o=()=>this.#s||n.signal.aborted||this.#t.get(e.id)!==n||!this.attachments.includes(e);try{let s=await this.#a().add(e.file,{signal:n.signal,onProgress:i=>{o()||e.status!=="uploading"||(e.progress=aw(i),this.#n(e),this.#v())}});if(o())return;e.contentPart=s,e.status="ready",e.progress=void 0,e.error=void 0}catch(s){if(o())return;e.status="error",e.progress=void 0,e.error=s instanceof Error?s.message:String(s??"Upload failed")}finally{this.#t.get(e.id)===n&&this.#t.delete(e.id)}this.#n(e),this.#v()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.#s||(n.status=this.#r()?"uploading":"processing",n.progress=this.#r()?0:void 0,n.error=void 0,this.#n(n),this.#v(),this.#f(n))}#i(e){let n=this.#t.get(e);n&&(this.#t.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(i=>i.id===e);if(n===-1)return;let o=this.attachments[n];this.#i(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.#e?.querySelector(`[data-attachment-id="${e}"]`);s&&s.remove(),o.status==="ready"&&o.contentPart&&this.#u(o.contentPart),this.#h(),this.#v()}#u(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(s=>{console.error("[AttachmentManager] adapter.remove failed:",s)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.#i(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=""),this.#h(),this.#v()}destroy(){if(!this.#s){this.#s=!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}}#v(){this.#s||this.config.onAttachmentsChange?.(this.getAttachments())}#N(e){if(!this.#e)return;let n=Ed(e.file),o=P("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let g=P("img");g.src=e.previewUrl,g.alt=e.file.name,g.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",g.style.width="48px",g.style.height="48px",g.style.objectFit="cover",g.style.borderRadius="8px",o.appendChild(g)}else{let g=P("div");g.style.width="48px",g.style.height="48px",g.style.borderRadius="8px",g.style.backgroundColor="var(--persona-container, #f3f4f6)",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.display="flex",g.style.flexDirection="column",g.style.alignItems="center",g.style.justifyContent="center",g.style.gap="2px",g.style.overflow="hidden";let y=cw(e.file.type),h=yt(y,20,"var(--persona-muted, #6b7280)",1.5);h&&g.appendChild(h);let C=P("span");C.textContent=sf(e.file.type,e.file.name),C.style.fontSize="8px",C.style.fontWeight="600",C.style.color="var(--persona-muted, #6b7280)",C.style.textTransform="uppercase",C.style.lineHeight="1",g.appendChild(C),o.appendChild(g)}let s=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),i=P("div","persona-attachment-progress");i.appendChild(P("div","persona-attachment-progress__bar"));let l=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=se("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);c?l.appendChild(c):l.textContent="\u21BB",l.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.retryAttachment(e.id)}),s.append(i,l),o.appendChild(s);let u=P("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");u.type="button",u.setAttribute("aria-label","Remove attachment"),u.style.position="absolute",u.style.top="-4px",u.style.insetInlineEnd="-4px",u.style.width="18px",u.style.height="18px",u.style.borderRadius="50%",u.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",u.style.border="none",u.style.cursor="pointer",u.style.display="flex",u.style.alignItems="center",u.style.justifyContent="center",u.style.padding="0";let p=yt(sw,10,"var(--persona-text-inverse, #ffffff)",2);p?u.appendChild(p):(u.textContent="\xD7",u.style.color="var(--persona-text-inverse, #ffffff)",u.style.fontSize="14px",u.style.lineHeight="1"),u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(u),this.#e.appendChild(o),this.#l(o,e)}#n(e){let n=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.#l(n,e)}#l(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let s=e.querySelector(".persona-attachment-progress__bar");if(s){let i=n.progress;s.style.width=typeof i=="number"?`${Math.round(i*100)}%`:""}}#h(){this.#e&&(this.#e.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var uh=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),dw=(t,e)=>t.length===e.length&&t.every((n,o)=>{let s=e[o];return n.id===s.id&&n.name===s.name&&n.mimeType===s.mimeType&&n.size===s.size&&n.status===s.status&&n.progress===s.progress&&n.error===s.error});function gh(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,s=!1,i=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",l=()=>{let g=i();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(y=>Object.freeze({...y}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:g,inputDisabled:t.inputDisabled,sendDisabled:g!=="idle"||t.sendDisabled||t.inputDisabled})},c=()=>(n||(n=l()),n),u=()=>{if(o=!1,s||e.size===0)return;let g=c();for(let y of[...e])try{y(g)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},p=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(u))};return{getState:c,subscribe:g=>(e.add(g),()=>e.delete(g)),setText:g=>{t.text!==g&&(t.text=g,p())},setAttachments:g=>{dw(t.attachments,g)||(t.attachments=[...g],p())},setMentionRefs:g=>{uh(t.mentionRefs,g)||(t.mentionRefs=[...g],p())},setSelectedModelId:g=>{t.selectedModelId!==g&&(t.selectedModelId=g,p())},setActiveModeIds:g=>{uh(t.activeModeIds,g)||(t.activeModeIds=[...g],p())},setQuote:g=>{let y=t.quote;y?.text===g?.text&&y?.messageId===g?.messageId&&y?.sourceLabel===g?.sourceLabel||(t.quote=g?{...g}:void 0,p())},setPendingSubmission:g=>{t.pendingSubmission!==g&&(t.pendingSubmission=g,p())},setPreparing:g=>{t.preparing!==g&&(t.preparing=g,p())},setStreaming:g=>{t.streaming!==g&&(t.streaming=g,p())},setInputDisabled:g=>{t.inputDisabled!==g&&(t.inputDisabled=g,p())},setSendDisabled:g=>{t.sendDisabled!==g&&(t.sendDisabled=g,p())},flush:()=>{o&&u()},destroy:()=>{s=!0,o=!1,e.clear()}}}var Qt=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},mh=(t,e)=>{let n=P("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function fh(t,e={}){let n=Qt(t,"[data-persona-composer-form]"),o=Qt(t,"[data-persona-composer-input]");if(!n||!o){let L=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(L);return typeof console<"u"&&console.warn(L),null}let s={header:Qt(t,"[data-persona-composer-header]"),body:Qt(t,"[data-persona-composer-body]"),actionsStart:Qt(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Qt(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Qt(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Qt(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Qt(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=mh("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(l,n):t.appendChild(l));let c=s.body??o.parentElement??n,u=(I,L,k,R,B)=>{if(L)return L;i.add(I);let O=mh(k,R);return B.appendChild(O),O},p=u("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),g=u("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),y=u("suggestions",s.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),h=u("status",s.status,"persona-widget-composer__status","data-persona-composer-status",t),C=[],E=(I,L)=>I.target===L.target&&I.type===L.type&&I.handler===L.handler,A=Qt(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:l,body:c,actionsStart:p,actionsEnd:g,suggestions:y,status:h,attachmentInput:A,attachmentPreviews:Qt(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Qt(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Qt(t,"[data-persona-composer-submit]")??void 0,micButton:Qt(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(I,L,k,R)=>{I.addEventListener(L,k,R),C.push({target:I,type:L,handler:k,options:R})},removeListener:(I,L,k,R)=>{I.removeEventListener(L,k,R),C=C.filter(B=>!E(B,{target:I,type:L,handler:k}))},destroy:()=>{for(let I of C)I.target.removeEventListener(I.type,I.handler,I.options);C=[]}}}var pw='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',uw=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],Gd="data-persona-menu-focus",gw=new Set(["ArrowDown","ArrowUp","Home","End"]);function hh(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(pw)??t}var mw=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function yh(t){let e=t.label,n=!1,o=P("div","persona-send-button-wrapper"),s=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Uo} ${Mr}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=Y("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),l=()=>{let x=t.getButtonSize?.()??"";s.style.width=x,s.style.height=x,s.style.minWidth=x,s.style.minHeight=x,s.style.lineHeight="1",s.replaceChildren();let z=se("plus",qn,"currentColor",1.5);z?s.appendChild(z):s.textContent="+"},c=()=>{s.setAttribute("aria-label",e),s.setAttribute("title",e),i.setAttribute("aria-label",e)};c(),l();let u=[],p=-1,g=!1,y=()=>{let z=i.getRootNode().activeElement;return z instanceof HTMLElement?z:null},h=()=>{let x=y();for(let z of u){let W=!!x&&hh(z)===x;z.toggleAttribute(Gd,W&&g)}},C=()=>u.filter(x=>x.isConnected||i.contains(x)).map(hh).filter(x=>!mw(x)),E=(x,z)=>{x.forEach((W,ee)=>{W.setAttribute("tabindex",ee===z?"0":"-1")})},A=x=>{let z=C();if(z.length===0)return;let W=(x%z.length+z.length)%z.length;p=W,E(z,W),z[W].focus(),h()},I=()=>o.ownerDocument??document,L=null,k=null,R=null,B=()=>{L&&(I().removeEventListener("focusin",L,!0),L=null)},O=()=>{k&&(i.removeEventListener("focusin",k),k=null),R&&(i.removeEventListener("pointerdown",R,!0),R=null)},V=null,J=()=>(V||(V=ll({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),B()}})),V),_=()=>V?.isOpen===!0,Q=(x=!1)=>{if(_()){V?.close(),s.setAttribute("aria-expanded","false"),B(),O(),p=-1,g=!1;for(let z of u)z.removeAttribute(Gd);x&&s.focus()}},G=(x=0,z=!1)=>{if(n||_())return;g=z,tl(s,i,uw),J().open(),s.setAttribute("aria-expanded","true");let W=C();E(W,-1),A(x<0?W.length-1:x),L=ee=>{let ne=typeof ee.composedPath=="function"?ee.composedPath():[];ne.includes(i)||ne.includes(o)||Q()},I().addEventListener("focusin",L,!0),k=()=>h(),i.addEventListener("focusin",k),R=()=>{g=!1},i.addEventListener("pointerdown",R,!0)},w=x=>{x.preventDefault(),x.stopPropagation(),_()?Q(!0):G(0)},v=x=>{if(x.key==="ArrowDown"||x.key==="Enter"||x.key===" "){x.preventDefault(),g=!0,_()?A(0):G(0,!0);return}x.key==="ArrowUp"&&(x.preventDefault(),g=!0,_()?A(-1):G(-1,!0))},T=x=>{switch(gw.has(x.key)&&(g=!0),x.key){case"ArrowDown":x.preventDefault(),A(p+1);return;case"ArrowUp":x.preventDefault(),A(p-1);return;case"Home":x.preventDefault(),A(0);return;case"End":x.preventDefault(),A(C().length-1);return;case"Escape":x.preventDefault(),x.stopPropagation(),Q(!0);return;case"Tab":Q(!0);return;default:}};return s.addEventListener("click",w),s.addEventListener("keydown",v),i.addEventListener("keydown",T),{trigger:o,triggerButton:s,panel:i,setItems:x=>{for(let W of u)x.includes(W)||W.removeAttribute(Gd);if(u=[...x],!_())return;let z=C();E(z,Math.min(p,z.length-1)),h()},isOpen:_,open:()=>G(0),close:Q,setLabel:x=>{x!==e&&(e=x,c())},applyButtonSize:l,destroy:()=>{n=!0,B(),O(),s.removeEventListener("click",w),s.removeEventListener("keydown",v),i.removeEventListener("keydown",T),V?.destroy(),V=null,o.remove(),i.remove(),u=[]}}}var Kn={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},bh="data-persona-composer-action",Yd="data-persona-composer-disable-when-streaming",fw="core:overflow",hw=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function yw(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=P("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let s=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(s)&&s>0?s:Number.isFinite(n)?n:null}function Qd(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),s=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-s)}var vh=(t,e)=>{!t||typeof console>"u"||console.warn(e)},bw=(t,e)=>e.includes(":")?e:`${t}:${e}`;function vw(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let u=o.get(c.id);if(u){vh(e,`[Persona] composer action "${c.id}" is already contributed by ${Ch(u)}; the ${Ch(c)} copy is ignored.`);return}o.set(c.id,c),n.push(c)};for(let c of t.builtIns)i({id:c.id,placement:c.placement,presentation:"bar",order:c.order,sequence:s++,source:"core",builtIn:c});let l=(c,u,p)=>{let g=p?bw(p,c.id):c.id,y=c.order??Kn.custom;c.placement==="end"&&y>=Kn.send&&(vh(e,`[Persona] composer action "${g}" ordered at ${y} would render after send; clamped to ${Kn.send-1}.`),y=Kn.send-1),i({id:g,placement:c.placement,presentation:c.presentation??"bar",order:y,sequence:s++,source:u,pluginId:p,action:c})};for(let c of t.configActions??[])l(c,"config");for(let c of t.plugins){if(!c.contributeComposerActions)continue;let u;try{u=c.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,p);continue}for(let p of u??[])l(p,"plugin",c.id)}return n.sort((c,u)=>c.order===u.order?c.sequence-u.sequence:c.order-u.order)}var Ch=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",wh=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,Cw=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function ww(t,e){if(!t||t==="always")return!0;let n=Cw(e);return t==="when-text"?n:!n}var jo=t=>t.kind==="custom",Xd=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,Sw=t=>{let e=Xd(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},xw='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Aw(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let s=o;typeof s.matches=="function"&&s.matches(xw)||o.childNodes.forEach(n)};return n(t),e.trim()}var Mw=t=>Aw(t).length===0;function Sh(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(w,v)=>{let T=w.button;if(!T)return;T.setAttribute("role","menuitem"),T.setAttribute("tabindex","-1"),T.className="persona-composer-overflow-menu__item";for(let W of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])T.style[W]="";T.style.lineHeight="1",v.tooltipText?T.setAttribute("title",v.tooltipText):T.removeAttribute("title"),T.replaceChildren();let x=P("span","persona-composer-overflow-menu__icon");if(v.iconName){let W=se(v.iconName,16,"currentColor",1.5);W&&x.appendChild(W)}let z=P("span","persona-composer-overflow-menu__label");z.textContent=v.shortLabel??v.label,T.append(x,z)},l=(w,v)=>{let T=w.button;if(!T)return;if(T.setAttribute("aria-label",v.label),v.pressed===void 0?T.removeAttribute("aria-pressed"):T.setAttribute("aria-pressed",v.pressed?"true":"false"),T.toggleAttribute(Yd,v.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,i(w,v);return}T.removeAttribute("role"),T.removeAttribute("tabindex"),T.removeAttribute("title");let x=s(),z=!!v.shortLabel;if(T.className=ss("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Uo,Mr,z&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),T.style.width=x&&!z?x:"",T.style.height=x??"",T.style.minWidth=x&&!z?x:"",T.style.minHeight=x??"",T.style.fontSize=z?"":"18px",T.style.lineHeight="1",T.style.color=v.iconColor??"",T.style.backgroundColor=v.backgroundColor??"",T.replaceChildren(),v.iconName){let W=se(v.iconName,qn,"currentColor",1.5);W&&T.appendChild(W)}if(z){let W=P("span","persona-composer-action-button__label");W.textContent=v.shortLabel,T.appendChild(W)}else T.firstChild||(T.textContent=v.label);w.tooltip?.destroy(),w.tooltip=vn({anchor:T,trigger:w.element,text:()=>v.tooltipText??v.label,enabled:!!v.tooltipText})},c=(w,v)=>{let T=w.action,x=Y("button",{attrs:{type:"button"}}),z=x;if(v==="bar"){let ne=P("div","persona-send-button-wrapper");ne.appendChild(x),z=ne}z.setAttribute(bh,w.id);let W={resolved:w,element:z,button:x,owned:!0,managed:!0,busy:!1,visible:!0,mode:v},ee=ne=>{if(ne.preventDefault(),ne.stopPropagation(),W.busy||x.disabled)return;let he=W.resolved.action;W.mode==="menu"&&C?.close(!0);let ve;try{ve=he.onSelect(t.actionContext,ne)}catch(Xe){t.reportError(Xe,{actionId:W.resolved.id});return}!ve||typeof ve.then!="function"||(W.busy=!0,x.setAttribute("aria-busy","true"),ve.catch(Xe=>{t.reportError(Xe,{actionId:W.resolved.id})}).finally(()=>{W.busy=!1,x.removeAttribute("aria-busy")}))};return x.addEventListener("click",ee),W.detach=()=>x.removeEventListener("click",ee),l(W,T),W},u=w=>{let v=w.action,T;try{T=v.render({...t.actionContext,id:w.id,action:v})}catch(x){return t.reportError(x,{actionId:w.id}),null}return T?.element?(T.element.setAttribute(bh,w.id),T.element.toggleAttribute(Yd,v.disableWhenStreaming===!0),{resolved:w,element:T.element,owned:!0,managed:!0,destroy:T.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(w,v)=>{if(w.builtIn){let x=w.builtIn.element;return x?{resolved:w,element:x,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let T=w.action;return T?jo(T)?u(w):c(w,v):null},g=w=>{if(w.detach?.(),w.tooltip?.destroy(),w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0,w.owned){try{w.destroy?.()}catch(v){t.reportError(v,{actionId:w.resolved.id})}w.element.remove()}},y=(w,v)=>{for(let T=0;T<v.length;T++){let x=v[T];if(!x.managed)continue;let z=null;for(let W=T+1;W<v.length;W++){let ee=v[W];if(!ee.managed&&ee.element.parentElement===w){z=ee.element;break}}z?(x.element.parentElement!==w||x.element.nextSibling!==z)&&w.insertBefore(x.element,z):w.lastChild!==x.element&&w.appendChild(x.element)}},h=(w,v)=>{if(w.button){w.button.disabled=v;return}if(!w.owned)return;let T=w.element;T.toggleAttribute("data-disabled",v),T.setAttribute("aria-disabled",v?"true":"false");let x=T instanceof HTMLButtonElement||T instanceof HTMLSelectElement||T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement?T:T.querySelector("button, select, input, textarea");x&&(x.disabled=v)},C=null,E=null,A=null,I=0,L=()=>{let w=t.getOverflow?.();return w?.enabled===!0?w:void 0},k=()=>(C?C.setLabel(t.getOverflowLabel?.()??"More actions"):C=yh({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),C),R=w=>{E!==w&&(A?.disconnect(),E=w,I=Qd(w),!(typeof ResizeObserver>"u")&&(A=new ResizeObserver(v=>{let x=v[v.length-1]?.contentRect?.width??Qd(w);x!==I&&(I=x,Q())}),A.observe(w)))},B=(w,v)=>{let T=yw(w.collapseAutoActionsBelow,v);if(T===null)return!1;let x=I||Qd(v);return x>0&&x<T},O=(w,v,T)=>{if(!v)return"bar";if(w.resolved.builtIn){let z=hw(w.resolved.id);return z&&v.includeBuiltIns?.includes(z)?"menu":"bar"}let x=w.resolved.presentation;return x==="overflow"||x==="auto"&&T?"menu":"bar"},V=w=>{let v=w.menuSlot;if(!v)return;if(!Mw(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let T=Sw(w.element);if(!T){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=P("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==T&&(w.menuLabel.textContent=T),w.menuLabel.parentElement!==v&&v.appendChild(w.menuLabel)},J=(w,v)=>{if(w.mode===v)return w;let T=w.resolved.action;if(T&&!jo(T)){g(w),e.delete(w.resolved.id);let x=c(w.resolved,v);return e.set(w.resolved.id,x),x}if(v==="menu"){let x=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[lf]:""}});x.appendChild(w.element),cf(Xd(w.element)),w.menuSlot=x;let z=W=>{let ee=Xd(w.element);if(ee.disabled)return;let ne=W.target===ee||ee.contains(W.target);C?.close(!0),ne||ee.click()};x.addEventListener("click",z,!0),w.detachMenuSlot=()=>x.removeEventListener("click",z,!0),w.managed=!0,V(w)}else w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0;return w.mode=v,w},_=(w,v)=>{let T=v.map(x=>x.menuSlot??x.element);for(T.forEach((x,z)=>{let W=w.children[z];W!==x&&(W?w.insertBefore(x,W):w.appendChild(x))});w.children.length>T.length;)w.lastElementChild?.remove()},Q=()=>{if(o)return;let w=t.getBindings();if(!w)return;let v=t.getState(),T=v.phase==="streaming",x=L();x&&R(w.footer);let z=x?B(x,w.footer):!1,W={start:[],end:[]},ee=[];for(let ne of n){let he=e.get(ne.id);if(!he)continue;let ve=ne.action,Xe=ve?wh(ve.visible,v,!0)&&ww(ve.visibility,v):!0;if(he.visible!==Xe&&(he.visible=Xe,!Xe&&he.managed&&(he.menuSlot??he.element).remove()),!!Xe){if(he=J(he,O(he,x,z)),ve){let Je=wh(ve.disabled,v,!1)||ve.disableWhenStreaming===!0&&T;h(he,Je),!jo(ve)&&ve.pressed!==void 0&&he.button?.setAttribute("aria-pressed",ve.pressed?"true":"false")}he.mode==="menu"?(V(he),ee.push(he)):W[ne.placement].push(he)}}if(ee.length>0){let ne=k();_(ne.panel,ee),ne.setItems(ee.map(Je=>Je.menuSlot??Je.element)),ne.applyButtonSize();let he=Number.isFinite(x?.order)?x?.order:Kn.overflow,ve=W.start.findIndex(Je=>Je.resolved.order>he),Xe={resolved:{id:fw,placement:"start",presentation:"bar",order:he,sequence:-1,source:"core"},element:ne.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};W.start.splice(ve<0?W.start.length:ve,0,Xe)}else C&&(C.close(),C.trigger.remove(),C.setItems([]));y(w.actionsStart,W.start),y(w.actionsEnd,W.end)};return{resolve:()=>{if(o)return;let w=vw(t.collect()),v=new Set(w.map(T=>T.id));for(let[T,x]of e)v.has(T)||(g(x),e.delete(T));for(let T of w){let x=e.get(T.id);if(!x){let ne=p(T,"bar");ne&&e.set(T.id,ne);continue}let z=x.resolved.action,W=T.action;if(!!z!=!!W||z&&W&&jo(z)!==jo(W)||z&&W&&jo(z)&&jo(W)&&z.render!==W.render){g(x),e.delete(T.id);let ne=p(T,x.mode);ne&&e.set(T.id,ne);continue}x.resolved=T,T.builtIn?(x.managed=T.builtIn.managed===!0||x.mode==="menu",T.builtIn.element&&x.mode==="bar"&&(x.element=T.builtIn.element)):W&&!jo(W)?l(x,W):W&&x.element.toggleAttribute(Yd,W.disableWhenStreaming===!0)}n=w,Q()},sync:Q,getResolved:()=>n,getOverflowMenu:()=>C,destroy:()=>{if(!o){o=!0,A?.disconnect(),A=null,E=null;for(let w of e.values())g(w);e.clear(),C?.destroy(),C=null,n=[]}}}}var Ew="core:model",Tw=700,xh=16,kw=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],Ah=()=>{let t=Y("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=Y("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Mh(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=u=>{let p=t.getSelectedModelId();return u.find(g=>g.id===p)??u[0]},i=()=>{let u=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",g=()=>{let A=t.getModels(),I=A.map(L=>`${L.id}:${L.label}`).join("|");I!==p&&(p=I,u.replaceChildren(...A.map(L=>{let k=Y("option",{attrs:{value:L.id}});return k.textContent=L.label,k}))),u.value=s(A)?.id??""};g(),o=g;let y=()=>{u.value&&t.onSelect(u.value)};u.addEventListener("change",y);let h=A=>A.stopPropagation();u.addEventListener("click",h);let{wrapper:C,chevron:E}=Ah();return C.append(u,E),{element:C,destroy:()=>{o===g&&(o=null),u.removeEventListener("change",y),u.removeEventListener("click",h)}}},l=()=>{let u=Y("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=P("span","persona-composer-model-picker-label"),g=P("span","persona-composer-model-picker-suffix");u.append(p,g);let y=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),h=new Map,C="",E=null,A=()=>E?.isOpen===!0,I=(v=!1)=>{A()&&(E?.close(),u.setAttribute("aria-expanded","false"),v&&u.focus())},L=v=>{let T=[...h.values()];if(T.length===0)return;let x=(v%T.length+T.length)%T.length;T[x].focus()},k=v=>{if(A())return;E||(E=ll({anchor:u,content:y,placement:"top-start",offset:6,onDismiss:()=>u.setAttribute("aria-expanded","false")})),tl(u,y,kw),E.open(),u.setAttribute("aria-expanded","true");let x=[...h.keys()].indexOf(s(t.getModels())?.id??"");L(v??(x>=0?x:0))},R=v=>{I(!0),t.onSelect(v)},B=v=>{v.preventDefault(),v.stopPropagation();let T=v.currentTarget.getAttribute("data-persona-model-option");T&&R(T)},O=v=>{let T=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":v.id}});if(v.icon){let ne=se(v.icon,xh,"currentColor",1.5);if(ne){let he=P("span","persona-composer-model-option-icon");he.appendChild(ne),T.appendChild(he)}}let x=P("span","persona-composer-model-option-body"),z=P("span","persona-composer-model-option-label");if(z.textContent=v.label,x.appendChild(z),v.description){let ne=P("span","persona-composer-model-option-description");ne.textContent=v.description,x.appendChild(ne)}T.appendChild(x);let W=P("span","persona-composer-model-option-check");W.setAttribute("aria-hidden","true");let ee=se("check",xh,"currentColor",2);return ee&&W.appendChild(ee),T.appendChild(W),T.addEventListener("click",B),T},V=()=>{let v=t.getModels(),T=v.map(W=>`${W.id}:${W.label}:${W.icon??""}:${W.description??""}`).join("|");if(T!==C){C=T;for(let W of h.values())W.removeEventListener("click",B);h.clear(),y.replaceChildren(...v.map(W=>{let ee=O(W);return h.set(W.id,ee),ee}))}let x=s(v);for(let[W,ee]of h)ee.setAttribute("aria-selected",String(W===x?.id));p.textContent=x?.label??"";let z=t.getSuffix?.()??"";g.textContent=z,u.setAttribute("aria-label",[e,[x?.label,z].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let J=v=>{v.preventDefault(),v.stopPropagation(),A()?I(!0):k()},_=v=>{if(v.key==="ArrowDown"){v.preventDefault(),A()?L(0):k(0);return}v.key==="ArrowUp"&&(v.preventDefault(),A()?L(-1):k(-1))},Q=v=>{let T=[...h.values()],x=T.indexOf(v.target?.closest?.(".persona-composer-model-option"));switch(v.key){case"ArrowDown":v.preventDefault(),L(x+1);return;case"ArrowUp":v.preventDefault(),L(x-1);return;case"Home":v.preventDefault(),L(0);return;case"End":v.preventDefault(),L(T.length-1);return;case"Escape":v.preventDefault(),v.stopPropagation(),I(!0);return;case"Tab":I(!0);return;default:}};u.addEventListener("click",J),u.addEventListener("keydown",_),y.addEventListener("keydown",Q);let{wrapper:G,chevron:w}=Ah();return G.append(u,w),{element:G,destroy:()=>{o===V&&(o=null),u.removeEventListener("click",J),u.removeEventListener("keydown",_),y.removeEventListener("keydown",Q);for(let v of h.values())v.removeEventListener("click",B);h.clear(),E?.destroy(),E=null,y.remove()}}};return{action:{id:Ew,kind:"custom",placement:"end",order:Tw,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var Pw=":scope > [data-persona-composer-mode]";function Eh(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=p=>{let g=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let E=P("span","persona-mention-chip-icon"),A=se(p.iconName,12,"currentColor",1.5);A&&E.appendChild(A),g.appendChild(E)}let y=P("span","persona-mention-chip-label");y.textContent=p.shortLabel??p.label,g.appendChild(y);let h=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),C=se("x",12,"currentColor",2);return C?h.appendChild(C):h.textContent="\xD7",h.addEventListener("click",E=>{E.preventDefault(),E.stopPropagation(),t.onRemove(p.id)}),g.appendChild(h),g},l=()=>Array.from(e.querySelectorAll(Pw)),c=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let g=()=>{p.remove(),al(e)},y=e.ownerDocument.defaultView,h=typeof y?.getComputedStyle=="function"?y.getComputedStyle(p).animationName:"";if(!h||h==="none"){g();return}p.addEventListener("animationend",g,{once:!0}),p.addEventListener("animationcancel",g,{once:!0})},u=()=>{for(let p of l())p.remove()};return{element:e,render:(p,g)=>{if(o)return;let y=g.filter(A=>p.includes(A.id)),h=y.map(A=>`${A.id}:${A.shortLabel??A.label}`).join("|");if(h===n)return;n=h;let C=new Map;for(let A of l()){let I=A.getAttribute("data-persona-composer-mode");I&&y.some(k=>k.id===I)&&!A.hasAttribute("data-persona-chip-exit")?C.set(I,A):A.hasAttribute("data-persona-chip-exit")||c(A)}let E=e.firstChild;for(let A of y){let I=C.get(A.id);I||(I=i(A),s.has(A.id)||(I.setAttribute("data-persona-chip-enter",""),I.addEventListener("animationend",()=>I?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(A.id),I!==E&&e.insertBefore(I,E),E=I.nextSibling}al(e)},destroy:()=>{o=!0,u(),al(e)}}}var Th=t=>`core:mode:${t}`;var Jd=t=>Math.min(300+t,499),kh=t=>`core:mode-group:${t}`;function Al(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function Lw(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Ph(t,e){return t?.length?t.filter(n=>!Al(n.groupId,e)&&!Lw(n.groupId,e)):[]}var Iw=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Lh(t,e,n,o){let s=n.find(c=>c.id===e);if(!s)return[...t];let i=t.includes(e),l=new Set(t);if(i)l.delete(e);else{if(Iw(s,o)==="single"){let c=n.filter(u=>u.groupId===s.groupId).map(u=>u.id);l=new Set([...l].filter(u=>!c.includes(u)))}l.add(e)}return n.filter(c=>l.has(c.id)).map(c=>c.id)}function Ml(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Ih(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Hh(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var Hw=16;function Rh(t){let e=null;return{action:{id:kh(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=Y("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=p=>{p.preventDefault(),p.stopPropagation();let y=p.currentTarget.getAttribute("data-persona-composer-mode");!y||t.getActiveIds().includes(y)&&t.getGroup()?.selection==="single"||t.onSelect(y)},c=p=>{let g=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let h=se(p.iconName,Hw,"currentColor",1.5);h&&g.appendChild(h)}let y=P("span","persona-composer-segmented-label");return y.textContent=p.shortLabel??p.label,g.appendChild(y),g.addEventListener("click",l),g},u=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let g=t.getModes(),y=g.map(C=>`${C.id}:${C.shortLabel??C.label}:${C.iconName??""}`).join("|");if(y!==i){i=y;for(let E of s.values())E.removeEventListener("click",l);s.clear();let C=g.map(E=>{let A=c(E);return s.set(E.id,A),A});o.replaceChildren(...C)}let h=t.getActiveIds();for(let[C,E]of s)E.setAttribute("aria-pressed",String(h.includes(C)))};return u(),e=u,{element:o,destroy:()=>{e===u&&(e=null);for(let p of s.values())p.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function Wh(t){let e=Y("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,s=i=>{let l=P("span","persona-composer-quote-bar"),c=P("div","persona-composer-quote-content");if(i.sourceLabel){let y=P("div","persona-composer-quote-source");y.textContent=i.sourceLabel,c.appendChild(y)}let u=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});u.textContent=Cl(i.text),c.appendChild(u);let p=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),g=se("x",12,"currentColor",2);g?p.appendChild(g):p.textContent="\xD7",p.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),t.onDismiss()}),e.replaceChildren(l,c,p)};return{element:e,render:i=>{if(o)return;let l=i?`${i.sourceLabel??""}\0${i.text}`:"";if(l!==n){if(n=l,!i){e.replaceChildren(),e.style.display="none";return}s(i),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function Bh(t){let e=Y("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,u,p)=>{let g=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[u]:""}}),y=se(l,12,"currentColor",2);return y?g.appendChild(y):g.textContent=c,g.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),g},i=l=>{let c=Cl(l.text??"",90);if(c)return c;let u=l.contentParts?.length??0;return u>0?u===1?"1 attachment":`${u} attachments`:(l.mentionRefs?.length??0)>0?l.mentionRefs.map(g=>g.label).join(", "):"Queued message"};return{element:e,render:l=>{if(o||l===n)return;if(n=l,!l){e.replaceChildren(),e.style.display="none";return}let c=P("span","persona-composer-pending-badge");c.textContent=t.label??"Sends next";let u=Y("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});u.textContent=i(l),e.replaceChildren(c,u,s("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),s("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function Dh(t){let e=Y("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=Y("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let s=P("div","persona-message-edit-actions"),i=(c,u,p,g)=>{let y=Y("button",{className:`persona-message-edit-button ${u}`,attrs:{type:"button",[p]:""},text:c});return y.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),g()}),y},l=()=>{let c=n.value.trim();c&&t.onSave(c)};return s.append(i(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),i(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",l)),n.addEventListener("keydown",c=>{if(c.key==="Escape"){c.preventDefault(),c.stopPropagation(),t.onCancel();return}c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),l())}),e.append(n,s),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let c=n.value.length;n.setSelectionRange(c,c),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function Oh(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function _h(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(u=>n.has(u.sourceId)),s=o.length===(t.mentionRefs?.length??0)&&o.length>0,i=new Set(e.modes.map(u=>u.id)),l=(t.activeModeIds??[]).filter(u=>i.has(u)),c=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...s?{mentionRefs:o}:{},...s&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...c?{selectedModelId:c}:{},...l.length?{activeModeIds:l}:{},...t.quote?.text?{quote:t.quote}:{}}}function Fh(t){let e=t.delay??500,n=null,o=!1,s=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(s(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(s(),t.write())},cancel:s,destroy:()=>{o=!0,s()}}}function Nh(t){return t.wrapped||t.text.includes(`
|
|
13
|
+
`),c=Array.isArray(e.contentParts)&&e.contentParts.length>0,u=s.contentParts.length>0;if(c){let p=[];i&&p.push(zo(i)),p.push(...s.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(u){let p=[];l&&p.push(zo(l)),p.push(...s.contentParts),e.contentParts=p}else i&&(e.llmContent=l);Object.keys(s.context).length>0&&(e.mentionContext=s.context)}async sendMessage(e,n){let o=e.trim(),s=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!s)return;this.#B&&!n?.voiceTurn&&(this.#B.failed=!0,this.#B=null),(this.#M||this.#y||this.#d||this.#W)&&await this.#Re(),this.stopSpeaking(),this.abortController?.abort(),this.#ee(),this.#j++,this.#ne();let i=n?.voiceTurn?.userMessageId,l=i?this.messages.find(C=>C.id===i&&C.role==="user"):void 0,c=l?.id??bl(),u=hs();this.#i=null;let p=n?.contentParts&&nf(n.contentParts)?Za:"",g={id:c,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#k(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};l?(l.viaVoice=!0,delete l.voiceCaption,l.content.trim()!==o&&(l.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#N(g),this.#g(!0);let y=new AbortController;if(this.abortController=y,n?.mentions){let C=this.messages.find(E=>E.id===c)??g;if(await this.#Xe(C,o,n.mentions.finalize),y.signal.aborted||this.abortController!==y)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let C=this.messages.find(A=>A.id===c)??g,E=rh({quote:n.quote,text:C.llmContent??C.content,contentParts:C.contentParts});E.contentParts&&(C.contentParts=E.contentParts),E.llmContent!==void 0&&(C.llmContent=E.llmContent),(E.contentParts||E.llmContent!==void 0)&&(C.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let h=l?[...this.messages.filter(C=>C!==l),{...l,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(h,y,u,c,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(C){if(this.status==="resuming"||this.#s)return;this.#B&&(this.#B.failed=!0);let E=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!E){let A=jd(C,this.config.errorMessage);if(A){let I={id:u,role:"assistant",createdAt:new Date().toISOString(),content:A,sequence:this.#k()};this.#N(I)}}this.#H("idle"),this.#g(!1),this.abortController=null,E||(C instanceof Error?this.callbacks.onError?.(C):this.callbacks.onError?.(new Error(String(C))))}}resubmitFrom(e,n){let o=sh(this.messages,e);if(!o)return!1;let s=this.messages[o.start],i=n.replacement,l=i?i.text:s.content,c=i?i.contentParts:s.contentParts;if(!(!!l?.trim()||(c?.length??0)>0||!i&&(s.llmContent?.trim()?.length??0)>0))return!1;let p=i?void 0:{...s.llmContent!==void 0&&{llmContent:s.llmContent},...s.rawContent!==void 0&&{rawContent:s.rawContent},...s.mentionContext&&{mentionContext:s.mentionContext},...s.contextMentions&&{contextMentions:s.contextMentions},...s.quote&&{quote:s.quote}},g=i?this.#Je(i.options):s.composerOptions,y=i?i.contentSegments:s.contentSegments,h=i?i.options?.quote:void 0,C=i?i.viaVoice:s.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(l??"",{...c?.length?{contentParts:[...c]}:{},...y?.length?{contentSegments:[...y]}:{},...g?{composerOptions:g}:{},...h?{quote:h}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:C===!0}),!0}#Je(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.#M||this.#y||this.#d||this.#W)&&await this.#Re(),this.abortController?.abort(),this.#ne();let e=hs();this.#i=null,this.#g(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(s){if(this.status==="resuming"||this.#s)return;let i=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!i){let l=jd(s,this.config.errorMessage);if(l){let c={id:e,role:"assistant",createdAt:new Date().toISOString(),content:l,sequence:this.#k()};this.#N(c)}}this.#H("idle"),this.#g(!1),this.abortController=null,i||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.#i=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let l of this.messages)l.streaming&&l.id!==o&&(l.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.#g(!0);let i={};try{await this.client.processStream(e,l=>{let c=this.#o;this.#o=i;try{this.handleEvent(l)}finally{this.#o=c}},n?.assistantMessageId,n?.seedContent),this.#xe(i)}catch(l){if(this.status==="resuming"||this.#s){this.#pt(i);return}this.#xe(i),this.#H("error"),this.webMcpResolveControllers.size===0&&(this.#g(!1),this.abortController=null),this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}}#We(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.#S}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let s=this.messages.find(i=>i.id===e);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}#Ze;#j;#de(e){let n=this.#Ze??={s:this,setStreaming:i=>this.#g(i),appendMessage:i=>this.#N(i),nextSequence:()=>this.#k(),settleApprovalPausedToolCall:i=>this.#Oe(i),resumeAfter:i=>this.#t?.executionId===i?this.#t.lastEventId:void 0},o=oh();if(o)return e(o,n);let s=this.#j;return Nd().then(i=>s===this.#j?e(i,n):void 0,i=>{this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))})}resolveApproval(e,n,o){return this.#de((s,i)=>s.resolveApproval(i,e,n,o))}resolveAskUserQuestion(e,n){return this.#de((o,s)=>o.resolveAskUserQuestion(s,e,n))}resolveWebMcpToolCall(e){return this.#de((n,o)=>n.resolveWebMcpToolCall(o,e))}persistAskUserQuestionProgress(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}#et(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let i=this.#p;queueMicrotask(()=>{i===this.#p&&this.resolveWebMcpToolCall(e)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(o)&&(s.seen.add(o),s.snapshots.push(e))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#p;queueMicrotask(()=>{if(e===this.#p)for(let n of[...this.webMcpAwaitBatches.keys()])this.#nt(n)})}#nt(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.#de((s,i)=>s.resolveWebMcpToolCallBatch(i,e,o))}#ee(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.#p++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#g(!1),this.#H("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.messages=[],this.agentExecution=null,this.#we(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#g(!1),this.#H("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#h}selectArtifact(e){this.#h=e,this.#te()}clearArtifacts(){this.#we()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.#h=n,this.#te(),e.transcript!==!1&&this.#ot(o),o}#ot(e){let n=`artifact-ref-${e.id}`,o=as(this.config.features?.artifacts,e),s=wd(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),i=this.messages.find(l=>l.id===n);if(i){i.rawContent=s,i.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:s})}#Be(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(l=>l.id===`artifact-ref-${n.id}`);if(!o)continue;let s=as(this.config.features?.artifacts,n),i=wd(s,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==i&&(o.rawContent=i,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#we(){this.artifacts.size===0&&this.#h===null||(this.artifacts.clear(),this.#h=null,this.#te())}#te(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#h})}#rt(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.#h=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.#te()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#ne(),this.#ee(),this.#j++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#K(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#k()}))),this.#g(!1),this.#H("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.#h=n,this.#te()}#st(e){let n=this.agentExecution?.executionId;if(!n||!this.#i||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:e,assistantMessageId:this.#i,status:"running"},this.#dt(o)}#it(){return this.#t!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#De()}#De(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}#Se(){this.#s||!this.#t||typeof this.config.reconnectStream!="function"||(this.#s=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#g(!0),this.#H("resuming"),this.#at().then(e=>{this.#s&&this.#t&&e.begin()}))}#at(){return this.#a?Promise.resolve(this.#a):(this.#v||(this.#v=dh().then(({createReconnectController:e})=>{let n=e(this.#lt());return this.#a=n,n}),this.#v.catch(()=>{this.#v=null})),this.#v)}#lt(){let e=this;return{get config(){return e.config},getResumable:()=>e.#t,clearResumable:()=>e.#pe(),getStatus:()=>e.status,setStatus:n=>e.#H(n),setStreaming:n=>e.#g(n),setReconnecting:n=>{e.#s=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,s)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>e.#N(n),nextSequence:()=>e.#k(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>jd(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.#s){this.#a?.wake();return}this.#Se()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.#s)return;let n=this.#ct();n||(n=hs(),this.#N({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#k()})),this.#i=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#t={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.#Se()}#ct(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}#ne(){this.#s=!1,this.#a?.teardown(),this.#pe()}#pe(){this.#c&&(clearTimeout(this.#c),this.#c=null);let e=this.#t!==null;this.#t=null,e&&this.config.onExecutionState?.(null)}#dt(e){let n=this.config.onExecutionState;if(n){if(e){this.#c&&(clearTimeout(this.#c),this.#c=null),n(this.#t);return}this.#c||(this.#c=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#H(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#g(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&(this.#xe(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let s=[...this.messages].reverse().find(l=>l.role==="assistant"&&l.content&&!l.voiceProcessing);if(!s||e&&!e.includes(s.id))return;if(this.ttsSpokenMessageIds.has(s.id)){this.ttsSpokenMessageIds.delete(s.id);return}let i=Ud(s.content);i.trim()&&this.readAloud.play(s.id,{text:i,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(e){return zd(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=Ud(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#xe(e){for(let[n,o]of[...this.#e])o===e&&(this.#e.delete(n),this.#Oe(n))}#pt(e){for(let[n,o]of this.#e)o===e&&this.#e.set(n,void 0)}#Oe(e){let n=this.messages.find(c=>c.id===e)?.approval,o=n?.toolCallId,s=o&&this.messages.find(c=>c.toolCall?.id===o),i=s&&s.toolCall;if(!i||i.status==="complete"||n.status==="pending")return;let l={...i,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...s,streaming:!1,toolCall:l})}#N(e){let n=this.#ie(e);this.messages=this.#K([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.#ie(e),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.#N(n);return}this.messages=this.messages.map((s,i)=>{if(i!==o)return s;let l={...s,...n};s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(l.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(l.agentMetadata={...l.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let c=s.agentMetadata?.clientToolAnswer;if(c&&l.agentMetadata&&!l.agentMetadata.clientToolAnswer&&(l.agentMetadata={...l.agentMetadata,clientToolAnswer:c}),s.approval&&n.approval&&s.approval.id===n.approval.id){let y=s.approval,h=n.approval;l.approval={...y,...h,executionId:h.executionId||y.executionId,toolName:h.toolName||y.toolName,description:h.description||y.description,toolType:h.toolType??y.toolType,reason:h.reason??y.reason,parameters:h.parameters??y.parameters,toolCallId:h.toolCallId??y.toolCallId}}let u=n.toolCall?.name,p=n.agentMetadata?.executionId,g=n.toolCall?.id;if(u&&ph(u)&&p&&g&&n.agentMetadata?.awaitingLocalTool===!0){let y=`${p}:${g}`,h=this.webMcpInflightKeys.has(y),C=this.webMcpResolvedKeys.has(y),E=s.toolCall?.name,A=s.agentMetadata?.executionId===p&&s.toolCall?.id===g&&E!==void 0&&ph(E)&&s.toolCall?.status==="complete";(h||C||A)&&(l.agentMetadata={...l.agentMetadata??{},awaitingLocalTool:!1},l.toolCall=s.toolCall,l.streaming=s.streaming)}return l}),this.messages=this.#K(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#ie(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.#k()}}#k(){return this.#m++}#K(e){return[...e].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),i=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=n.sequence??0,c=o.sequence??0;return l!==c?l-c:n.id.localeCompare(o.id)})}};import{File as nw,FileCode as ow,FileSpreadsheet as rw,FileText as Kd,X as sw}from"lucide";var iw={add:t=>of(t)},aw=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,xl={allowedTypes:us,maxFileSize:10*1024*1024,maxFiles:4};function lw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cw(t){return t==="application/pdf"?Kd:t.startsWith("text/")?Kd:t.includes("word")?Kd:t.includes("excel")||t.includes("spreadsheet")?rw:t==="application/json"?ow:nw}var xi=class t{constructor(e={}){this.attachments=[];this.#e=null;this.#o=new Map;this.#m=!1;this.config={allowedTypes:e.allowedTypes??xl.allowedTypes,maxFileSize:e.maxFileSize??xl.maxFileSize,maxFiles:e.maxFiles??xl.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#e;#o;#m;#t(){return typeof this.config.adapter?.add=="function"}#i(){return this.#t()?this.config.adapter:iw}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML="";for(let n of this.attachments)this.#h(n)}this.#n()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:xl.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#m)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let s=rf(o,this.config.allowedTypes,this.config.maxFileSize);if(!s.valid){let l=s.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,l);continue}let i={id:lw(),file:o,previewUrl:Ed(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#t()?"uploading":"processing",progress:this.#t()?0:void 0};this.attachments.push(i),this.#h(i),n.push(i)}this.#n(),this.#c(),await Promise.all(n.map(o=>this.#s(o)))}async#s(e){let n=new AbortController;this.#o.set(e.id,n);let o=()=>this.#m||n.signal.aborted||this.#o.get(e.id)!==n||!this.attachments.includes(e);try{let s=await this.#i().add(e.file,{signal:n.signal,onProgress:i=>{o()||e.status!=="uploading"||(e.progress=aw(i),this.#p(e),this.#c())}});if(o())return;e.contentPart=s,e.status="ready",e.progress=void 0,e.error=void 0}catch(s){if(o())return;e.status="error",e.progress=void 0,e.error=s instanceof Error?s.message:String(s??"Upload failed")}finally{this.#o.get(e.id)===n&&this.#o.delete(e.id)}this.#p(e),this.#c()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.#m||(n.status=this.#t()?"uploading":"processing",n.progress=this.#t()?0:void 0,n.error=void 0,this.#p(n),this.#c(),this.#s(n))}#a(e){let n=this.#o.get(e);n&&(this.#o.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(i=>i.id===e);if(n===-1)return;let o=this.attachments[n];this.#a(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.#e?.querySelector(`[data-attachment-id="${e}"]`);s&&s.remove(),o.status==="ready"&&o.contentPart&&this.#v(o.contentPart),this.#n(),this.#c()}#v(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(s=>{console.error("[AttachmentManager] adapter.remove failed:",s)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.#a(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#o.clear(),this.#e&&(this.#e.innerHTML=""),this.#n(),this.#c()}destroy(){if(!this.#m){this.#m=!0;for(let e of this.#o.values())e.abort();this.#o.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#m||this.config.onAttachmentsChange?.(this.getAttachments())}#h(e){if(!this.#e)return;let n=Ed(e.file),o=P("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let g=P("img");g.src=e.previewUrl,g.alt=e.file.name,g.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",g.style.width="48px",g.style.height="48px",g.style.objectFit="cover",g.style.borderRadius="8px",o.appendChild(g)}else{let g=P("div");g.style.width="48px",g.style.height="48px",g.style.borderRadius="8px",g.style.backgroundColor="var(--persona-container, #f3f4f6)",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.display="flex",g.style.flexDirection="column",g.style.alignItems="center",g.style.justifyContent="center",g.style.gap="2px",g.style.overflow="hidden";let y=cw(e.file.type),h=yt(y,20,"var(--persona-muted, #6b7280)",1.5);h&&g.appendChild(h);let C=P("span");C.textContent=sf(e.file.type,e.file.name),C.style.fontSize="8px",C.style.fontWeight="600",C.style.color="var(--persona-muted, #6b7280)",C.style.textTransform="uppercase",C.style.lineHeight="1",g.appendChild(C),o.appendChild(g)}let s=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),i=P("div","persona-attachment-progress");i.appendChild(P("div","persona-attachment-progress__bar"));let l=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=se("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);c?l.appendChild(c):l.textContent="\u21BB",l.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.retryAttachment(e.id)}),s.append(i,l),o.appendChild(s);let u=P("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");u.type="button",u.setAttribute("aria-label","Remove attachment"),u.style.position="absolute",u.style.top="-4px",u.style.insetInlineEnd="-4px",u.style.width="18px",u.style.height="18px",u.style.borderRadius="50%",u.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",u.style.border="none",u.style.cursor="pointer",u.style.display="flex",u.style.alignItems="center",u.style.justifyContent="center",u.style.padding="0";let p=yt(sw,10,"var(--persona-text-inverse, #ffffff)",2);p?u.appendChild(p):(u.textContent="\xD7",u.style.color="var(--persona-text-inverse, #ffffff)",u.style.fontSize="14px",u.style.lineHeight="1"),u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(u),this.#e.appendChild(o),this.#S(o,e)}#p(e){let n=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.#S(n,e)}#S(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let s=e.querySelector(".persona-attachment-progress__bar");if(s){let i=n.progress;s.style.width=typeof i=="number"?`${Math.round(i*100)}%`:""}}#n(){this.#e&&(this.#e.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var uh=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),dw=(t,e)=>t.length===e.length&&t.every((n,o)=>{let s=e[o];return n.id===s.id&&n.name===s.name&&n.mimeType===s.mimeType&&n.size===s.size&&n.status===s.status&&n.progress===s.progress&&n.error===s.error});function gh(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,s=!1,i=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",l=()=>{let g=i();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(y=>Object.freeze({...y}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:g,inputDisabled:t.inputDisabled,sendDisabled:g!=="idle"||t.sendDisabled||t.inputDisabled})},c=()=>(n||(n=l()),n),u=()=>{if(o=!1,s||e.size===0)return;let g=c();for(let y of[...e])try{y(g)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},p=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(u))};return{getState:c,subscribe:g=>(e.add(g),()=>e.delete(g)),setText:g=>{t.text!==g&&(t.text=g,p())},setAttachments:g=>{dw(t.attachments,g)||(t.attachments=[...g],p())},setMentionRefs:g=>{uh(t.mentionRefs,g)||(t.mentionRefs=[...g],p())},setSelectedModelId:g=>{t.selectedModelId!==g&&(t.selectedModelId=g,p())},setActiveModeIds:g=>{uh(t.activeModeIds,g)||(t.activeModeIds=[...g],p())},setQuote:g=>{let y=t.quote;y?.text===g?.text&&y?.messageId===g?.messageId&&y?.sourceLabel===g?.sourceLabel||(t.quote=g?{...g}:void 0,p())},setPendingSubmission:g=>{t.pendingSubmission!==g&&(t.pendingSubmission=g,p())},setPreparing:g=>{t.preparing!==g&&(t.preparing=g,p())},setStreaming:g=>{t.streaming!==g&&(t.streaming=g,p())},setInputDisabled:g=>{t.inputDisabled!==g&&(t.inputDisabled=g,p())},setSendDisabled:g=>{t.sendDisabled!==g&&(t.sendDisabled=g,p())},flush:()=>{o&&u()},destroy:()=>{s=!0,o=!1,e.clear()}}}var Qt=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},mh=(t,e)=>{let n=P("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function fh(t,e={}){let n=Qt(t,"[data-persona-composer-form]"),o=Qt(t,"[data-persona-composer-input]");if(!n||!o){let L=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(L);return typeof console<"u"&&console.warn(L),null}let s={header:Qt(t,"[data-persona-composer-header]"),body:Qt(t,"[data-persona-composer-body]"),actionsStart:Qt(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Qt(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Qt(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Qt(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Qt(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=mh("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(l,n):t.appendChild(l));let c=s.body??o.parentElement??n,u=(I,L,k,R,B)=>{if(L)return L;i.add(I);let O=mh(k,R);return B.appendChild(O),O},p=u("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),g=u("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),y=u("suggestions",s.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),h=u("status",s.status,"persona-widget-composer__status","data-persona-composer-status",t),C=[],E=(I,L)=>I.target===L.target&&I.type===L.type&&I.handler===L.handler,A=Qt(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:l,body:c,actionsStart:p,actionsEnd:g,suggestions:y,status:h,attachmentInput:A,attachmentPreviews:Qt(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Qt(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Qt(t,"[data-persona-composer-submit]")??void 0,micButton:Qt(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(I,L,k,R)=>{I.addEventListener(L,k,R),C.push({target:I,type:L,handler:k,options:R})},removeListener:(I,L,k,R)=>{I.removeEventListener(L,k,R),C=C.filter(B=>!E(B,{target:I,type:L,handler:k}))},destroy:()=>{for(let I of C)I.target.removeEventListener(I.type,I.handler,I.options);C=[]}}}var pw='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',uw=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],Gd="data-persona-menu-focus",gw=new Set(["ArrowDown","ArrowUp","Home","End"]);function hh(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(pw)??t}var mw=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function yh(t){let e=t.label,n=!1,o=P("div","persona-send-button-wrapper"),s=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Uo} ${Mr}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=Y("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),l=()=>{let x=t.getButtonSize?.()??"";s.style.width=x,s.style.height=x,s.style.minWidth=x,s.style.minHeight=x,s.style.lineHeight="1",s.replaceChildren();let z=se("plus",qn,"currentColor",1.5);z?s.appendChild(z):s.textContent="+"},c=()=>{s.setAttribute("aria-label",e),s.setAttribute("title",e),i.setAttribute("aria-label",e)};c(),l();let u=[],p=-1,g=!1,y=()=>{let z=i.getRootNode().activeElement;return z instanceof HTMLElement?z:null},h=()=>{let x=y();for(let z of u){let W=!!x&&hh(z)===x;z.toggleAttribute(Gd,W&&g)}},C=()=>u.filter(x=>x.isConnected||i.contains(x)).map(hh).filter(x=>!mw(x)),E=(x,z)=>{x.forEach((W,ee)=>{W.setAttribute("tabindex",ee===z?"0":"-1")})},A=x=>{let z=C();if(z.length===0)return;let W=(x%z.length+z.length)%z.length;p=W,E(z,W),z[W].focus(),h()},I=()=>o.ownerDocument??document,L=null,k=null,R=null,B=()=>{L&&(I().removeEventListener("focusin",L,!0),L=null)},O=()=>{k&&(i.removeEventListener("focusin",k),k=null),R&&(i.removeEventListener("pointerdown",R,!0),R=null)},V=null,J=()=>(V||(V=ll({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),B()}})),V),_=()=>V?.isOpen===!0,Q=(x=!1)=>{if(_()){V?.close(),s.setAttribute("aria-expanded","false"),B(),O(),p=-1,g=!1;for(let z of u)z.removeAttribute(Gd);x&&s.focus()}},G=(x=0,z=!1)=>{if(n||_())return;g=z,tl(s,i,uw),J().open(),s.setAttribute("aria-expanded","true");let W=C();E(W,-1),A(x<0?W.length-1:x),L=ee=>{let ne=typeof ee.composedPath=="function"?ee.composedPath():[];ne.includes(i)||ne.includes(o)||Q()},I().addEventListener("focusin",L,!0),k=()=>h(),i.addEventListener("focusin",k),R=()=>{g=!1},i.addEventListener("pointerdown",R,!0)},w=x=>{x.preventDefault(),x.stopPropagation(),_()?Q(!0):G(0)},v=x=>{if(x.key==="ArrowDown"||x.key==="Enter"||x.key===" "){x.preventDefault(),g=!0,_()?A(0):G(0,!0);return}x.key==="ArrowUp"&&(x.preventDefault(),g=!0,_()?A(-1):G(-1,!0))},T=x=>{switch(gw.has(x.key)&&(g=!0),x.key){case"ArrowDown":x.preventDefault(),A(p+1);return;case"ArrowUp":x.preventDefault(),A(p-1);return;case"Home":x.preventDefault(),A(0);return;case"End":x.preventDefault(),A(C().length-1);return;case"Escape":x.preventDefault(),x.stopPropagation(),Q(!0);return;case"Tab":Q(!0);return;default:}};return s.addEventListener("click",w),s.addEventListener("keydown",v),i.addEventListener("keydown",T),{trigger:o,triggerButton:s,panel:i,setItems:x=>{for(let W of u)x.includes(W)||W.removeAttribute(Gd);if(u=[...x],!_())return;let z=C();E(z,Math.min(p,z.length-1)),h()},isOpen:_,open:()=>G(0),close:Q,setLabel:x=>{x!==e&&(e=x,c())},applyButtonSize:l,destroy:()=>{n=!0,B(),O(),s.removeEventListener("click",w),s.removeEventListener("keydown",v),i.removeEventListener("keydown",T),V?.destroy(),V=null,o.remove(),i.remove(),u=[]}}}var Kn={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},bh="data-persona-composer-action",Yd="data-persona-composer-disable-when-streaming",fw="core:overflow",hw=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function yw(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=P("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let s=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(s)&&s>0?s:Number.isFinite(n)?n:null}function Qd(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),s=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-s)}var vh=(t,e)=>{!t||typeof console>"u"||console.warn(e)},bw=(t,e)=>e.includes(":")?e:`${t}:${e}`;function vw(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let u=o.get(c.id);if(u){vh(e,`[Persona] composer action "${c.id}" is already contributed by ${Ch(u)}; the ${Ch(c)} copy is ignored.`);return}o.set(c.id,c),n.push(c)};for(let c of t.builtIns)i({id:c.id,placement:c.placement,presentation:"bar",order:c.order,sequence:s++,source:"core",builtIn:c});let l=(c,u,p)=>{let g=p?bw(p,c.id):c.id,y=c.order??Kn.custom;c.placement==="end"&&y>=Kn.send&&(vh(e,`[Persona] composer action "${g}" ordered at ${y} would render after send; clamped to ${Kn.send-1}.`),y=Kn.send-1),i({id:g,placement:c.placement,presentation:c.presentation??"bar",order:y,sequence:s++,source:u,pluginId:p,action:c})};for(let c of t.configActions??[])l(c,"config");for(let c of t.plugins){if(!c.contributeComposerActions)continue;let u;try{u=c.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,p);continue}for(let p of u??[])l(p,"plugin",c.id)}return n.sort((c,u)=>c.order===u.order?c.sequence-u.sequence:c.order-u.order)}var Ch=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",wh=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,Cw=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function ww(t,e){if(!t||t==="always")return!0;let n=Cw(e);return t==="when-text"?n:!n}var jo=t=>t.kind==="custom",Xd=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,Sw=t=>{let e=Xd(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},xw='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Aw(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let s=o;typeof s.matches=="function"&&s.matches(xw)||o.childNodes.forEach(n)};return n(t),e.trim()}var Mw=t=>Aw(t).length===0;function Sh(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(w,v)=>{let T=w.button;if(!T)return;T.setAttribute("role","menuitem"),T.setAttribute("tabindex","-1"),T.className="persona-composer-overflow-menu__item";for(let W of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])T.style[W]="";T.style.lineHeight="1",v.tooltipText?T.setAttribute("title",v.tooltipText):T.removeAttribute("title"),T.replaceChildren();let x=P("span","persona-composer-overflow-menu__icon");if(v.iconName){let W=se(v.iconName,16,"currentColor",1.5);W&&x.appendChild(W)}let z=P("span","persona-composer-overflow-menu__label");z.textContent=v.shortLabel??v.label,T.append(x,z)},l=(w,v)=>{let T=w.button;if(!T)return;if(T.setAttribute("aria-label",v.label),v.pressed===void 0?T.removeAttribute("aria-pressed"):T.setAttribute("aria-pressed",v.pressed?"true":"false"),T.toggleAttribute(Yd,v.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,i(w,v);return}T.removeAttribute("role"),T.removeAttribute("tabindex"),T.removeAttribute("title");let x=s(),z=!!v.shortLabel;if(T.className=ss("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Uo,Mr,z&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),T.style.width=x&&!z?x:"",T.style.height=x??"",T.style.minWidth=x&&!z?x:"",T.style.minHeight=x??"",T.style.fontSize=z?"":"18px",T.style.lineHeight="1",T.style.color=v.iconColor??"",T.style.backgroundColor=v.backgroundColor??"",T.replaceChildren(),v.iconName){let W=se(v.iconName,qn,"currentColor",1.5);W&&T.appendChild(W)}if(z){let W=P("span","persona-composer-action-button__label");W.textContent=v.shortLabel,T.appendChild(W)}else T.firstChild||(T.textContent=v.label);w.tooltip?.destroy(),w.tooltip=vn({anchor:T,trigger:w.element,text:()=>v.tooltipText??v.label,enabled:!!v.tooltipText})},c=(w,v)=>{let T=w.action,x=Y("button",{attrs:{type:"button"}}),z=x;if(v==="bar"){let ne=P("div","persona-send-button-wrapper");ne.appendChild(x),z=ne}z.setAttribute(bh,w.id);let W={resolved:w,element:z,button:x,owned:!0,managed:!0,busy:!1,visible:!0,mode:v},ee=ne=>{if(ne.preventDefault(),ne.stopPropagation(),W.busy||x.disabled)return;let he=W.resolved.action;W.mode==="menu"&&C?.close(!0);let ve;try{ve=he.onSelect(t.actionContext,ne)}catch(Xe){t.reportError(Xe,{actionId:W.resolved.id});return}!ve||typeof ve.then!="function"||(W.busy=!0,x.setAttribute("aria-busy","true"),ve.catch(Xe=>{t.reportError(Xe,{actionId:W.resolved.id})}).finally(()=>{W.busy=!1,x.removeAttribute("aria-busy")}))};return x.addEventListener("click",ee),W.detach=()=>x.removeEventListener("click",ee),l(W,T),W},u=w=>{let v=w.action,T;try{T=v.render({...t.actionContext,id:w.id,action:v})}catch(x){return t.reportError(x,{actionId:w.id}),null}return T?.element?(T.element.setAttribute(bh,w.id),T.element.toggleAttribute(Yd,v.disableWhenStreaming===!0),{resolved:w,element:T.element,owned:!0,managed:!0,destroy:T.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(w,v)=>{if(w.builtIn){let x=w.builtIn.element;return x?{resolved:w,element:x,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let T=w.action;return T?jo(T)?u(w):c(w,v):null},g=w=>{if(w.detach?.(),w.tooltip?.destroy(),w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0,w.owned){try{w.destroy?.()}catch(v){t.reportError(v,{actionId:w.resolved.id})}w.element.remove()}},y=(w,v)=>{for(let T=0;T<v.length;T++){let x=v[T];if(!x.managed)continue;let z=null;for(let W=T+1;W<v.length;W++){let ee=v[W];if(!ee.managed&&ee.element.parentElement===w){z=ee.element;break}}z?(x.element.parentElement!==w||x.element.nextSibling!==z)&&w.insertBefore(x.element,z):w.lastChild!==x.element&&w.appendChild(x.element)}},h=(w,v)=>{if(w.button){w.button.disabled=v;return}if(!w.owned)return;let T=w.element;T.toggleAttribute("data-disabled",v),T.setAttribute("aria-disabled",v?"true":"false");let x=T instanceof HTMLButtonElement||T instanceof HTMLSelectElement||T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement?T:T.querySelector("button, select, input, textarea");x&&(x.disabled=v)},C=null,E=null,A=null,I=0,L=()=>{let w=t.getOverflow?.();return w?.enabled===!0?w:void 0},k=()=>(C?C.setLabel(t.getOverflowLabel?.()??"More actions"):C=yh({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),C),R=w=>{E!==w&&(A?.disconnect(),E=w,I=Qd(w),!(typeof ResizeObserver>"u")&&(A=new ResizeObserver(v=>{let x=v[v.length-1]?.contentRect?.width??Qd(w);x!==I&&(I=x,Q())}),A.observe(w)))},B=(w,v)=>{let T=yw(w.collapseAutoActionsBelow,v);if(T===null)return!1;let x=I||Qd(v);return x>0&&x<T},O=(w,v,T)=>{if(!v)return"bar";if(w.resolved.builtIn){let z=hw(w.resolved.id);return z&&v.includeBuiltIns?.includes(z)?"menu":"bar"}let x=w.resolved.presentation;return x==="overflow"||x==="auto"&&T?"menu":"bar"},V=w=>{let v=w.menuSlot;if(!v)return;if(!Mw(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let T=Sw(w.element);if(!T){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=P("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==T&&(w.menuLabel.textContent=T),w.menuLabel.parentElement!==v&&v.appendChild(w.menuLabel)},J=(w,v)=>{if(w.mode===v)return w;let T=w.resolved.action;if(T&&!jo(T)){g(w),e.delete(w.resolved.id);let x=c(w.resolved,v);return e.set(w.resolved.id,x),x}if(v==="menu"){let x=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[lf]:""}});x.appendChild(w.element),cf(Xd(w.element)),w.menuSlot=x;let z=W=>{let ee=Xd(w.element);if(ee.disabled)return;let ne=W.target===ee||ee.contains(W.target);C?.close(!0),ne||ee.click()};x.addEventListener("click",z,!0),w.detachMenuSlot=()=>x.removeEventListener("click",z,!0),w.managed=!0,V(w)}else w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0;return w.mode=v,w},_=(w,v)=>{let T=v.map(x=>x.menuSlot??x.element);for(T.forEach((x,z)=>{let W=w.children[z];W!==x&&(W?w.insertBefore(x,W):w.appendChild(x))});w.children.length>T.length;)w.lastElementChild?.remove()},Q=()=>{if(o)return;let w=t.getBindings();if(!w)return;let v=t.getState(),T=v.phase==="streaming",x=L();x&&R(w.footer);let z=x?B(x,w.footer):!1,W={start:[],end:[]},ee=[];for(let ne of n){let he=e.get(ne.id);if(!he)continue;let ve=ne.action,Xe=ve?wh(ve.visible,v,!0)&&ww(ve.visibility,v):!0;if(he.visible!==Xe&&(he.visible=Xe,!Xe&&he.managed&&(he.menuSlot??he.element).remove()),!!Xe){if(he=J(he,O(he,x,z)),ve){let Je=wh(ve.disabled,v,!1)||ve.disableWhenStreaming===!0&&T;h(he,Je),!jo(ve)&&ve.pressed!==void 0&&he.button?.setAttribute("aria-pressed",ve.pressed?"true":"false")}he.mode==="menu"?(V(he),ee.push(he)):W[ne.placement].push(he)}}if(ee.length>0){let ne=k();_(ne.panel,ee),ne.setItems(ee.map(Je=>Je.menuSlot??Je.element)),ne.applyButtonSize();let he=Number.isFinite(x?.order)?x?.order:Kn.overflow,ve=W.start.findIndex(Je=>Je.resolved.order>he),Xe={resolved:{id:fw,placement:"start",presentation:"bar",order:he,sequence:-1,source:"core"},element:ne.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};W.start.splice(ve<0?W.start.length:ve,0,Xe)}else C&&(C.close(),C.trigger.remove(),C.setItems([]));y(w.actionsStart,W.start),y(w.actionsEnd,W.end)};return{resolve:()=>{if(o)return;let w=vw(t.collect()),v=new Set(w.map(T=>T.id));for(let[T,x]of e)v.has(T)||(g(x),e.delete(T));for(let T of w){let x=e.get(T.id);if(!x){let ne=p(T,"bar");ne&&e.set(T.id,ne);continue}let z=x.resolved.action,W=T.action;if(!!z!=!!W||z&&W&&jo(z)!==jo(W)||z&&W&&jo(z)&&jo(W)&&z.render!==W.render){g(x),e.delete(T.id);let ne=p(T,x.mode);ne&&e.set(T.id,ne);continue}x.resolved=T,T.builtIn?(x.managed=T.builtIn.managed===!0||x.mode==="menu",T.builtIn.element&&x.mode==="bar"&&(x.element=T.builtIn.element)):W&&!jo(W)?l(x,W):W&&x.element.toggleAttribute(Yd,W.disableWhenStreaming===!0)}n=w,Q()},sync:Q,getResolved:()=>n,getOverflowMenu:()=>C,destroy:()=>{if(!o){o=!0,A?.disconnect(),A=null,E=null;for(let w of e.values())g(w);e.clear(),C?.destroy(),C=null,n=[]}}}}var Ew="core:model",Tw=700,xh=16,kw=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],Ah=()=>{let t=Y("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=Y("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Mh(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=u=>{let p=t.getSelectedModelId();return u.find(g=>g.id===p)??u[0]},i=()=>{let u=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",g=()=>{let A=t.getModels(),I=A.map(L=>`${L.id}:${L.label}`).join("|");I!==p&&(p=I,u.replaceChildren(...A.map(L=>{let k=Y("option",{attrs:{value:L.id}});return k.textContent=L.label,k}))),u.value=s(A)?.id??""};g(),o=g;let y=()=>{u.value&&t.onSelect(u.value)};u.addEventListener("change",y);let h=A=>A.stopPropagation();u.addEventListener("click",h);let{wrapper:C,chevron:E}=Ah();return C.append(u,E),{element:C,destroy:()=>{o===g&&(o=null),u.removeEventListener("change",y),u.removeEventListener("click",h)}}},l=()=>{let u=Y("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=P("span","persona-composer-model-picker-label"),g=P("span","persona-composer-model-picker-suffix");u.append(p,g);let y=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),h=new Map,C="",E=null,A=()=>E?.isOpen===!0,I=(v=!1)=>{A()&&(E?.close(),u.setAttribute("aria-expanded","false"),v&&u.focus())},L=v=>{let T=[...h.values()];if(T.length===0)return;let x=(v%T.length+T.length)%T.length;T[x].focus()},k=v=>{if(A())return;E||(E=ll({anchor:u,content:y,placement:"top-start",offset:6,onDismiss:()=>u.setAttribute("aria-expanded","false")})),tl(u,y,kw),E.open(),u.setAttribute("aria-expanded","true");let x=[...h.keys()].indexOf(s(t.getModels())?.id??"");L(v??(x>=0?x:0))},R=v=>{I(!0),t.onSelect(v)},B=v=>{v.preventDefault(),v.stopPropagation();let T=v.currentTarget.getAttribute("data-persona-model-option");T&&R(T)},O=v=>{let T=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":v.id}});if(v.icon){let ne=se(v.icon,xh,"currentColor",1.5);if(ne){let he=P("span","persona-composer-model-option-icon");he.appendChild(ne),T.appendChild(he)}}let x=P("span","persona-composer-model-option-body"),z=P("span","persona-composer-model-option-label");if(z.textContent=v.label,x.appendChild(z),v.description){let ne=P("span","persona-composer-model-option-description");ne.textContent=v.description,x.appendChild(ne)}T.appendChild(x);let W=P("span","persona-composer-model-option-check");W.setAttribute("aria-hidden","true");let ee=se("check",xh,"currentColor",2);return ee&&W.appendChild(ee),T.appendChild(W),T.addEventListener("click",B),T},V=()=>{let v=t.getModels(),T=v.map(W=>`${W.id}:${W.label}:${W.icon??""}:${W.description??""}`).join("|");if(T!==C){C=T;for(let W of h.values())W.removeEventListener("click",B);h.clear(),y.replaceChildren(...v.map(W=>{let ee=O(W);return h.set(W.id,ee),ee}))}let x=s(v);for(let[W,ee]of h)ee.setAttribute("aria-selected",String(W===x?.id));p.textContent=x?.label??"";let z=t.getSuffix?.()??"";g.textContent=z,u.setAttribute("aria-label",[e,[x?.label,z].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let J=v=>{v.preventDefault(),v.stopPropagation(),A()?I(!0):k()},_=v=>{if(v.key==="ArrowDown"){v.preventDefault(),A()?L(0):k(0);return}v.key==="ArrowUp"&&(v.preventDefault(),A()?L(-1):k(-1))},Q=v=>{let T=[...h.values()],x=T.indexOf(v.target?.closest?.(".persona-composer-model-option"));switch(v.key){case"ArrowDown":v.preventDefault(),L(x+1);return;case"ArrowUp":v.preventDefault(),L(x-1);return;case"Home":v.preventDefault(),L(0);return;case"End":v.preventDefault(),L(T.length-1);return;case"Escape":v.preventDefault(),v.stopPropagation(),I(!0);return;case"Tab":I(!0);return;default:}};u.addEventListener("click",J),u.addEventListener("keydown",_),y.addEventListener("keydown",Q);let{wrapper:G,chevron:w}=Ah();return G.append(u,w),{element:G,destroy:()=>{o===V&&(o=null),u.removeEventListener("click",J),u.removeEventListener("keydown",_),y.removeEventListener("keydown",Q);for(let v of h.values())v.removeEventListener("click",B);h.clear(),E?.destroy(),E=null,y.remove()}}};return{action:{id:Ew,kind:"custom",placement:"end",order:Tw,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var Pw=":scope > [data-persona-composer-mode]";function Eh(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=p=>{let g=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let E=P("span","persona-mention-chip-icon"),A=se(p.iconName,12,"currentColor",1.5);A&&E.appendChild(A),g.appendChild(E)}let y=P("span","persona-mention-chip-label");y.textContent=p.shortLabel??p.label,g.appendChild(y);let h=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),C=se("x",12,"currentColor",2);return C?h.appendChild(C):h.textContent="\xD7",h.addEventListener("click",E=>{E.preventDefault(),E.stopPropagation(),t.onRemove(p.id)}),g.appendChild(h),g},l=()=>Array.from(e.querySelectorAll(Pw)),c=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let g=()=>{p.remove(),al(e)},y=e.ownerDocument.defaultView,h=typeof y?.getComputedStyle=="function"?y.getComputedStyle(p).animationName:"";if(!h||h==="none"){g();return}p.addEventListener("animationend",g,{once:!0}),p.addEventListener("animationcancel",g,{once:!0})},u=()=>{for(let p of l())p.remove()};return{element:e,render:(p,g)=>{if(o)return;let y=g.filter(A=>p.includes(A.id)),h=y.map(A=>`${A.id}:${A.shortLabel??A.label}`).join("|");if(h===n)return;n=h;let C=new Map;for(let A of l()){let I=A.getAttribute("data-persona-composer-mode");I&&y.some(k=>k.id===I)&&!A.hasAttribute("data-persona-chip-exit")?C.set(I,A):A.hasAttribute("data-persona-chip-exit")||c(A)}let E=e.firstChild;for(let A of y){let I=C.get(A.id);I||(I=i(A),s.has(A.id)||(I.setAttribute("data-persona-chip-enter",""),I.addEventListener("animationend",()=>I?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(A.id),I!==E&&e.insertBefore(I,E),E=I.nextSibling}al(e)},destroy:()=>{o=!0,u(),al(e)}}}var Th=t=>`core:mode:${t}`;var Jd=t=>Math.min(300+t,499),kh=t=>`core:mode-group:${t}`;function Al(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function Lw(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Ph(t,e){return t?.length?t.filter(n=>!Al(n.groupId,e)&&!Lw(n.groupId,e)):[]}var Iw=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Lh(t,e,n,o){let s=n.find(c=>c.id===e);if(!s)return[...t];let i=t.includes(e),l=new Set(t);if(i)l.delete(e);else{if(Iw(s,o)==="single"){let c=n.filter(u=>u.groupId===s.groupId).map(u=>u.id);l=new Set([...l].filter(u=>!c.includes(u)))}l.add(e)}return n.filter(c=>l.has(c.id)).map(c=>c.id)}function Ml(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Ih(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Hh(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var Hw=16;function Rh(t){let e=null;return{action:{id:kh(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=Y("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=p=>{p.preventDefault(),p.stopPropagation();let y=p.currentTarget.getAttribute("data-persona-composer-mode");!y||t.getActiveIds().includes(y)&&t.getGroup()?.selection==="single"||t.onSelect(y)},c=p=>{let g=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let h=se(p.iconName,Hw,"currentColor",1.5);h&&g.appendChild(h)}let y=P("span","persona-composer-segmented-label");return y.textContent=p.shortLabel??p.label,g.appendChild(y),g.addEventListener("click",l),g},u=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let g=t.getModes(),y=g.map(C=>`${C.id}:${C.shortLabel??C.label}:${C.iconName??""}`).join("|");if(y!==i){i=y;for(let E of s.values())E.removeEventListener("click",l);s.clear();let C=g.map(E=>{let A=c(E);return s.set(E.id,A),A});o.replaceChildren(...C)}let h=t.getActiveIds();for(let[C,E]of s)E.setAttribute("aria-pressed",String(h.includes(C)))};return u(),e=u,{element:o,destroy:()=>{e===u&&(e=null);for(let p of s.values())p.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function Wh(t){let e=Y("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,s=i=>{let l=P("span","persona-composer-quote-bar"),c=P("div","persona-composer-quote-content");if(i.sourceLabel){let y=P("div","persona-composer-quote-source");y.textContent=i.sourceLabel,c.appendChild(y)}let u=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});u.textContent=Cl(i.text),c.appendChild(u);let p=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),g=se("x",12,"currentColor",2);g?p.appendChild(g):p.textContent="\xD7",p.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),t.onDismiss()}),e.replaceChildren(l,c,p)};return{element:e,render:i=>{if(o)return;let l=i?`${i.sourceLabel??""}\0${i.text}`:"";if(l!==n){if(n=l,!i){e.replaceChildren(),e.style.display="none";return}s(i),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function Bh(t){let e=Y("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,u,p)=>{let g=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[u]:""}}),y=se(l,12,"currentColor",2);return y?g.appendChild(y):g.textContent=c,g.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),g},i=l=>{let c=Cl(l.text??"",90);if(c)return c;let u=l.contentParts?.length??0;return u>0?u===1?"1 attachment":`${u} attachments`:(l.mentionRefs?.length??0)>0?l.mentionRefs.map(g=>g.label).join(", "):"Queued message"};return{element:e,render:l=>{if(o||l===n)return;if(n=l,!l){e.replaceChildren(),e.style.display="none";return}let c=P("span","persona-composer-pending-badge");c.textContent=t.label??"Sends next";let u=Y("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});u.textContent=i(l),e.replaceChildren(c,u,s("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),s("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function Dh(t){let e=Y("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=Y("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let s=P("div","persona-message-edit-actions"),i=(c,u,p,g)=>{let y=Y("button",{className:`persona-message-edit-button ${u}`,attrs:{type:"button",[p]:""},text:c});return y.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),g()}),y},l=()=>{let c=n.value.trim();c&&t.onSave(c)};return s.append(i(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),i(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",l)),n.addEventListener("keydown",c=>{if(c.key==="Escape"){c.preventDefault(),c.stopPropagation(),t.onCancel();return}c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),l())}),e.append(n,s),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let c=n.value.length;n.setSelectionRange(c,c),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function Oh(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function _h(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(u=>n.has(u.sourceId)),s=o.length===(t.mentionRefs?.length??0)&&o.length>0,i=new Set(e.modes.map(u=>u.id)),l=(t.activeModeIds??[]).filter(u=>i.has(u)),c=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...s?{mentionRefs:o}:{},...s&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...c?{selectedModelId:c}:{},...l.length?{activeModeIds:l}:{},...t.quote?.text?{quote:t.quote}:{}}}function Fh(t){let e=t.delay??500,n=null,o=!1,s=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(s(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(s(),t.write())},cancel:s,destroy:()=>{o=!0,s()}}}function Nh(t){return t.wrapped||t.text.includes(`
|
|
14
14
|
`)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission)}function Vh(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function $h(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),s=Number.parseFloat(n.fontSize),i=Number.isFinite(o)&&o>0?o:Number.isFinite(s)&&s>0?s*1.4:0;if(!i)return!1;let l=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-l>i*1.5}function Zd(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function Uh(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var Rw=t=>typeof t?.then=="function";function zh(t,e){return e===!1?{status:"canceled"}:!e||typeof e!="object"?{status:"proceed"}:(typeof e.text=="string"&&(t.text=e.text),e.options&&(t.options={...t.options,...e.options}),{status:"proceed"})}function qh(t,e,n){let o;try{o=t(Zd(e),{signal:n})}catch(s){return{status:"error",error:s}}return Rw(o)?Promise.resolve(o).then(s=>n.aborted?{status:"aborted"}:zh(e,s),s=>n.aborted?{status:"aborted"}:{status:"error",error:s}):zh(e,o)}var El=t=>t?.launcher?.variant??(t?.future?.v5Defaults===!0?"circle":"pill"),Tl={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var Pl="16px",Ll="transparent",Ww=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),Ai={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:Ww,typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},kl={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},an={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Rm,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Pl,canvasBackground:Ll,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}},Bw=Ai.colors.gray,Dw={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},Ow={...Ai,colors:{...Ai.colors,gray:Bw}},_w={...Ai,colors:{...Ai.colors,gray:Dw},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var Fw=kl,Nw={...kl,colors:{...kl.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...kl.typography,fontSize:"14px",lineHeight:"1.5"}};var tp=an,Vw={...an,launcher:Tl,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...an.input,borderRadius:"palette.radius.full"},introCard:{...an.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...an.suggestion.chip,fontWeight:"400"},card:{...an.suggestion.card,fontWeight:"400"},list:{...an.suggestion.list,fontWeight:"400"}},panel:{...an.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...an.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...an.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...an.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...an.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...an.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}};var $w=t=>Ar({future:t}),np=t=>$w(t)==="v5"?{palette:_w,semantic:Nw,components:Vw}:{palette:Ow,semantic:Fw,components:tp};function Pt(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let s of n){if(o==null)return;o=o[s]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Pt(t,o):o}function Kh(t){let e={};function n(o,s){for(let[i,l]of Object.entries(o)){let c=`${s}.${i}`;if(typeof l=="string"){let u=Pt(t,l);u!==void 0&&(e[c]={path:c,value:u,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof l=="object"&&l!==null&&n(l,c)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function zw(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function Gh(t,e){let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];i&&typeof i=="object"&&!Array.isArray(i)&&s&&typeof s=="object"&&!Array.isArray(s)?n[o]=Gh(i,s):n[o]=s}return n}function Uw(t,e){return e?Gh(t,e):t}function ys(t,e={}){let n=np(e.future),o={palette:n.palette,semantic:n.semantic,components:n.components},s={palette:{...o.palette,...t?.palette,colors:{...o.palette.colors,...t?.palette?.colors},spacing:{...o.palette.spacing,...t?.palette?.spacing},typography:{...o.palette.typography,...t?.palette?.typography},shadows:{...o.palette.shadows,...t?.palette?.shadows},borders:{...o.palette.borders,...t?.palette?.borders},radius:{...o.palette.radius,...t?.palette?.radius}},semantic:{...o.semantic,...t?.semantic,colors:{...o.semantic.colors,...t?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...t?.semantic?.spacing},typography:{...o.semantic.typography,...t?.semantic?.typography}},components:Uw(o.components,t?.components)},i=t?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let g of["rowHeight","labelSize","iconSize","indent","bodySurface"])i?.[g]!==void 0&&(s.components[p][g]=i[g]);let l=t?.components?.collapsibleWidget?.surface;l!==void 0&&i?.bodySurface===void 0&&(s.components.activity={...s.components.activity,bodySurface:l});let c=t?.components?.header;c?.padding!==void 0&&c.minimalPadding===void 0&&(s.components.header.minimalPadding=s.components.header.padding);let u=t?.components?.message;if(u?.gap!==void 0&&u.fullscreenGap===void 0&&(s.components.message.fullscreenGap=s.components.message.gap),e.validate!==!1){let p=zw(s);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(g=>g.message).join(", ")}`)}if(e.plugins)for(let p of e.plugins)s=p.transform(s);return s}var ep=t=>t.trim()==="0"?"0px":t,jh="--persona-",qw=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let l=e.slice(1);if(!/^[0-9a-f]+$/.test(l))return;l.length===3||l.length===4?n=[0,1,2].map(c=>parseInt(l[c]+l[c],16)):(l.length===6||l.length===8)&&(n=[0,2,4].map(c=>parseInt(l.slice(c,c+2),16)))}else{let l=e.match(/^rgba?\(([^)]+)\)$/);if(l){let c=l[1].split(/[,/\s]+/).filter(Boolean);c.length>=3&&(n=c.slice(0,3).map(u=>{let p=u.endsWith("%"),g=parseFloat(p?u.slice(0,-1):u);return p?g/100*255:g}))}}if(!n||n.some(l=>!Number.isFinite(l)))return;let[o,s,i]=n.map(l=>{let c=Math.max(0,Math.min(255,l))/255;return c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4)});return .2126*o+.7152*s+.0722*i},jw=.179,kt=(t,e)=>{for(let[n,...o]of e){let s;for(let i of o)if(s=i.charCodeAt(0)===61?i.slice(1):t[jh+i],s!==void 0)break;s!==void 0&&(t[jh+n]=s)}};function Yh(t){let e=Kh(t),n={};for(let[H,Me]of Object.entries(e)){let de=H.replace(/\./g,"-");n[`--persona-${de}`]=Me.value}kt(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],kt(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),kt(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,kt(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Pl,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ll,kt(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),kt(n,[["header-bg","components-header-background","surface"]]);let s=n["--persona-header-bg"],i=n["--persona-components-header-foreground"],l=i?`color-mix(in srgb, ${i} 72%, ${s})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(i?`color-mix(in srgb, ${i} 14%, ${s})`:void 0)??n["--persona-divider"],kt(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??i??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??l??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??l??n["--persona-muted"],kt(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let c=t.components?.header;c?.shadow&&(n["--persona-header-shadow"]=c.shadow),c?.borderBottom&&(n["--persona-header-border-bottom"]=c.borderBottom),c?.minHeight&&(n["--persona-header-min-height"]=c.minHeight);let u=n["--persona-components-history-railHeader-background"];u&&(n["--persona-history-rail-header-bg"]=u);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let g=n["--persona-components-history-railHeader-minHeight"];g&&(n["--persona-history-rail-header-min-height"]=g);for(let[H,Me]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let de=n[`--persona-components-history-overlay-${H}`];de&&(n[`--persona-history-overlay-${Me}`]=de)}for(let[H,Me]of[["background","bg"],["borderRadius","radius"]]){let de=n[`--persona-components-history-menu-${H}`];de&&(n[`--persona-history-menu-${Me}`]=de)}let y=t.components?.history?.motion;if(y){let H=In=>{if(In===void 0)return;let Ps=String(In).trim();return/^\d+(\.\d+)?$/.test(Ps)?`${Ps}ms`:Ps},Me=H(y.enterDurationMs);Me!==void 0&&(n["--persona-history-enter-ms"]=Me);let de=H(y.exitDurationMs);de!==void 0&&(n["--persona-history-exit-ms"]=de),y.enterEasing&&(n["--persona-history-enter-easing"]=y.enterEasing),y.exitEasing&&(n["--persona-history-exit-easing"]=y.exitEasing)}let h=n["--persona-components-history-dangerForeground"];h&&(n["--persona-history-danger-fg"]=h),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let H of["scrim","shadow"]){let Me=n[`--persona-components-history-confirm-${H}`];Me&&(n[`--persona-history-confirm-${H}`]=Me)}for(let[H,Me]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let de=n[`--persona-components-tooltip-${H}`];de&&(n[`--persona-tooltip-${Me}`]=de)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[H,Me]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let de=n[`--persona-components-messageActions-${H}`];de&&(n[`--persona-message-action-${Me}`]=de)}kt(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let C=n["--persona-components-introCard-background"],E=n["--persona-components-introCard-shadow"],A=(!C||C==="transparent"||C==="none")&&(!E||E==="none"),I=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=A&&I==="1.5rem"?"1.5rem 0":I,kt(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),kt(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let L=n["--persona-components-markdown-heading-h1-fontSize"];L&&(n["--persona-md-h1-size"]=L);let k=n["--persona-components-markdown-heading-h1-fontWeight"];k&&(n["--persona-md-h1-weight"]=k);let R=n["--persona-components-markdown-heading-h2-fontSize"];R&&(n["--persona-md-h2-size"]=R);let B=n["--persona-components-markdown-heading-h2-fontWeight"];B&&(n["--persona-md-h2-weight"]=B);let O=n["--persona-components-markdown-prose-fontFamily"];O&&O!=="inherit"&&(n["--persona-md-prose-font-family"]=O),kt(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),kt(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),kt(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),kt(n,[["md-hr-color","components-markdown-hr-color","divider"]]),kt(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let V=[["container","surface"],["surface","surface"],["border","border"]];for(let[H,Me]of V){let de=n[`--persona-components-collapsibleWidget-${H}`]??n[`--persona-${Me}`];de!==void 0&&(n[`--persona-cw-${H}`]=de,n[`--cw-${H}`]=de)}kt(n,[["message-border","components-message-border","border"]]),kt(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let J=t.components,_=J?.iconButton;_&&(_.background&&(n["--persona-icon-btn-bg"]=_.background),_.border&&(n["--persona-icon-btn-border"]=_.border),_.color&&(n["--persona-icon-btn-color"]=_.color),_.padding&&(n["--persona-icon-btn-padding"]=_.padding),_.borderRadius&&(n["--persona-icon-btn-radius"]=_.borderRadius),_.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=_.hoverBackground),_.hoverColor&&(n["--persona-icon-btn-hover-color"]=_.hoverColor),_.activeBackground&&(n["--persona-icon-btn-active-bg"]=_.activeBackground),_.activeBorder&&(n["--persona-icon-btn-active-border"]=_.activeBorder));let Q=J?.labelButton;Q&&(Q.background&&(n["--persona-label-btn-bg"]=Q.background),Q.border&&(n["--persona-label-btn-border"]=Q.border),Q.color&&(n["--persona-label-btn-color"]=Q.color),Q.padding&&(n["--persona-label-btn-padding"]=Q.padding),Q.borderRadius&&(n["--persona-label-btn-radius"]=Q.borderRadius),Q.hoverBackground&&(n["--persona-label-btn-hover-bg"]=Q.hoverBackground),Q.fontSize&&(n["--persona-label-btn-font-size"]=Q.fontSize),Q.gap&&(n["--persona-label-btn-gap"]=Q.gap));let G=J?.toggleGroup;G&&(G.gap&&(n["--persona-toggle-group-gap"]=G.gap),G.borderRadius&&(n["--persona-toggle-group-radius"]=G.borderRadius));let w=J?.artifact;if(w?.toolbar){let H=w.toolbar;H.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=H.iconHoverColor),H.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=H.iconHoverBackground),H.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=H.iconPadding),H.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=H.iconBorderRadius),H.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=H.iconBorder),H.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ep(H.toggleGroupGap)),H.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=H.toggleBorderRadius),H.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=ep(H.toggleGroupPadding)),H.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=H.toggleGroupBorder),H.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=H.toggleGroupBorderRadius),H.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Pt(t,H.toggleGroupBackground)??H.toggleGroupBackground),H.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=H.copyBackground),H.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=H.copyBorder),H.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=H.copyColor),H.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ep(H.copyBorderRadius)),H.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=H.copyPadding),H.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=H.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??H.copyMenuBackground),H.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=H.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??H.copyMenuBorder),H.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=H.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??H.copyMenuShadow),H.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=H.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??H.copyMenuBorderRadius),H.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=H.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??H.copyMenuItemHoverBackground),H.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=H.iconBackground),H.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=H.toolbarBorder)}if(w?.tab){let H=w.tab;H.background&&(n["--persona-artifact-tab-bg"]=H.background),H.activeBackground&&(n["--persona-artifact-tab-active-bg"]=H.activeBackground),H.activeBorder&&(n["--persona-artifact-tab-active-border"]=H.activeBorder),H.borderRadius&&(n["--persona-artifact-tab-radius"]=H.borderRadius),H.textColor&&(n["--persona-artifact-tab-color"]=H.textColor),H.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=H.hoverBackground),H.listBackground&&(n["--persona-artifact-tab-list-bg"]=H.listBackground),H.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=H.listBorderColor),H.listPadding&&(n["--persona-artifact-tab-list-padding"]=H.listPadding)}if(w?.pane){let H=w.pane;if(H.toolbarBackground){let Me=Pt(t,H.toolbarBackground)??H.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Me}}if(w?.card){let H=w.card;H.background&&(n["--persona-artifact-card-bg"]=H.background),H.border&&(n["--persona-artifact-card-border"]=H.border),H.borderRadius&&(n["--persona-artifact-card-radius"]=H.borderRadius),H.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=H.hoverBackground),H.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=H.hoverBorderColor)}if(w?.inline){let H=w.inline;H.background&&(n["--persona-artifact-inline-bg"]=Pt(t,H.background)??H.background),H.border&&(n["--persona-artifact-inline-border"]=H.border),H.borderRadius&&(n["--persona-artifact-inline-radius"]=H.borderRadius),H.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Pt(t,H.chromeBackground)??H.chromeBackground),H.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Pt(t,H.chromeBorder)??H.chromeBorder),H.titleColor&&(n["--persona-artifact-inline-title-color"]=Pt(t,H.titleColor)??H.titleColor),H.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Pt(t,H.mutedColor)??H.mutedColor),H.frameHeight&&(n["--persona-artifact-inline-frame-height"]=H.frameHeight)}let v=J?.code;v&&(v.keywordColor&&(n["--persona-code-keyword-color"]=v.keywordColor),v.stringColor&&(n["--persona-code-string-color"]=v.stringColor),v.commentColor&&(n["--persona-code-comment-color"]=v.commentColor),v.numberColor&&(n["--persona-code-number-color"]=v.numberColor),v.tagColor&&(n["--persona-code-tag-color"]=v.tagColor),v.attrColor&&(n["--persona-code-attr-color"]=v.attrColor),v.propertyColor&&(n["--persona-code-property-color"]=v.propertyColor),v.lineNumberColor&&(n["--persona-code-line-number-color"]=v.lineNumberColor),v.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=v.gutterBorderColor),v.background&&(n["--persona-code-bg"]=Pt(t,v.background)??v.background));let T=n["--persona-surface"],x=n["--persona-container"],z=n["--persona-palette-colors-gray-100"]??"#f3f4f6",W=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ee=n["--persona-palette-colors-gray-300"]??"#d1d5db",ne=!x||x===T,he=qw(T??n["--persona-background"]),ve=ne&&he!==void 0&&he<jw,Xe=ve?"rgba(255, 255, 255, 0.08)":z,Je=ve?"rgba(255, 255, 255, 0.12)":W,Wt=ve?"rgba(255, 255, 255, 0.16)":ee,$e=ne?Xe:x,Ce=ne?Je:x;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??$e,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Ce,ne&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??Wt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??$e,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??$e,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??$e,n}var Kw=t=>!!t&&"launcher"in t&&(t.launcher?.sidebarMode===!0||t.launcher?.mountMode==="docked"),Qh=(t,e)=>{if(!e||!Kw(e))return t;let n=e.theme?.components?.panel?.width,o=e.darkTheme?.components?.panel?.width;return(Ei(e)==="dark"?o??n:n)!=null?t:{...t,components:{...t.components,panel:{...t.components.panel,width:Ar(e)==="v5"?"400px":"420px"}}}},Gw={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Mi={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},op=Gw,Yw={...op,colors:{...op.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},Qw=Mi,Xw={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600"}}},components:{...Mi.components,button:{...Mi.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...Mi.components?.eventStream,badge:{...Mi.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},Jw=t=>Ar({future:t})==="v5"?{palette:Yw,components:Xw}:{palette:op,components:Qw},Xh=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},rp=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Zw=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":rp()},Ei=t=>Zw(t),eS=(t,e={})=>ys(t,e),tS=(t,e={})=>{let n=Jw(e.future),o=Sr(n.components,t??{})??{};return ys({...o,palette:{...o.palette,colors:Ar(e)==="v5"?Sr(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:e.future})},ho=t=>{let e=Ei(t),n=Xh(t?.theme),o=El(t)==="circle"?Tl:{...tp.launcher,...t?.future?.v5Defaults?{offset:"1.5rem"}:{}},s=Sr({components:{launcher:o}},n),i=Xh(t?.darkTheme);return Qh(e==="dark"?tS(Sr(s??{},i??{}),{future:t?.future}):eS(s,{future:t?.future}),t)},nS=t=>Yh(t),Ti=(t,e)=>{let n=ho(e),o=nS(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",Ei(e)),t.setAttribute("data-persona-defaults",Ar(e))},Il=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(rp())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(rp());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};import{Activity as fb,Check as hb,Copy as yb}from"lucide";var Ko=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Hl="24px",sp=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",ki=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},Jh=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);import{Idiomorph as oS}from"idiomorph";var Rl=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;oS.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,i){if(s instanceof HTMLElement&&o){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-tool-elapsed"))return i instanceof HTMLElement&&i.getAttribute("data-tool-elapsed")===s.getAttribute("data-tool-elapsed")?!1:void 0;if(s.hasAttribute("data-preserve-animation")){if(i instanceof HTMLElement&&!i.hasAttribute("data-preserve-animation"))return;if(i instanceof HTMLElement&&i.hasAttribute("data-preserve-animation")){let l=s.textContent??"",c=i.textContent??"";if(l!==c)return}return!1}}}}})};var Zh=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var ip={index:-1,draft:""};function ey(t){let{direction:e,history:n,currentValue:o,atStart:s,state:i}=t,l=i.index!==-1;if(n.length===0)return{handled:!1,state:i};if(e==="up"){if(!l&&!s)return{handled:!1,state:i};if(!l){let c=n.length-1;return{handled:!0,value:n[c],state:{index:c,draft:o}}}if(i.index>0){let c=i.index-1;return{handled:!0,value:n[c],state:{index:c,draft:i.draft}}}return{handled:!0,state:i}}if(!l)return{handled:!1,state:i};if(i.index<n.length-1){let c=i.index+1;return{handled:!0,value:n[c],state:{index:c,draft:i.draft}}}return{handled:!0,value:i.draft,state:{index:-1,draft:i.draft}}}function ty(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function ny(){return new Map}function oy(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function ry(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function sy(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:fT,load:rS}=je({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var iy=rS;function ap(t,e=Dt){let n=t.style.position,o=t.style.zIndex,s=t.style.isolation,i=getComputedStyle(t),l=i.position==="static"||i.position==="";return l&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{l&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=s}}var Pi=0,Go=null;function lp(t=document){if(Pi++,Pi===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Go={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,Pi=Math.max(0,Pi-1),Pi===0&&Go)){let n=t.body,o=t.defaultView??window;n.style.overflow=Go.originalOverflow,n.style.position=Go.originalPosition,n.style.top=Go.originalTop,n.style.width=Go.originalWidth,o.scrollTo(0,Go.scrollY),Go=null}}}var Li={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},rt=t=>(t?.launcher?.mountMode??"floating")==="docked",Ii=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Cn=t=>{let e=t?.launcher?.dock,n=xr(t).dockWidth?e?.width:Pt(ho(t),"components.panel.width");return{side:e?.side??Li.side,width:n??Li.width,animate:e?.animate??Li.animate,reveal:e?.reveal??Li.reveal,maxHeight:e?.maxHeight??Li.maxHeight}};import{ArrowRight as sS}from"lucide";var cp=t=>t==="followUp"?"follow-up":t,dp=(t,e=0)=>{if(typeof t=="string"){let s=t.trim();return s?{id:s,label:s,prompt:s,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},ay=new WeakSet,iS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,aS=t=>{iS()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},pp=t=>{let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:u,chipsConfig:p,session:g,getTextarea:y,eventTarget:h,submitPrompt:C}=t,E=o==="followUp",A=e.behavior,I=()=>{if(g.isStreaming())return;let R={suggestion:{...e},surface:o,source:s,behavior:A},B=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:R,bubbles:!0,composed:!0,cancelable:!0}));if(E&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!B)return;for(let V of u)if(V.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let O=y();if(A==="fill"){O.value=e.prompt,O.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),O.focus();return}if(C){C(e.prompt);return}O.value="",g.sendMessage(e.prompt)},L=()=>{let R=P("button",`persona-suggestion persona-suggestion--${i}`);if(R.type="button",R.disabled=l,R.dataset.suggestionId=e.id,R.dataset.emphasis=e.emphasis,R.dataset.behavior=A,i==="chip"&&(p?.fontWeight&&(R.style.fontWeight=p.fontWeight),p?.paddingX&&(R.style.paddingLeft=p.paddingX,R.style.paddingRight=p.paddingX),p?.paddingY&&(R.style.paddingTop=p.paddingY,R.style.paddingBottom=p.paddingY)),e.icon){let O=se(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);O&&(O.classList.add("persona-suggestion__icon"),e.iconColor&&(O.style.color=e.iconColor),R.appendChild(O))}let B=P("span","persona-suggestion__copy");if(B.appendChild(Y("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&B.appendChild(Y("span",{className:"persona-suggestion__description",text:e.description})),R.appendChild(B),i!=="chip"){let O=yt(sS,16,"currentColor",1.8);O&&(O.classList.add("persona-suggestion__arrow"),R.appendChild(O))}return R.addEventListener("click",I),R},k=null;for(let R of u)if(R.renderSuggestion&&(k=R.renderSuggestion({suggestion:{...e},index:n,surface:o,source:s,variant:i,streaming:l,config:c,defaultRenderer:L,select:I}),k))break;return k??=L(),k.dataset.suggestionId||=e.id,k.dataset.behavior||=A,k.dataset.emphasis||=e.emphasis,k instanceof HTMLButtonElement||k.setAttribute("aria-disabled",l?"true":"false"),k},Hi=t=>{let e=[],n=[],o=null,s=null,i=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},l=()=>{if(s=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){i();return}let g=Math.max(0,t.scrollWidth-t.clientWidth);if(g<=1){i();return}let y=getComputedStyle(t).direction==="rtl",h=Math.min(g,Math.max(0,Math.abs(t.scrollLeft))),C=4,E=h<=C,A=h>=g-C,I=y?!A:!E,L=y?!E:!A;t.toggleAttribute("data-scroll-left",I),t.toggleAttribute("data-scroll-right",L)},c=()=>{if(s!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&l();return}s=requestAnimationFrame(l)};t.addEventListener("scroll",c,{passive:!0});let u=typeof ResizeObserver=="function"?new ResizeObserver(c):null;return u?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",c),u?.disconnect(),s!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(s),s=null},render:(g,y,h,C,E,A)=>{t.replaceChildren(),e.length=0,n.length=0;let I=A?.source??"config",L=A?.surface??(I==="config"?"starter":"followUp"),k=L==="followUp",R=A?.variant??"chip",B=A?.behavior??"send",O=A?.overflow??"wrap",V=A?.config??{},J=A?.plugins??[],_=typeof A?.maxItems=="number"?Math.max(0,Math.floor(A.maxItems)):void 0,Q=k?"followUps":"starters";!ay.has(V)&&V.debug===!0&&R!=="chip"&&V.suggestions?.[Q]?.overflow!==void 0&&(ay.add(V),console.info(`[persona] suggestions.${Q}.overflow applies to the "chip" variant only; the "${R}" variant manages its own stacking.`));let G=W=>W.map(dp).filter(ee=>ee!==null).map(ee=>({...ee,behavior:ee.behavior??B})),w=G(g??[]);J.forEach(W=>{W.transformSuggestions&&(w=G(W.transformSuggestions({suggestions:w.map(ee=>({...ee})),surface:L,source:I,config:V})))});let v=_===void 0?w:w.slice(0,_);if(!v.length){t.hidden=!0,o=null,i();return}if(!k&&(C??y.getMessages()).some(ee=>ee.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=cp(L),t.dataset.variant=R,t.dataset.overflow=O;let T=document.createDocumentFragment(),x=y.isStreaming();v.forEach((W,ee)=>{let ne=pp({item:W,index:ee,surface:L,source:I,variant:R,streaming:x,config:V,plugins:J,chipsConfig:E,session:y,getTextarea:()=>h,eventTarget:t,submitPrompt:A?.submitPrompt});T.appendChild(ne),n.push(ne),[...ne instanceof HTMLButtonElement?[ne]:[],...Array.from(ne.querySelectorAll("button"))].forEach(ve=>{e.includes(ve)||(ve.disabled=x,e.push(ve))})}),t.appendChild(T),l(),c();let z=JSON.stringify({normalized:v,surface:L,variant:R,source:I});z!==o&&(o=z,aS(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:v.map(W=>({...W})),surface:L,source:I,variant:R},bubbles:!0,composed:!0})),k&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:v.map(W=>W.prompt)},bubbles:!0,composed:!0})))}}};var ln={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var lS="persona-header-control",cS="persona-header-control--glyph",dS="persona-header-control--sparse",pS=20,uS={x:[1.4,1.05]},ly="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",gS="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wl=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=uS[e]??[1,1.5],c=!o;t.classList.toggle(cS,c),t.classList.toggle(dS,c&&i!==1);let u=parseFloat(o??"")||pS,p=se(e,`${Math.round(u*i)}px`,"currentColor",l);p?(p.style.display="block",c||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((l/1.5).toFixed(4))})`),t.replaceChildren(p)):s&&(t.textContent=s)},bs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=ly,size:c,iconSize:u,color:p,backgroundColor:g,borderWidth:y,borderColor:h,borderRadius:C,paddingX:E,paddingY:A,hidden:I,extraClassName:L,attrs:k}=t,R=P("div",l),B=!!(y||h),O=Y("button",{className:ss(lS,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"persona-bg-transparent hover:persona-bg-gray-100",!B&&"persona-border-none",!C&&"persona-rounded-full",L),attrs:{type:"button","aria-label":e,...k},style:{width:c,height:c,minWidth:c,minHeight:c,display:I?"none":void 0,color:p||Vt.actionIconColor,backgroundColor:g,border:B?`${y||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:C,paddingLeft:E,paddingRight:E,paddingTop:A,paddingBottom:A}});return s?Wl(O,s,{iconSize:u,iconText:i}):i&&(O.textContent=i),R.appendChild(O),vn({anchor:O,trigger:R,text:()=>O.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:O,wrapper:R}},vs=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=ly,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",u=l.closeButtonShowTooltip??!0,{button:p,wrapper:g}=bs({ariaLabel:c,tooltip:u,iconName:l.closeButtonIconName??"x",iconText:l.closeButtonIconText??"\xD7",wrapperClassName:o,size:s??l.closeButtonSize,iconSize:i,color:l.closeButtonColor,backgroundColor:l.closeButtonBackgroundColor,borderWidth:l.closeButtonBorderWidth,borderColor:l.closeButtonBorderColor,borderRadius:l.closeButtonBorderRadius,paddingX:l.closeButtonPaddingX,paddingY:l.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:g}},Cs=(t,e={})=>{let{wrapperClassName:n=gS,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",u=l.showTooltip??!0,{button:p,wrapper:g}=bs({ariaLabel:c,tooltip:u,iconName:l.iconName??"refresh-cw",wrapperClassName:n,size:o??l.size,iconSize:s,color:l.iconColor,backgroundColor:l.backgroundColor,borderWidth:l.borderWidth,borderColor:l.borderColor,borderRadius:l.borderRadius,paddingX:l.paddingX,paddingY:l.paddingY});return{button:p,wrapper:g}};var Vt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},up={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},mS={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},kr=t=>{let{config:e,showClose:n=!0}=t,o=Y("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:Vt.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),s=e?.launcher??{},i=s.headerIconSize??$a,l=s.closeButtonPlacement??"inline",c=s.headerIconHidden??!1,u=s.headerIconName,p=Y("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:i,width:i,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!c)if(u){let O=parseFloat(i)||24,V=se(u,O*.6,"currentColor",1);V?(V.style.width=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,V.style.height=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(V)):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let O=P("img");O.src=e.launcher.iconUrl,O.alt="",O.className="persona-rounded-xl persona-object-cover",O.style.height=i,O.style.width=i,p.replaceChildren(O)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let g=P("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),y=Y("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Vt.titleColor,...up}}),h=Y("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Vt.subtitleColor,...mS}});g.append(y,h),c?o.append(g):o.append(p,g);let C=s.clearChat??{},E=C.enabled??!0,A=C.placement??"inline",I=null,L=null;if(E){let V=Cs(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});I=V.button,L=V.wrapper,A==="top-right"&&(L.style.right="48px"),A==="inline"&&o.appendChild(L)}let k=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":E&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:B}=vs(e,{showClose:n,wrapperClassName:k});return l!=="top-right"&&o.appendChild(B),{header:o,iconHolder:p,headerTitle:y,headerSubtitle:h,closeButton:R,closeButtonWrapper:B,clearChatButton:I,clearChatButtonWrapper:L}},Ri=(t,e,n)=>{let o=n?.launcher??{},s=o.closeButtonPlacement??"inline",i=o.clearChat?.placement??"inline";t.appendChild(e.header),s==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&i==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};var fS=t=>{let e=kr({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return e};function hS(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=bs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?xf(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(s.setAttribute("data-persona-header-action",o.id),o.shortcut){let l=Af(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=Wf({items:o.menuItems,onSelect:c=>n?.(c),anchor:i,position:"bottom-right"});i.appendChild(l.element),s.addEventListener("click",c=>{c.stopPropagation(),l.toggle()})}else s.addEventListener("click",()=>n?.(o.id));t.appendChild(i)}}var yS=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:i}=t,l=e?.launcher??{},c=P("div","persona-flex persona-items-center persona-justify-between");c.setAttribute("data-persona-theme-zone","header"),c.style.minHeight=Vt.minHeight,c.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",c.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",c.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",c.style.boxShadow="var(--persona-header-shadow, none)",c.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let u=s?.titleMenu,p,g;if(u){let B=Df({label:l.title??"Chat Assistant",menuItems:u.menuItems,onSelect:O=>{let V=_=>{_===!1&&B.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:O}}))},J=u.onSelect(O);J instanceof Promise?J.then(V,()=>{}):V(J)},hover:u.hover,className:""});p=B.element,p.style.color=Vt.titleColor,g=p.querySelector(".persona-combo-btn-label")??p}else{if(p=P("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=P("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=Vt.titleColor,Object.assign(g.style,up),g.textContent=l.title??"Chat Assistant",p.appendChild(g),s?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let O=s.onTitleClick;p.addEventListener("click",V=>{V.target.closest("button")||O()}),p.addEventListener("keydown",V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),O())})}let B=s?.titleRowHover;B&&(p.style.borderRadius=B.borderRadius??"10px",p.style.padding=B.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=B.background??"",p.style.borderColor=B.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}c.appendChild(p);let y="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:C}=vs(e,{showClose:n,wrapperClassName:y});o&&h.addEventListener("click",o);let E=P("div","persona-flex persona-items-center persona-gap-1");u||hS(E,s?.trailingActions,s?.onAction??i);let A=l.clearChat??{},I=null,L=null;if(A.enabled??!0){let B=A.placement??"inline",O=Cs(e,{wrapperClassName:B==="top-right"?"persona-absolute persona-top-4 persona-z-50":y});I=O.button,L=O.wrapper,B==="top-right"?L.style.right="48px":E.appendChild(L)}E.appendChild(C),c.appendChild(E);let k=P("div");k.style.display="none";let R=P("span");return R.style.display="none",{header:c,iconHolder:k,headerTitle:g,headerSubtitle:R,closeButton:h,closeButtonWrapper:C,clearChatButton:I,clearChatButtonWrapper:L}},cy={default:fS,minimal:yS},bS=t=>cy[t]??cy.default,Bl=(t,e,n)=>{if(e?.render){let l=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),c=P("div");c.style.display="none";let u=P("span"),p=P("span"),g=P("button");g.style.display="none";let y=P("div");return y.style.display="none",{header:l,iconHolder:c,headerTitle:u,headerSubtitle:p,closeButton:g,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=bS(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(i.iconHolder.style.display="none"),e.showTitle===!1&&(i.headerTitle.style.display="none"),e.showSubtitle===!1&&(i.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(i.closeButton.style.display="none"),e.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display="none")),i};var Wi=t=>{let{config:e}=t,n=Y("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=il(),s=Y("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:i,attachAutoResize:l}=nl(e);l();let c=ol(e),u=gs(e),p=rl(e),g=sl(e),y=Y("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(y),p&&(p.previewsContainer.style.gap="8px",y.append(p.previewsContainer),s.append(p.input)),s.append(i);let h=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),C=Y("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),E=Y("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&C.append(p.wrapper),u&&E.append(u.wrapper),E.append(c.wrapper),h.append(C,E),s.append(h),s.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&i.focus()}),e?.statusIndicator?.mode==="transient"?n.append(o,g,s):n.append(o,s,g),{footer:n,suggestions:o,composerForm:s,header:y,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:g,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:h,leftActions:C,rightActions:E,setSendButtonMode:c.setMode}};import{ChevronUp as vS,MessageSquare as CS}from"lucide";var dy=()=>{let t=Y("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=P("span","persona-pill-peek__icon"),n=yt(CS,16,"currentColor",1.5);n&&e.appendChild(n);let o=P("span","persona-pill-peek__text"),s=P("span","persona-pill-peek__caret"),i=yt(vS,16,"currentColor",1.5);return i&&s.appendChild(i),t.append(e,o,s),{root:t,textNode:o}},Dl=t=>{let{config:e}=t,n=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=il(),s=sl(e);s.style.display="none";let{textarea:i,attachAutoResize:l}=nl(e,{defaultMaxLines:5});l();let c=ol(e),u=gs(e),p=rl(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let g=Y("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),y=Y("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&y.append(p.wrapper);let h=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});u&&h.append(u.wrapper),h.append(c.wrapper),g.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&i.focus()}),p&&g.append(p.input),g.append(y,i,h);let C=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(C),p&&C.append(p.previewsContainer),n.append(o,g,s);let E=g;return{footer:n,suggestions:o,composerForm:g,header:C,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:s,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:E,leftActions:y,rightActions:h,setSendButtonMode:c.setMode}};var wS=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},SS=(t,e)=>{if(!t)return null;let n=wS(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},xS=(t,e)=>{let n=P("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},AS=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},mp=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},fp=320,fy=320,MS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),ES=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),TS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),kS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),PS=t=>{if(!t||t.length===0)return null;let e=Y("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Y("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=P("span","persona-mention-chip-icon"),i=se(n.iconName??"at-sign",13,"currentColor",2);i&&s.appendChild(i),o.appendChild(s),o.appendChild(Y("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},LS=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Id(o.ref,{readonly:!0,render:e}))}return n},py="\uE000",uy="\uE001",IS=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=h=>`${py}${s}:${h}${uy}`,l=e.map((h,C)=>h.kind==="text"?h.text:i(C)).join(""),c=n(l);if(!e.every((h,C)=>h.kind==="text"||c.includes(i(C)))){t.replaceChildren(LS(e,o));return}t.innerHTML=c;let p=new RegExp(`${py}${s}:(\\d+)${uy}`),g=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),y=[];for(let h=g.nextNode();h;h=g.nextNode())y.push(h);for(let h of y){let C=h;for(let E=p.exec(C.data);E;E=p.exec(C.data)){let A=e[Number(E[1])],I=C.splitText(E.index);I.data=I.data.slice(E[0].length),A?.kind==="mention"&&I.parentNode?.insertBefore(Id(A.ref,{readonly:!0,render:o}),I),C=I}}},HS=(t,e,n)=>{if(t.length===0)return null;try{let o=P("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let s=0,i=!1,l=()=>{i||(i=!0,o.remove(),n?.())};return t.forEach((c,u)=>{let p=P("img");p.alt=c.alt?.trim()||`Attached image ${u+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${fp}px`,p.style.maxHeight=`${fy}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;s+=1,p.addEventListener("error",()=>{g||(g=!0,s=Math.max(0,s-1),p.remove(),s===0&&l())}),p.addEventListener("load",()=>{g=!0}),AS(c.image)?(p.src=c.image,o.appendChild(p)):(g=!0,s=Math.max(0,s-1),p.remove())}),s===0?(l(),null):o}catch{return n?.(),null}},RS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!mp(o.audio))return;let s=P("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${fp}px`,e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},WS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!mp(o.video))return;let s=P("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${fp}px`,s.style.maxHeight=`${fy}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},BS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!mp(o.data))return;let s=P("a");s.href=o.data,s.download=o.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Bi=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(s),t},DS=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Bi};if(e){let s=e(o);if(s!==null)return s}return Bi()},OS=(t,e)=>{let n=P("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let s=P("img");s.src=o,s.alt=e==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},gy=(t,e,n="div")=>{let o=P(n,"persona-text-xs persona-text-persona-muted"),s=new Date(t.createdAt);return e.format?o.textContent=e.format(s):o.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Di=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},my={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},_S=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=my[n??"bubble"]??my.bubble;o.padding&&(t.style.padding=`var(--persona-message-${s}-padding, ${i.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${s}-font-size, ${i.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${s}-line-height, ${i.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${s}-font-family, inherit)`)},Ol="custom:",FS=t=>`${Ol}${t}`,hy=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),NS=(t,e,n,o)=>{let s=e.showCopy??!0,i=e.showUpvote??!1,l=e.showDownvote??!1,c=e.showReadAloud??!1,u=(e.showRegenerate??!1)&&o?.canRegenerate===!0,p=(e.showEdit??!1)&&o?.canEdit===!0,g=(e.showQuote??!1)&&o?.canQuote!==!1,y=hy(e,t.role);if(!s&&!i&&!l&&!c&&!u&&!p&&!g&&y.length===0){let R=P("div");return R.style.display="none",R.id=`actions-${t.id}`,R.setAttribute("data-actions-for",t.id),R}let h=e.visibility??"hover",C=e.align??"right",E=e.layout??"pill-inside",A={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[C],I={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[E],L=P("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${A} ${I} ${h==="hover"?"persona-message-actions-hover":""}`);L.id=`actions-${t.id}`,L.setAttribute("data-actions-for",t.id);let k=(R,B,O)=>{let V=Bf({icon:R,label:B,size:14,className:"persona-message-action-btn",chromeless:!0});return V.setAttribute("data-action",O),V};s&&L.appendChild(k("copy","Copy message","copy")),c&&L.appendChild(k("volume-2","Read aloud","read-aloud")),i&&L.appendChild(k("thumbs-up","Upvote","upvote")),l&&L.appendChild(k("thumbs-down","Downvote","downvote")),u&&L.appendChild(k("refresh-cw","Regenerate response","regenerate")),p&&L.appendChild(k("pencil","Edit message","edit")),g&&L.appendChild(k("quote","Quote message","quote"));for(let R of y)L.appendChild(k(R.iconName??"ellipsis",R.label,FS(R.id)));return L},hp=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",u=l.avatar,p=l.timestamp,g=u?.show??!1,y=p?.show??!1,h=u?.position??"left",C=p?.position??"below",E=Di(t.role,c),A=P("div",E.join(" "));A.id=`bubble-${t.id}`,A.setAttribute("data-message-id",t.id),A.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let I=np(i?.widgetConfig?.future).components.message,L=i?.widgetConfig?.theme?.components?.message;_S(A,t.role,c,t.role==="user"?{...I.user,...L?.user,...i?.widgetConfig?.darkTheme?.components?.message?.user}:{...I.assistant,...L?.assistant,...i?.widgetConfig?.darkTheme?.components?.message?.assistant}),c==="flat"?(A.style.backgroundColor="transparent",A.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=MS(t),R=t.content?.trim()??"",O=k.length>0&&R===Za,V=cl(i?.widgetConfig?.features?.streamAnimation),J=i?.widgetConfig?.features?.streamAnimation?.plugins,_=t.role==="assistant"&&V.type!=="none"?mi(V.type,J):null,Q=t.role==="assistant"&&_?.isAnimating?.(t)===!0,G=t.role==="assistant"&&_!==null&&(!!t.streaming||Q);G&&_?.bubbleClass&&A.classList.add(_.bubbleClass);let w=document.createElement("div");w.classList.add("persona-message-content"),t.streaming&&w.classList.add("persona-content-streaming"),G&&_&&(_.containerClass&&w.classList.add(_.containerClass),w.style.setProperty("--persona-stream-step",`${V.speed}ms`),w.style.setProperty("--persona-stream-duration",`${V.duration}ms`));let v=G?dl(t.content??"",V.buffer,_,t,!!t.streaming):t.content??"",T=()=>{let Ce=e({text:v,message:t,streaming:!!t.streaming,raw:t.rawContent});return G&&_?.wrap==="char"?fi(Ce,"char",t.id,{skipTags:_.skipTags}):G&&_?.wrap==="word"?fi(Ce,"word",t.id,{skipTags:_.skipTags}):Ce},x=null;if(O?(x=document.createElement("div"),x.innerHTML=T(),x.style.display="none",w.appendChild(x)):t.contentSegments?.length?IS(w,t.contentSegments,Ce=>e({text:Ce,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):w.innerHTML=T(),G&&_?.useCaret&&!O&&R){let Ce=pl(),H=w.querySelectorAll(".persona-stream-char, .persona-stream-word"),Me=H[H.length-1];if(Me?.parentNode)Me.parentNode.insertBefore(Ce,Me.nextSibling);else{let de=w.lastElementChild;de?de.appendChild(Ce):w.appendChild(Ce)}}if(y&&C==="inline"&&t.createdAt){let Ce=gy(t,p,"span");Ce.classList.add("persona-timestamp-inline");let H=w.lastElementChild;H?H.appendChild(Ce):w.appendChild(Ce)}if(k.length>0){let Ce=HS(k,!O&&!!R,()=>{O&&x&&(x.style.display="")});Ce?A.appendChild(Ce):O&&x&&(x.style.display="")}let z=ES(t);if(z.length>0){let Ce=RS(z);Ce&&A.appendChild(Ce)}let W=TS(t);if(W.length>0){let Ce=WS(W);Ce&&A.appendChild(Ce)}let ee=kS(t);if(ee.length>0){let Ce=BS(ee);Ce&&A.appendChild(Ce)}let ne=t.contentSegments?.length?null:PS(t.contextMentions);if(ne&&A.appendChild(ne),A.appendChild(w),y&&C==="below"&&t.createdAt){let Ce=gy(t,p);Ce.classList.add("persona-mt-1"),A.appendChild(Ce)}let he=t.role==="assistant"?SS(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Ce=!!(v&&v.trim()),H=V.placeholder==="skeleton",Me=H&&V.buffer==="line"&&Ce;if(Ce)Me&&A.appendChild(hi());else if(H)A.appendChild(hi());else{let de=DS("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);de&&A.appendChild(de)}}he&&t.stopReason&&!t.streaming&&(R||(w.style.display="none"),A.appendChild(xS(t.stopReason,he)));let ve=t.role==="assistant"&&!t.streaming&&!t.voiceCaption&&t.content&&t.content.trim()&&o?.enabled!==!1,Xe=i?.actionEligibility,Je=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Xe?.canEdit===!0||o?.showQuote===!0&&Xe?.canQuote===!0||hy(o,"user").length>0);if((ve||Je)&&o){let Ce=NS(t,Je?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,Xe);A.appendChild(Ce)}if(!g||t.role==="system")return A;let Wt=P("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),$e=OS(u,t.role);return h==="right"||h==="left"&&t.role==="user"?Wt.append(A,$e):Wt.append($e,A),Wt};var VS=40,$S=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=se(e.name,VS);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(Y("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(Y("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},yy=(t,e,n={})=>{let o=Y("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let s=P("p","persona-welcome-kicker");s.hidden=!0;let i=P("h2","persona-welcome-title"),l=P("p","persona-welcome-subtitle"),c=Y("div",{className:"persona-welcome-head-text"},s,i),u=Y("div",{className:"persona-welcome-title-row"},o,c);return{host:Y("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},u,l,e),iconHolder:o,kicker:s,title:i,subtitle:l,starterSuggestions:e}},ws=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},Fl=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",$S(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-layout",e.layout??"top"),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},zS="data-persona-welcome-plugin",by="data-persona-welcome-overlay",_l="persona-welcome-overlay-active",yp=new WeakMap,bp=(t,e,n)=>{n.setAttribute(zS,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(by,""),t.classList.contains(_l)||(yp.set(t,t.scrollTop),t.classList.add(_l),t.scrollTop=0)},vp=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(by),t.classList.contains(_l)&&(t.classList.remove(_l),t.scrollTop=yp.get(t)??t.scrollTop,yp.delete(t))},vy=()=>{let t=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},Nl=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",s=Y("div",{className:Di("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});t.appendChild(Y("div",{className:"persona-flex"},s)),t.hidden=!1},Cy=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,wy=(t,e)=>{if(Cy()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,s=0,i=0,l=0;if(o){let E=getComputedStyle(o);s=parseFloat(E.rowGap)||0;let A=t.previousElementSibling,I=t.nextElementSibling,k=o.getBoundingClientRect().top+(parseFloat(E.borderTopWidth)||0)+(parseFloat(E.paddingTop)||0)-o.scrollTop;i=Math.max(0,A?n.top-A.getBoundingClientRect().bottom-s:n.top-k),l=Math.max(0,I?I.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let u=getComputedStyle(t),p=parseFloat(u.paddingTop)||0,g=parseFloat(u.paddingBottom)||0,y=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${g}px`,marginTop:`${i}px`,marginBottom:`${l}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-s}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,C=()=>{h||(h=!0,t.style.overflow=c,e(y))};return y.finished.then(C).catch(C),y},Sy=(t,e,n,o=260)=>{if(e<=1||Cy()||typeof t.animate!="function"||!t.isConnected)return null;let s=n==="drop"?-e:e;return t.animate([{transform:`translateY(${s}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var US="Hello \u{1F44B}",qS="I can answer questions and help you get things done here.",xy=new WeakSet,$t=(t,e)=>!!t&&t[e]!==void 0,jS=(t,e)=>{!t||t.debug!==!0||!e.length||xy.has(t)||(xy.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Vl=(t,e=t?.launcher?.fullHeight===!0&&!t.launcher.sidebarMode&&t.launcher.mountMode!=="docked")=>{let n=t?.welcome,o=t?.copy,s=t?.future?.v5Defaults===!0,i=n?.layout??(s?"centered":"top"),l=$t(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",c=l==="hero"&&!s&&n?.layout===void 0?"on-first-message":$t(n,"dismiss")?n.dismiss:s||l==="hero"?"on-first-message":"never",u=[];$t(n,"title")&&$t(o,"welcomeTitle")&&u.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),$t(n,"subtitle")&&$t(o,"welcomeSubtitle")&&u.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),$t(n,"variant")&&$t(o,"showWelcomeCard")&&u.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),l==="hero"&&$t(n,"message")&&u.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!s&&n?.layout===void 0&&l==="hero"&&$t(n,"dismiss")&&n.dismiss!=="on-first-message"&&u.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(i==="centered"&&e?"center":"bottom"),g=ki(n?.anchorComposerTop)!==null;return $t(n,"anchorComposerTop")&&!g&&u.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&($t(n,"anchorComposerTop")||$t(n,"composerGap"))&&u.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),jS(t,u),{title:$t(n,"title")?n.title:o?.welcomeTitle??(s?"What can I help with?":US),kicker:n?.kicker??"",subtitle:$t(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(s?"":qS),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:i==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:l,dismiss:c,message:l==="hero"?void 0:n?.message,layout:i,anchor:p,anchorComposerTop:g?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Hl}},Ay=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ss=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var KS="var(--persona-components-panel-maxWidth)",My="var(--persona-components-panel-height)",GS="var(--persona-components-panel-maxHeight)",Pr=t=>{let e=xr(t),n=e.launcherWidth?t?.launcher?.width:e.legacyLauncherWidth?t?.launcherWidth:void 0,o=t?.launcher?.heightOffset??0,s=o===0?`max(200px, ${My})`:`max(200px, calc(${My} - ${o}px))`;return{width:n??Lm,maxWidth:n??KS,height:s,maxHeight:GS}},Ey="16px",wp="10px",Sp="14px",Ty=t=>{let e=t?.launcher?.enabled??!0,n=rt(t);if(Ii(t)){let p=t?.launcher?.composerBar??{},g=P("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Dt);let y=P("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",g.appendChild(y);let h=P("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=p.expandedSize??"anchored",h.style.zIndex=String(t?.launcher?.zIndex??Dt),{wrapper:g,panel:y,pillRoot:h}}if(n){let p=P("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=P("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(g),{wrapper:p,panel:g}}if(!e){let p=P("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=P("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=xr(t),C=y.launcherWidth||y.legacyLauncherWidth||t?.theme?.components?.panel?.width!==void 0?Pr(t).width:"100%";return p.style.width=C,g.style.width="100%",p.appendChild(g),{wrapper:p,panel:g}}let s=t?.launcher??{},i=s.position&&ln[s.position]?ln[s.position]:ln["bottom-right"],l=P("div",`persona-widget-wrapper persona-fixed ${i} persona-transition`);l.style.zIndex=String(t?.launcher?.zIndex??Dt);let c=P("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=Pr(t);return c.style.width=u.width,c.style.maxWidth=u.maxWidth,l.appendChild(c),{wrapper:l,panel:c}},xp=t=>{let e=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":cp(t)}});return e.hidden=!0,e},ky=(t,e)=>{let n=xp("starter"),o=yy(t,n,{flatShadow:rt(t)}),s=Vl(t);Fl(o,s),ws(e,o.host,Ss(s,t?.initialMessages));let i=vy();return Nl(i,s.message,t),{welcome:o,greetingHost:i}},YS=(t,e)=>{let n=P("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:s}=vs(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:Ey,iconSize:wp});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let i=t?.launcher?.clearChat?.enabled??!0,l=null,c=null;if(i){let J=Cs(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Ey,iconSize:Sp});l=J.button,c=J.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let u=Y("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Y("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:g,greetingHost:y}=ky(t,p),{host:h,title:C,subtitle:E}=g,A=g.starterSuggestions,I=P("div","persona-widget-messages persona-flex persona-flex-col");I.style.gap="var(--persona-components-message-gap, 12px)";let L=xp("followUp"),k=Ko(t,!0);k&&(I.style.maxWidth=k,I.style.marginLeft="auto",I.style.marginRight="auto",I.style.width="100%"),p.append(h,y,I,L);let R=Y("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),B=Dl({config:t}),{root:O,textNode:V}=dy();return n.append(u,s,p,R),c&&n.appendChild(c),{container:n,body:p,messagesWrapper:I,starterSuggestions:A,transcriptSuggestions:L,composerOverlay:R,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,welcomeHost:h,welcomeIconHolder:g.iconHolder,greetingHost:y,introKicker:g.kicker,introTitle:C,introSubtitle:E,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:P("span"),headerTitle:P("span"),headerSubtitle:P("span"),header:u,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:O,peekTextNode:V}},Py=(t,e=!0)=>{if(Ii(t))return YS(t,e);let n=Y("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,s=t?.layout?.showHeader!==!1,i=o?Bl(t,o,{showClose:e}):kr({config:t,showClose:e}),l=Y("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:u}=ky(t,l),{host:p,title:g,subtitle:y}=c,h=c.starterSuggestions,C=P("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let E=xp("followUp"),A=Ko(t,!1);A&&(C.style.maxWidth=A,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),l.append(p,u,C,E);let I=Wi({config:t}),L=t?.layout?.showFooter!==!1;s?Ri(n,i,t):(i.header.style.display="none",Ri(n,i,t)),n.append(l);let k=Y("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return L||(I.footer.style.display="none"),n.append(I.footer),n.append(k),{container:n,body:l,messagesWrapper:C,starterSuggestions:h,transcriptSuggestions:E,composerOverlay:k,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,welcomeHost:p,welcomeIconHolder:c.iconHolder,greetingHost:u,introKicker:c.kicker,introTitle:g,introSubtitle:y,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,header:i.header,footer:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode}};var Ap=(t,e)=>{let n=P("button");n.type="button",n.innerHTML=`
|
|
15
15
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
16
16
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|