@runtypelabs/persona 4.32.1 → 4.32.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,n as l,o as u,p as d,r as f,t as p,u as m,v as h,y as g}from"./chunk-CdpVP6LZ.js";import{n as _,r as v,t as y}from"./chunk-BnfM7-qg.js";import{t as b}from"./chunk-CnxIZOzx.js";import{A as x,C as S,D as C,E as ee,F as w,I as T,M as te,N as ne,O as re,P as ie,S as ae,T as oe,_ as se,a as ce,b as le,c as ue,d as de,f as E,g as fe,h as pe,i as me,j as he,k as ge,l as _e,m as ve,n as ye,o as be,r as xe,s as Se,t as Ce,u as we,v as D,w as Te,x as Ee,y as De}from"./chunk-DgZZqy14.js";import{_ as Oe,a as ke,c as Ae,d as je,f as Me,g as Ne,h as Pe,i as Fe,l as Ie,m as Le,o as Re,p as ze,r as Be,s as Ve,u as He,v as Ue}from"./chunk-UWMfWW2a.js";import{i as We,r as O,t as k}from"./chunk-D5BxWOFB.js";import{i as Ge,n as Ke,r as qe}from"./chunk-Bb41bKyp.js";import{a as Je,c as Ye,i as Xe,l as Ze,n as Qe,o as $e,r as et,s as tt,t as nt}from"./chunk-CVMIncEY.js";import{a as rt,i as it,n as at,o as ot,r as st}from"./chunk-BAdIgC5d.js";import{n as ct,r as A}from"./chunk-DDZBCAer.js";import{n as lt,r as ut,t as dt}from"./chunk-BvhTpG6k.js";import{f as ft,r as pt,s as mt,u as ht}from"./chunk-DTGvDx8o.js";import{a as gt,i as _t,r as vt}from"./chunk-xzeTUTrE.js";import{a as yt,c as bt,i as xt,n as St,o as j,r as M,s as N,t as Ct,u as wt}from"./chunk-B_H0l3u2.js";import{m as Tt,n as Et}from"./chunk-mEFmAbxE.js";import{t as Dt}from"./chunk-BkOYJ11B.js";import{t as Ot}from"./chunk-C8560fIY.js";import{a as kt,c as At,d as jt,l as Mt,n as Nt,o as Pt,t as Ft,u as It}from"./chunk-BlTD-Wgn.js";import{t as Lt}from"./chunk-aTmHfQO_.js";import{r as Rt,t as zt}from"./chunk-Bz9jAgba.js";import{c as Bt,f as Vt,l as Ht,m as Ut,n as Wt,r as Gt,s as Kt,t as qt,u as Jt}from"./chunk-BEDTp-dm.js";import{n as Yt,t as Xt}from"./chunk-BAkaTZpd.js";import{n as Zt,t as Qt}from"./chunk-Crczk7D3.js";import{n as $t}from"./chunk-py2YB6PV.js";import{a as en,i as tn,n as nn,o as rn,s as an}from"./chunk-Cy1A8vbF.js";import{a as on,c as sn,i as cn,l as ln,n as un,o as dn,r as fn,s as pn,t as mn,u as hn}from"./chunk-BExOAPZb.js";import{n as gn}from"./chunk-DTDHeUsG.js";import{Activity as _n,ArrowRight as vn,Check as yn,ChevronUp as bn,Copy as xn,File as Sn,FileCode as Cn,FileSpreadsheet as wn,FileText as Tn,MessageSquare as En,X as Dn}from"lucide";import"partial-json";import{Idiomorph as On}from"idiomorph";const kn=e=>{let t=0,n=!1,r=Promise.resolve(),i=()=>{},a,o=e.inert===!0,s=()=>{a?.remove(),a=void 0,e.removeAttribute(`data-persona-preparing`),e.inert=o};return{get ready(){return r},prepare(o,c,l=!1){let u=++t;if(i(),!o.length){if(c(),u!==t)return;s(),r=Promise.resolve();return}!l&&!a&&(a=e.ownerDocument.createElement(`style`),a.textContent=`[data-persona-preparing],[data-persona-preparing] *{visibility:hidden!important}`,e.append(a)),l||(e.setAttribute(`data-persona-preparing`,``),e.inert=!0);let d=new Promise((e,t)=>{i=()=>t(/* @__PURE__ */ Error(`Widget destroyed before ready`))});r=Promise.race([Promise.all(o),d]).then(()=>{if(n)throw Error(`Widget destroyed before ready`);if(u!==t||(c(),u!==t))return r;s()},e=>{if(!n&&u!==t)return r;throw e}),r.catch(()=>{})},destroy(){n=!0,++t,i(),s()}}},An={defaultProvenance:d,suppliedPath:e,hasExplicitThemeStyle:t,getExplicitLegacyStyle:f},{setLoader:jn,load:Mn,provide:Nn,getSync:Pn}=v({fallbackImport:()=>import(`./chunk-B4ecQzeK.js`)}),Fn=Mn,In=Pn,{setLoader:Ln,load:Rn,provide:zn}=v({fallbackImport:()=>import(`./chunk-C3cPmtjr.js`)});let Bn=null;const Vn=()=>Promise.all([Rn(),Fn()]).then(([e,t])=>(Object.assign(t.turnUi,e),Bn=e)),Hn=()=>Bn,{setLoader:Un,load:Wn,provide:Gn,getSync:Kn}=v({fallbackImport:()=>import(`./chunk-C7-m0EmI.js`)}),qn=Wn,Jn=Kn,{setLoader:Yn,load:P,provide:F,getSync:Xn}=v({fallbackImport:()=>import(`./chunk-B3l7TOOv.js`)}),I=P,Zn=Xn,{setLoader:L,load:R,getSync:z,provide:Qn}=v({fallbackImport:()=>import(`./chunk-Ds_twaZn.js`)}),$n=R,er=z;function tr(e){let{items:t,onSelect:n,anchor:r,position:i=`bottom-left`,portal:a,onOpenChange:o}=e,s=k(`div`,`persona-dropdown-menu persona-hidden`);s.setAttribute(`role`,`menu`),s.setAttribute(`data-persona-theme-zone`,`dropdown`),a?(s.style.position=`fixed`,s.style.zIndex=String(qe)):(s.style.position=`absolute`,s.style.top=`100%`,s.style.marginTop=`4px`,i===`bottom-right`?s.style.right=`0`:s.style.left=`0`);for(let e of t){if(e.dividerBefore){let e=document.createElement(`hr`);s.appendChild(e)}let t=document.createElement(`button`);if(t.type=`button`,t.setAttribute(`role`,`menuitem`),t.setAttribute(`data-dropdown-item-id`,e.id),e.destructive&&t.setAttribute(`data-destructive`,``),e.icon){let n=T(e.icon,16,`currentColor`,1.5);n&&t.appendChild(n)}let r=document.createElement(`span`);r.textContent=e.label,t.appendChild(r),t.addEventListener(`click`,t=>{t.stopPropagation(),d(),n(e.id)}),s.appendChild(t)}let c=null;function l(){if(!a)return;let e=r.getBoundingClientRect();s.style.top=`${e.bottom+4}px`,i===`bottom-right`?(s.style.right=`${window.innerWidth-e.right}px`,s.style.left=`auto`):(s.style.left=`${e.left}px`,s.style.right=`auto`)}function u(){let e=s.classList.contains(`persona-hidden`);l(),s.classList.remove(`persona-hidden`),e&&o?.(!0),requestAnimationFrame(()=>{let e=e=>{!s.contains(e.target)&&!r.contains(e.target)&&d()};document.addEventListener(`click`,e,!0),c=()=>document.removeEventListener(`click`,e,!0)})}function d(){let e=!s.classList.contains(`persona-hidden`);s.classList.add(`persona-hidden`),c?.(),c=null,e&&o?.(!1)}function f(){s.classList.contains(`persona-hidden`)?u():d()}function p(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:u,hide:d,toggle:f,destroy:p}}function nr(e){let{icon:t,label:n,size:r,strokeWidth:i,className:a,chromeless:o,onClick:s,aria:c}=e,l=k(`button`,We(!o&&`persona-icon-btn`,a));l.type=`button`,l.setAttribute(`aria-label`,n),l.title=n;let u=T(t,r??16,`currentColor`,i??2);if(u&&l.appendChild(u),s&&l.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))l.setAttribute(e,t);return l}function B(e){let{icon:t,label:n,variant:r=`default`,size:i=`sm`,iconSize:a,className:o,onClick:s,aria:c}=e,l=`persona-label-btn`;r!=="default"&&(l+=` persona-label-btn--`+r),l+=` persona-label-btn--`+i,o&&(l+=` `+o);let u=k(`button`,l);if(u.type=`button`,u.setAttribute(`aria-label`,n),t){let e=T(t,a??14,`currentColor`,2);e&&u.appendChild(e)}let d=k(`span`);if(d.textContent=n,u.appendChild(d),s&&u.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))u.setAttribute(e,t);return u}function rr(e){let{items:t,selectedId:n,onSelect:r,className:i}=e,a=k(`div`,`persona-toggle-group`+(i?` `+i:``));a.setAttribute(`role`,`group`);let o=n,s=[];function c(){for(let e of s)e.btn.setAttribute(`aria-pressed`,e.id===o?`true`:`false`)}for(let e of t){let t;e.icon?t=nr({icon:e.icon,label:e.label,className:e.className,onClick:()=>{o=e.id,c(),r(e.id)}}):(t=k(`button`,`persona-icon-btn`+(e.className?` `+e.className:``)),t.type=`button`,t.setAttribute(`aria-label`,e.label),t.title=e.label,t.textContent=e.label,t.addEventListener(`click`,()=>{o=e.id,c(),r(e.id)})),t.setAttribute(`aria-pressed`,e.id===o?`true`:`false`),s.push({id:e.id,btn:t}),a.appendChild(t)}function l(e){o=e,c()}return{element:a,setSelected:l}}function ir(e){let{label:t,icon:n,iconSize:r,iconOnly:i,menuItems:a,onSelect:o,onPrimary:s,position:c=`bottom-left`,portal:l,chevronLabel:u=`More options`,chevronIconSize:d,className:f,primaryClassName:p,chevronClassName:m}=e,h=k(`div`,`persona-split-btn`+(f?` `+f:``)),g={label:t,className:`persona-split-btn-primary`+(p?` `+p:``),onClick:s},_=i&&n?nr({...g,icon:n,size:r??14}):B({...g,icon:n,iconSize:r??14}),v=nr({icon:`chevron-down`,label:u,size:d??14,className:`persona-split-btn-chevron`+(m?` `+m:``),aria:{"aria-haspopup":`true`,"aria-expanded":`false`}});h.append(_,v);let y=null,b=()=>{if(y)return y;let e=(typeof l==`function`?l():l)??void 0;return y=tr({items:a,onSelect:o,anchor:h,position:c,portal:e,onOpenChange:e=>{v.setAttribute(`aria-expanded`,e?`true`:`false`)}}),e||h.appendChild(y.element),y};return h.isConnected?b():requestAnimationFrame(()=>{y||b()}),v.addEventListener(`click`,e=>{e.stopPropagation(),b().toggle()}),{element:h,primaryButton:_,chevronButton:v,openMenu:()=>b().show(),closeMenu:()=>y?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{y?.destroy(),h.remove()}}}function V(e){let{label:t,icon:n=`chevron-down`,menuItems:r,onSelect:i,position:a=`bottom-left`,portal:o,className:s,hover:c}=e,l=k(`div`,`persona-combo-btn`+(s?` `+s:``));l.style.position=`relative`,l.style.display=`inline-flex`,l.style.alignItems=`center`,l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`),l.setAttribute(`aria-haspopup`,`true`),l.setAttribute(`aria-expanded`,`false`),l.setAttribute(`aria-label`,t);let u=k(`span`,`persona-combo-btn-label`);u.textContent=t,l.appendChild(u);let d=T(n,14,`currentColor`,2);d&&(d.style.marginLeft=`4px`,d.style.opacity=`0.6`,l.appendChild(d)),c&&(l.style.borderRadius=c.borderRadius??`10px`,l.style.padding=c.padding??`6px 4px 6px 12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=c.background??``,l.style.borderColor=c.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}));let f=tr({items:r,onSelect:e=>{l.setAttribute(`aria-expanded`,`false`),i(e)},anchor:l,position:a,portal:o});o||l.appendChild(f.element);let p=()=>l.getAttribute(`data-persona-menu-locked`)===`true`;return l.addEventListener(`click`,e=>{if(e.stopPropagation(),p())return;let t=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,t?`false`:`true`),f.toggle()}),l.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),l.click())}),{element:l,setLabel:e=>{u.textContent=e,l.setAttribute(`aria-label`,e)},open:()=>{l.setAttribute(`aria-expanded`,`true`),f.show()},close:()=>{l.setAttribute(`aria-expanded`,`false`),f.hide()},toggle:()=>{let e=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,e?`false`:`true`),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}const ar=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:or,load:sr,provide:cr,getSync:lr}=v({fallbackImport:()=>import(`./chunk-BbXc58OA.js`)});let ur=null;const dr=/* @__PURE__ */ new Set,fr=e=>{if(ur)return ur;ur=e,e.initArtifactsUi({componentRegistry:ze,loadingLabels:Zn(),buttons:{createIconButton:nr,createLabelButton:B,createSplitButton:ir,createToggleGroup:rr}});for(let t of ar)ze.has(t)||ze.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Ne();t?e.__provideMarkdownParsers(t):Ue(()=>{let t=Ne();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader!==_&&e.__setIconsExtraLoader(y);let n=[...dr];dr.clear();for(let e of n)try{e()}catch{}return e},pr=()=>Promise.all([sr(),I()]).then(([e])=>fr(e)),mr=()=>{if(ur)return ur;if(!Zn())return null;let e=lr();return e?fr(e):null},hr=e=>ur?()=>{}:(dr.add(e),()=>{dr.delete(e)}),{setLoader:gr,load:_r,provide:vr,getSync:H}=v({fallbackImport:()=>import(`./chunk-BpjtKnGI.js`)}),yr=_r,br=H,{setLoader:xr,load:Sr,getSync:Cr}=v({fallbackImport:()=>import(`./chunk-CumoXK3u.js`)}),wr=Sr,Tr=Cr;function Er(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||kr(e)!==kr(t)||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Dr(e){return e?.type===`runtype`||e?.type===`custom`}const Or=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function U(e){try{if(e?.type===`custom`&&e.custom){let t=e.custom,n=typeof t==`function`?t():t;return!!n&&typeof n.startListening==`function`}return e?.type===`runtype`&&e.runtype?!0:Or()}catch{return!1}}function kr(e){let t=e.voiceRecognition;return Dr(t?.provider)&&(t?.provider?.type!==`custom`||!!t.dictation?.provider||!t.dictation&&t.completionBehavior!==`review`)}const Ar=e=>{let t=[],n=(e,n,r)=>{e&&!n&&t.push(r())};n(!0,Jn(),qn),n(!0,Ne(),Oe);let r=e.turnActivity?.enabled===!0;n(r,Hn(),Vn);let i=r||e.features?.showToolCalls!==!1||e.features?.showReasoning!==!1;n(i,In(),Fn),n(i||e.loadingLabel?.animation!==`none`&&(!!e.loadingLabel?.animate||(e.loadingIndicator?.variant??(e.future?.v5Defaults?`label`:`dots`))===`label`),Zn(),I),n(e.voiceRecognition?.enabled!==!1,er(),$n),n(e.voiceRecognition?.enabled!==!1&&kr(e),Tr(),wr),n(e.features?.artifacts?.enabled===!0,mr(),pr),n(e.contextMentions?.enabled===!0,br(),yr);let a=w();return a&&t.push(a),t};function jr(){let e=null,t=()=>{e!==null&&cancelAnimationFrame(e),e=null};return{get active(){return e!==null},cancel:t,start(n,r,i,a,o,s=()=>!0){t();let c=n.scrollTop,l=performance.now();if(Math.abs(r()-c)<1){n.scrollTop=r(),a(),o();return}let u=d=>{if(!s()){t(),o();return}let f=Math.min(Math.max(0,(d-l)/i),1);n.scrollTop=c+(r()-c)*(1-(1-f)**3),a(),f<1?e=requestAnimationFrame(u):(e=null,o())};e=requestAnimationFrame(u)}}}function Mr(e,t,n,r,i){let a=jr(),o=!1,s,c=!1,l=e=>{e&&(c=!1),a.active&&(a.cancel(),s=e,c=!!e,i())},u=e=>{[`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`,` `].includes(e.key)&&l(e)},d=e=>{e.deltaY!==0&&l(e)};return e.addEventListener(`wheel`,d,{passive:!0}),e.addEventListener(`touchstart`,l,{passive:!0}),e.addEventListener(`pointerdown`,l,{passive:!0}),t.addEventListener(`keydown`,u),{get active(){return a.active},cancel:l,get interrupted(){return c},interruptedBy:e=>s===e,start(t){if(o)return;a.cancel(),c=!1,s=void 0;let i=(t.features?.scrollToBottom?.scrollBehavior??(t.future?.v5Defaults?`smooth`:`instant`))===`smooth`,l=t.features?.scrollToBottom?.scrollDurationMs??220,u=Number.isFinite(l)&&l>=0?l:220,d=typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches;!i||d||u===0?(e.scrollTop=Xe(e),n(),r()):a.start(e,()=>Xe(e),u,n,r)},destroy(){o=!0,a.cancel(),e.removeEventListener(`wheel`,d),e.removeEventListener(`touchstart`,l),e.removeEventListener(`pointerdown`,l),t.removeEventListener(`keydown`,u)}}}function Nr(e,t,n){let r=k(`button`,`persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer`);r.type=`button`,r.setAttribute(`data-persona-scroll-to-bottom-visible`,`false`),r.disabled=!0,r.tabIndex=-1,r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`data-persona-scroll-to-bottom`,`true`);let i=k(`span`,`persona-flex persona-items-center persona-justify-center`);i.setAttribute(`aria-hidden`,`true`);let a=k(`span`,``),o=k(`span`,``);o.setAttribute(`data-persona-scroll-to-bottom-count`,``),r.appendChild(i),r.appendChild(a),r.appendChild(o);let s={},c={activity:`idle`,visible:!1,hovered:!1,focused:!1,reducedMotion:!1},l,u,d,f=``,p=typeof matchMedia==`function`?matchMedia(`(prefers-reduced-motion: reduce)`):void 0;c.reducedMotion=p?.matches??!1;let m=e=>console.warn(`Persona scroll icon failed`,e),h=()=>({config:s,state:{...c},view:t,signal:d.signal}),g=()=>{d?.abort();try{u?.destroy?.()}catch(e){m(e)}u=void 0,d=void 0,i.innerHTML=``,f=``},_=()=>{if(u?.element)return;let t=s.features?.scrollToBottom,n=c.activity===`generating-below`&&(t?.streamingIndicator??(s.future?.v5Defaults?`dots`:`arrow`))===`dots`,r=n?`dots`:`arrow:${t?.iconName??`arrow-down`}`;if(f!==r){if(f=r,i.innerHTML=``,n){let e=k(`span`,`persona-scroll-to-bottom-dots`);for(let t=0;t<3;t++){let n=k(`span`,``);n.style.animationDelay=`${t*150}ms`,e.appendChild(n)}i.appendChild(e)}else{let n=e(t?.iconName??`arrow-down`,`14px`,`currentColor`,2);n&&i.appendChild(n)}}},v=e=>{let t=s.features?.scrollToBottom?.enabled===!1?void 0:s.features?.scrollToBottom?.renderIcon;if(t!==l){if(g(),l=t,l){d=new AbortController;try{let e=l(h());u=e&&`element`in e?e:e?{element:e}:void 0,u?.element&&i.appendChild(u.element)}catch(e){m(e),g()}}}else if(e&&u?.update)try{u.update(h())}catch(e){m(e),g()}_()},y=e=>Object.keys(e).some(t=>e[t]!==c[t]),b=e=>{let t=y(e);c=e,v(t)},x=()=>b({...c,hovered:!0}),S=()=>b({...c,hovered:!1}),C=()=>b({...c,focused:!0}),ee=()=>b({...c,focused:!1}),w=()=>b({...c,reducedMotion:p?.matches??!1}),T=new AbortController;for(let[e,t]of[[`mouseenter`,x],[`mouseleave`,S],[`focus`,C],[`blur`,ee]])r.addEventListener(e,t,{signal:T.signal});return p?.addEventListener?.(`change`,w),{element:r,update(e,t,i=!1,l=0){let u=s.features?.scrollToBottom,d=e.features?.scrollToBottom,f=s.future?.v5Defaults!==e.future?.v5Defaults||[`enabled`,`iconName`,`label`,`streamingIndicator`,`transition`,`scrollBehavior`,`scrollDurationMs`].some(e=>u?.[e]!==d?.[e]);s=e;let p=s.features?.scrollToBottom;t&&=p?.enabled!==!1;let m=r.getRootNode().activeElement===r;r.setAttribute(`data-persona-scroll-to-bottom-visible`,String(t));let h=p?.enabled===!1?`none`:p?.transition??(s.future?.v5Defaults?`fade`:`none`);r.setAttribute(`data-persona-scroll-to-bottom-transition`,h),i&&t?r.setAttribute(`data-persona-scroll-to-bottom-streaming`,``):r.removeAttribute(`data-persona-scroll-to-bottom-streaming`),r.style.display=!t&&h===`none`?`none`:``,r.disabled=!t,r.tabIndex=t?0:-1,r.setAttribute(`aria-hidden`,String(!t)),!t&&m&&(r.blur(),n&&(n.hasAttribute(`tabindex`)||(n.tabIndex=-1),n.focus({preventScroll:!0})));let g=p?.label??``,_=g||`Jump to latest`;r.setAttribute(`aria-label`,`${_}${l>0?` (${l} new)`:``}${i&&t?` (response streaming below)`:``}`),r.title=g,r.setAttribute(`data-persona-scroll-to-bottom-has-label`,String(!!g)),a.textContent=g,a.style.display=g?``:`none`,o.textContent=l>0?String(l):``,o.style.display=l>0?``:`none`;let b={...c,visible:t,hovered:t&&c.hovered,focused:t&&c.focused,activity:i&&t?`generating-below`:`idle`},x=f||y(b);c=b,v(x)},destroy(){g(),T.abort(),p?.removeEventListener?.(`change`,w),r.remove()}}}function Pr(e){let t=/* @__PURE__ */ new Map,n=(t,n)=>({slot:t,signal:n.abort.signal,config:e.config(),defaultContent:()=>e.defaultContent(t)}),r=(n,r)=>{t.delete(n),r.abort.abort();try{r.result.destroy?.()}catch(e){console.error(`[AgentWidget] Error destroying slot "${n}":`,e)}e.remove(n,r.result.element)};return{update(){let i=e.config().layout?.slots??{};for(let[e,n]of t)i[e]!==n.renderer&&r(e,n);for(let[a,o]of Object.entries(i)){if(!o)continue;let i=t.get(a);try{if(!i){i={renderer:o,abort:new AbortController,result:{element:null}},t.set(a,i);let e=o(n(a,i));i.result=e===null||`nodeType`in e?{element:e}:e}else if(i.result.update){let t=i.result.update(n(a,i));t!==void 0&&t!==i.result.element&&(e.remove(a,i.result.element),i.result.element=t)}i.result.element&&e.mount(a,i.result.element)}catch(e){i&&r(a,i),console.error(`[AgentWidget] Error rendering slot "${a}":`,e)}}},remount(){for(let[n,r]of t)r.result.element&&e.mount(n,r.result.element)},detach(n){for(let r of n){let n=t.get(r);n&&e.remove(r,n.result.element)}},destroy(){for(let[e,n]of t)r(e,n)}}}const Fr=`var(--persona-md-table-scroll-fade, 24px)`,Ir=/* @__PURE__ */ new WeakSet;function Lr(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(`persona-table-scroll`))return;let t=document.createElement(`div`);t.className=`persona-table-scroll`,e.replaceWith(t),t.appendChild(e)})}function Rr(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute(`data-persona-scroll-x`);return}e.setAttribute(`data-persona-scroll-x`,``);let n=getComputedStyle(e).direction===`rtl`?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty(`--persona-fade-l`,n<=1?`0px`:Fr),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:Fr)}function zr(e){Ir.has(e)||(Ir.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&Rr(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(Rr)}const{setLoader:Br,load:Vr,provide:Hr,getSync:Ur}=v({fallbackImport:()=>import(`./chunk-DNdeIFJ6.js`)}),Wr=Vr,Gr=Ur,{setLoader:Kr,load:qr,provide:Jr,getSync:Yr}=v({fallbackImport:()=>import(`./chunk-DM-OJt5q.js`)}),Xr=qr,Zr=Yr,{setLoader:Qr,load:$r}=v({fallbackImport:()=>import(`./chunk-CzLEhoB_.js`)}),ei=$r,{setLoader:ti,load:ni}=v({fallbackImport:()=>import(`./chunk-lA5CJCgK.js`)}),ri=ni;function ii(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function ai(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=ii(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=ii(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}const{setLoader:oi,load:si,provide:ci}=v({fallbackImport:()=>import(`./chunk-C9uOhfk5.js`)}),li=si;var ui=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const di=e=>`reason`in e?e.reason:void 0;function fi(e){switch(e){case`json`:return yt;case`regex-json`:return N;case`xml`:return bt;default:return j}}var pi=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;constructor(e={},t={}){if(this.#f=0,this.#p=/* @__PURE__ */ new Set,this.#m=null,this.clientSession=null,this.#h=null,this.#g=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#_=null,this.#v=!1,this.#y=!1,this.#b=!1,this.#x=null,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#w=null,this.#U=null,this.#G=null,this.#i=e,this.#r=t,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":Dt,...e.headers},this.#n=!!e.debug,this.#a=e.streamParser??fi(e.parserType),this.#o=e.contextProviders??[],this.#s=e.requestMiddleware,this.#c=e.customFetch,this.#l=e.parseSSEEvent,this.#u=e.getHeaders,e.webmcp?.enabled===!0&&(this.#w=this.#E(e.webmcp))}#E(e){return ei().then(t=>{let n=new t.WebMcpBridge(e,{recordToolDisplayTitles:ot,getToolDisplayTitle:st,loadPolyfill:rt});return this.#T!==void 0&&n.setConfirmHandler(this.#T),this.webMcpBridge=n,n}).catch(e=>(this.#w=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#D(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.#i.webmcp?.enabled===!0?(this.#w||=this.#E(this.#i.webmcp),this.#w):Promise.resolve(null)}updateConfig(e){this.#i=e}setHistoryInternals(e){this.#r=e}cancelStreams(){if(this.#f+=1,this.#i.backgroundConversations)for(let e of this.#p)e.cancel().catch(()=>{})}setSSEEventCallback(e){this.#d=e}setWebMcpConfirmHandler(e){this.#T=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}getVoiceClientTools(){if(this.#i.webmcp?.enabled!==!0)return null;let e=()=>this.#D(),t={open:async e=>(await ri()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:at(t)}},onChange:t=>{let n=null,r=!1;return e().then(e=>{e&&!r&&(n=e.watchToolChanges(t))}),()=>{r=!0,n?.()}},execute:async(t,n,r)=>{let i=await e();return i?i.executeVoiceToolCall(t,n,r):{status:`failed`,error:{message:`WebMCP runtime failed to load.`}}}};return t}executeWebMcpToolCall(e,t,n,r){return this.#i.webmcp?.enabled===!0?this.#D().then(i=>i?i.executeToolCall(e,t,n,r):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#d}isClientTokenMode(){return!!this.#i.clientToken}#O(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.#i;if(!n)return{agentId:e,flowId:t};let i=ai(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.#i.agent||this.#O().agentId)}#k(){return this.#i.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#A(e){return`${this.#k()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new ui(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#k()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":Dt,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await li();t=await e.recoverFromUnauthorized(this.#K(),await e.readErrorCode(this.#K(),s),null,!0)}else{if(!s.ok)throw await(await li()).historyErrorFor(this.#K(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#h||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#g===e?null:(this.#g=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#h)return this.#h;let e=this.#h=this.#R().then(t=>this.#h===e?(this.clientSession=t,this.#g=!1,this.resetClientToolsFingerprint(),this.#i.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#h===e&&(this.#h=null)});return e}#j(){return this.#i.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#v}async readVisitorToken(){let e=this.#r.visitorStore;return e?(await e.ready,await e.get()??null):null}#M(){if(!this.#v){this.#I({state:`unavailable`,reason:`history_disabled`}),this.#v=!0,!this.#y&&typeof console<`u`&&(this.#y=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.#r.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#C])e(!1)}}getHistoryIdentityStatus(){return this.#x??this.#N()}subscribeHistoryIdentityStatus(e){return this.#S.add(e),()=>{this.#S.delete(e)}}subscribeHistoryAvailability(e){return this.#C.add(e),this.#v&&e(!1),()=>{this.#C.delete(e)}}#N(){return this.isClientTokenMode()?this.#i.features?.history?.enabled!==!0||this.#v?{state:`unavailable`,reason:`history_disabled`}:this.#P():{state:`unavailable`,reason:`ineligible_mode`}}#P(){let e=this.#x;return e?.state===`browser_only`?e:this.#F()}#F(){return this.#i.features?.history?.scope===`browser`?{state:`browser_only`,reason:`configured_browser_scope`}:this.#i.getIdentityProof?{state:`browser_only`,reason:`proof_unavailable_before_binding`}:{state:`browser_only`,reason:`no_identity_provider`}}#I(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&di(t)===di(e);if(this.#x=e,!n){this.#r.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#S])t(e)}}async#L(e){return new((Zr())??await(Xr())).ClientDispatch(this.#q()).createClientSession(e)}async#R(){return new((Zr())??await(Xr())).ClientDispatch(this.#q()).initializeSession()}async#z(e){let t=this.#i.getStoredSessionId?.()||null,n=this.#i.getStoredConversationId?.()||null,r=await this.#L({storedSessionId:t,identityProof:e}),i=this.#B(r,n,!1);return this.clientSession=i,this.#h=null,this.#g=!1,this.resetClientToolsFingerprint(),i}#B(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.#r.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.#i.setStoredSessionId?.(e.sessionId),r&&(this.#i.setStoredConversationId?.(r),this.#r.setStoredConversationRevision?.(e.conversationRevision??null)),e}#V(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#g=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#j())throw new ui(`history_disabled`,`Visitor history is disabled for this surface`);await this.#r.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new ui(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#L({conversationId:e,identityProof:n});return this.#V(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.#r.historyBootstrapReady;let e=await this.#L({});return this.#V(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#j()&&this.#I(this.#F())}clearClientSession(){this.clientSession=null,this.#h=null,this.#g=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#_=null}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);return new((Zr())??await(Xr())).ClientDispatch(this.#q()).sendFeedback(e)}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#H(e){e?.throwIfAborted();let t=this.#i.identityProvider;if(t===void 0)return;let n=this.#i.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#U;#W(){let e=this;return this.#U??={get config(){return e.#i},headers:this.#t,getHeaders:this.#u,debug:this.#n,clientApiBase:()=>e.#k(),getClientApiUrl:t=>e.#A(t),getWebMcpBridge:()=>e.#D(),sendWithClientToolsDiff:(t,n,r,i)=>e.#J(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#G;#K(){let e=this;return this.#G??={HistoryClientError:ui,get config(){return e.#i},get historyInternals(){return e.#r},get clientSession(){return e.clientSession},clientApiBase:()=>e.#k(),setHistoryIdentityStatus:t=>e.#I(t),browserOnlyStatus:()=>e.#P(),derivedBrowserOnly:()=>e.#F(),reinitWithProof:t=>e.#z(t),isHistoryCapable:()=>e.#j(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await li()).listConversations(this.#K(),e)}async getConversation(e,t){return(await li()).getConversation(this.#K(),e,t)}async finalizeDisplayProjections(e,t){return(await li()).finalizeDisplayProjections(this.#K(),e,t)}async deleteConversation(e,t){return(await li()).deleteConversation(this.#K(),e,t)}async deleteAllConversations(e){return(await li()).deleteAllConversations(this.#K(),e)}async resetVisitor(){return(await li()).resetVisitor(this.#K())}async dispatch(e,t){e.signal?.throwIfAborted(),Wr().catch(()=>{});let n=this.isClientTokenMode(),r=this.isAgentMode(),i=lt();n&&(this.#m=i),t({type:`status`,status:`connecting`});let a=Zr()??await Xr().catch(e=>{let r=e instanceof Error?e:Error(String(e));throw(!n||this.#m===i)&&t({type:`error`,error:r}),r});if(e.signal?.throwIfAborted(),n&&this.#m!==i)throw new DOMException(`Turn superseded`,`AbortError`);let o=new a.ClientDispatch(this.#q());return n?o.dispatchClientToken(e,t,i):r?o.dispatchAgent(e,t):o.dispatchProxy(e,t)}#q(){let e=this;return Object.setPrototypeOf({HistoryClientError:ui,get claimInFlight(){return e.#b},set claimInFlight(t){e.#b=t},get clientToolsFingerprintSessionId(){return e.clientToolsFingerprintSessionId},set clientToolsFingerprintSessionId(t){e.clientToolsFingerprintSessionId=t},get lastSentClientToolsFingerprint(){return e.lastSentClientToolsFingerprint},set lastSentClientToolsFingerprint(t){e.lastSentClientToolsFingerprint=t},get sentNonEmptyClientToolsSessionId(){return e.#_},set sentNonEmptyClientToolsSessionId(t){e.#_=t},get historyInternals(){return e.#r},markHistoryUnavailable:()=>e.#M(),apiUrl:this.#e,contextProviders:this.#o,requestMiddleware:this.#s,customFetch:this.#c,get clientSession(){return e.clientSession},set clientSession(t){e.clientSession=t},isCurrentTurn:t=>e.#m===t,isHistoryCapable:()=>e.#j(),createClientSession:t=>e.#L(t),finishInit:(t,n,r)=>e.#B(t,n,r),resetSessionWarmLatch:()=>{e.#g=!1},resetClientToolsFingerprint:()=>e.resetClientToolsFingerprint(),clearClientSession:()=>e.clearClientSession(),resolveChatIdentityProof:t=>e.#H(t),routing:()=>e.#O(),builtInClientTools:wt,streamResponse:(...t)=>e.#Y(...t)},this.#W())}async processStream(e,t,n,r,i,a,o){t({type:`status`,status:`connected`});try{await this.#Y(e,t,n,r,i,a,o)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t,n){return(await Wr()).resolveApproval(this.#W(),e,t,n)}async#J(e,t,n,r){return new((Zr())??await(Xr())).ClientDispatch(this.#q()).sendWithClientToolsDiff(e,t,n,r)}async resumeFlow(e,t,n){return(await Wr()).resumeFlow(this.#W(),e,t,n)}async#Y(e,t,n,r,i,a,o){let{streamResponse:s}=Gr()??await Wr();return s({config:()=>this.#i,streamGeneration:()=>this.#f,streamReaders:this.#p,createStreamParser:this.#a,parseSSEEvent:this.#l,onSSEEvent:(e,t)=>this.#d?.(e,t)},e,t,n,r,i,a,o)}};const{setLoader:mi,load:hi}=v({fallbackImport:()=>import(`./chunk-CsBLSRM_.js`)}),gi=hi,{setLoader:_i,load:vi,provide:W,getSync:G}=v({fallbackImport:()=>import(`./chunk-BL6v2bXy.js`)}),K=vi,yi=G,bi=e=>typeof e==`object`&&!!e&&!Array.isArray(e),xi=(e,t)=>{let n=/* @__PURE__ */ new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!bi(e))return[];let{toolCallId:r,name:i}=e;if(typeof r!=`string`||!r||typeof i!=`string`||!i||n.has(r))return[];n.add(r);let a=bi(e.arguments)?e.arguments:{},o=e.result??null;return[{id:`voice-tool-${r}`,role:`assistant`,variant:`tool`,content:``,createdAt:t,streaming:!1,toolCall:{id:r,name:i,status:`complete`,args:a,result:o},agentMetadata:{clientToolAnswer:{toolCallId:r,toolName:i,args:a,result:o}}}]})},Si=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function Ci(e){let t=e?.text?.trim()??``;return t?Lt(Si(e),t):``}function wi(e){let t=Ci(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[kt(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
1
+ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,n as l,o as u,p as d,r as f,t as p,u as m,v as h,y as g}from"./chunk-CdpVP6LZ.js";import{n as _,r as v,t as y}from"./chunk-BnfM7-qg.js";import{t as b}from"./chunk-CnxIZOzx.js";import{A as x,C as S,D as C,E as ee,F as w,I as T,M as te,N as ne,O as re,P as ie,S as ae,T as oe,_ as se,a as ce,b as le,c as ue,d as de,f as E,g as fe,h as pe,i as me,j as he,k as ge,l as _e,m as ve,n as ye,o as be,r as xe,s as Se,t as Ce,u as we,v as D,w as Te,x as Ee,y as De}from"./chunk-DgZZqy14.js";import{_ as Oe,a as ke,c as Ae,d as je,f as Me,g as Ne,h as Pe,i as Fe,l as Ie,m as Le,o as Re,p as ze,r as Be,s as Ve,u as He,v as Ue}from"./chunk-UWMfWW2a.js";import{i as We,r as O,t as k}from"./chunk-D5BxWOFB.js";import{i as Ge,n as Ke,r as qe}from"./chunk-Bb41bKyp.js";import{a as Je,c as Ye,i as Xe,l as Ze,n as Qe,o as $e,r as et,s as tt,t as nt}from"./chunk-CVMIncEY.js";import{a as rt,i as it,n as at,o as ot,r as st}from"./chunk-BAdIgC5d.js";import{n as ct,r as A}from"./chunk-DDZBCAer.js";import{n as lt,r as ut,t as dt}from"./chunk-BvhTpG6k.js";import{f as ft,r as pt,s as mt,u as ht}from"./chunk-DTGvDx8o.js";import{a as gt,i as _t,r as vt}from"./chunk-xzeTUTrE.js";import{a as yt,c as bt,i as xt,n as St,o as j,r as M,s as N,t as Ct,u as wt}from"./chunk-B_H0l3u2.js";import{m as Tt,n as Et}from"./chunk-mEFmAbxE.js";import{t as Dt}from"./chunk-BNE40cEG.js";import{t as Ot}from"./chunk-C8560fIY.js";import{a as kt,c as At,d as jt,l as Mt,n as Nt,o as Pt,t as Ft,u as It}from"./chunk-BlTD-Wgn.js";import{t as Lt}from"./chunk-aTmHfQO_.js";import{r as Rt,t as zt}from"./chunk-Bz9jAgba.js";import{c as Bt,f as Vt,l as Ht,m as Ut,n as Wt,r as Gt,s as Kt,t as qt,u as Jt}from"./chunk-BEDTp-dm.js";import{n as Yt,t as Xt}from"./chunk-BAkaTZpd.js";import{n as Zt,t as Qt}from"./chunk-Crczk7D3.js";import{n as $t}from"./chunk-py2YB6PV.js";import{a as en,i as tn,n as nn,o as rn,s as an}from"./chunk-Cy1A8vbF.js";import{a as on,c as sn,i as cn,l as ln,n as un,o as dn,r as fn,s as pn,t as mn,u as hn}from"./chunk-BExOAPZb.js";import{n as gn}from"./chunk-DTDHeUsG.js";import{Activity as _n,ArrowRight as vn,Check as yn,ChevronUp as bn,Copy as xn,File as Sn,FileCode as Cn,FileSpreadsheet as wn,FileText as Tn,MessageSquare as En,X as Dn}from"lucide";import"partial-json";import{Idiomorph as On}from"idiomorph";const kn=e=>{let t=0,n=!1,r=Promise.resolve(),i=()=>{},a,o=e.inert===!0,s=()=>{a?.remove(),a=void 0,e.removeAttribute(`data-persona-preparing`),e.inert=o};return{get ready(){return r},prepare(o,c,l=!1){let u=++t;if(i(),!o.length){if(c(),u!==t)return;s(),r=Promise.resolve();return}!l&&!a&&(a=e.ownerDocument.createElement(`style`),a.textContent=`[data-persona-preparing],[data-persona-preparing] *{visibility:hidden!important}`,e.append(a)),l||(e.setAttribute(`data-persona-preparing`,``),e.inert=!0);let d=new Promise((e,t)=>{i=()=>t(/* @__PURE__ */ Error(`Widget destroyed before ready`))});r=Promise.race([Promise.all(o),d]).then(()=>{if(n)throw Error(`Widget destroyed before ready`);if(u!==t||(c(),u!==t))return r;s()},e=>{if(!n&&u!==t)return r;throw e}),r.catch(()=>{})},destroy(){n=!0,++t,i(),s()}}},An={defaultProvenance:d,suppliedPath:e,hasExplicitThemeStyle:t,getExplicitLegacyStyle:f},{setLoader:jn,load:Mn,provide:Nn,getSync:Pn}=v({fallbackImport:()=>import(`./chunk-B4ecQzeK.js`)}),Fn=Mn,In=Pn,{setLoader:Ln,load:Rn,provide:zn}=v({fallbackImport:()=>import(`./chunk-C3cPmtjr.js`)});let Bn=null;const Vn=()=>Promise.all([Rn(),Fn()]).then(([e,t])=>(Object.assign(t.turnUi,e),Bn=e)),Hn=()=>Bn,{setLoader:Un,load:Wn,provide:Gn,getSync:Kn}=v({fallbackImport:()=>import(`./chunk-C7-m0EmI.js`)}),qn=Wn,Jn=Kn,{setLoader:Yn,load:P,provide:F,getSync:Xn}=v({fallbackImport:()=>import(`./chunk-B3l7TOOv.js`)}),I=P,Zn=Xn,{setLoader:L,load:R,getSync:z,provide:Qn}=v({fallbackImport:()=>import(`./chunk-Ds_twaZn.js`)}),$n=R,er=z;function tr(e){let{items:t,onSelect:n,anchor:r,position:i=`bottom-left`,portal:a,onOpenChange:o}=e,s=k(`div`,`persona-dropdown-menu persona-hidden`);s.setAttribute(`role`,`menu`),s.setAttribute(`data-persona-theme-zone`,`dropdown`),a?(s.style.position=`fixed`,s.style.zIndex=String(qe)):(s.style.position=`absolute`,s.style.top=`100%`,s.style.marginTop=`4px`,i===`bottom-right`?s.style.right=`0`:s.style.left=`0`);for(let e of t){if(e.dividerBefore){let e=document.createElement(`hr`);s.appendChild(e)}let t=document.createElement(`button`);if(t.type=`button`,t.setAttribute(`role`,`menuitem`),t.setAttribute(`data-dropdown-item-id`,e.id),e.destructive&&t.setAttribute(`data-destructive`,``),e.icon){let n=T(e.icon,16,`currentColor`,1.5);n&&t.appendChild(n)}let r=document.createElement(`span`);r.textContent=e.label,t.appendChild(r),t.addEventListener(`click`,t=>{t.stopPropagation(),d(),n(e.id)}),s.appendChild(t)}let c=null;function l(){if(!a)return;let e=r.getBoundingClientRect();s.style.top=`${e.bottom+4}px`,i===`bottom-right`?(s.style.right=`${window.innerWidth-e.right}px`,s.style.left=`auto`):(s.style.left=`${e.left}px`,s.style.right=`auto`)}function u(){let e=s.classList.contains(`persona-hidden`);l(),s.classList.remove(`persona-hidden`),e&&o?.(!0),requestAnimationFrame(()=>{let e=e=>{!s.contains(e.target)&&!r.contains(e.target)&&d()};document.addEventListener(`click`,e,!0),c=()=>document.removeEventListener(`click`,e,!0)})}function d(){let e=!s.classList.contains(`persona-hidden`);s.classList.add(`persona-hidden`),c?.(),c=null,e&&o?.(!1)}function f(){s.classList.contains(`persona-hidden`)?u():d()}function p(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:u,hide:d,toggle:f,destroy:p}}function nr(e){let{icon:t,label:n,size:r,strokeWidth:i,className:a,chromeless:o,onClick:s,aria:c}=e,l=k(`button`,We(!o&&`persona-icon-btn`,a));l.type=`button`,l.setAttribute(`aria-label`,n),l.title=n;let u=T(t,r??16,`currentColor`,i??2);if(u&&l.appendChild(u),s&&l.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))l.setAttribute(e,t);return l}function B(e){let{icon:t,label:n,variant:r=`default`,size:i=`sm`,iconSize:a,className:o,onClick:s,aria:c}=e,l=`persona-label-btn`;r!=="default"&&(l+=` persona-label-btn--`+r),l+=` persona-label-btn--`+i,o&&(l+=` `+o);let u=k(`button`,l);if(u.type=`button`,u.setAttribute(`aria-label`,n),t){let e=T(t,a??14,`currentColor`,2);e&&u.appendChild(e)}let d=k(`span`);if(d.textContent=n,u.appendChild(d),s&&u.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))u.setAttribute(e,t);return u}function rr(e){let{items:t,selectedId:n,onSelect:r,className:i}=e,a=k(`div`,`persona-toggle-group`+(i?` `+i:``));a.setAttribute(`role`,`group`);let o=n,s=[];function c(){for(let e of s)e.btn.setAttribute(`aria-pressed`,e.id===o?`true`:`false`)}for(let e of t){let t;e.icon?t=nr({icon:e.icon,label:e.label,className:e.className,onClick:()=>{o=e.id,c(),r(e.id)}}):(t=k(`button`,`persona-icon-btn`+(e.className?` `+e.className:``)),t.type=`button`,t.setAttribute(`aria-label`,e.label),t.title=e.label,t.textContent=e.label,t.addEventListener(`click`,()=>{o=e.id,c(),r(e.id)})),t.setAttribute(`aria-pressed`,e.id===o?`true`:`false`),s.push({id:e.id,btn:t}),a.appendChild(t)}function l(e){o=e,c()}return{element:a,setSelected:l}}function ir(e){let{label:t,icon:n,iconSize:r,iconOnly:i,menuItems:a,onSelect:o,onPrimary:s,position:c=`bottom-left`,portal:l,chevronLabel:u=`More options`,chevronIconSize:d,className:f,primaryClassName:p,chevronClassName:m}=e,h=k(`div`,`persona-split-btn`+(f?` `+f:``)),g={label:t,className:`persona-split-btn-primary`+(p?` `+p:``),onClick:s},_=i&&n?nr({...g,icon:n,size:r??14}):B({...g,icon:n,iconSize:r??14}),v=nr({icon:`chevron-down`,label:u,size:d??14,className:`persona-split-btn-chevron`+(m?` `+m:``),aria:{"aria-haspopup":`true`,"aria-expanded":`false`}});h.append(_,v);let y=null,b=()=>{if(y)return y;let e=(typeof l==`function`?l():l)??void 0;return y=tr({items:a,onSelect:o,anchor:h,position:c,portal:e,onOpenChange:e=>{v.setAttribute(`aria-expanded`,e?`true`:`false`)}}),e||h.appendChild(y.element),y};return h.isConnected?b():requestAnimationFrame(()=>{y||b()}),v.addEventListener(`click`,e=>{e.stopPropagation(),b().toggle()}),{element:h,primaryButton:_,chevronButton:v,openMenu:()=>b().show(),closeMenu:()=>y?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{y?.destroy(),h.remove()}}}function V(e){let{label:t,icon:n=`chevron-down`,menuItems:r,onSelect:i,position:a=`bottom-left`,portal:o,className:s,hover:c}=e,l=k(`div`,`persona-combo-btn`+(s?` `+s:``));l.style.position=`relative`,l.style.display=`inline-flex`,l.style.alignItems=`center`,l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`),l.setAttribute(`aria-haspopup`,`true`),l.setAttribute(`aria-expanded`,`false`),l.setAttribute(`aria-label`,t);let u=k(`span`,`persona-combo-btn-label`);u.textContent=t,l.appendChild(u);let d=T(n,14,`currentColor`,2);d&&(d.style.marginLeft=`4px`,d.style.opacity=`0.6`,l.appendChild(d)),c&&(l.style.borderRadius=c.borderRadius??`10px`,l.style.padding=c.padding??`6px 4px 6px 12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=c.background??``,l.style.borderColor=c.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}));let f=tr({items:r,onSelect:e=>{l.setAttribute(`aria-expanded`,`false`),i(e)},anchor:l,position:a,portal:o});o||l.appendChild(f.element);let p=()=>l.getAttribute(`data-persona-menu-locked`)===`true`;return l.addEventListener(`click`,e=>{if(e.stopPropagation(),p())return;let t=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,t?`false`:`true`),f.toggle()}),l.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),l.click())}),{element:l,setLabel:e=>{u.textContent=e,l.setAttribute(`aria-label`,e)},open:()=>{l.setAttribute(`aria-expanded`,`true`),f.show()},close:()=>{l.setAttribute(`aria-expanded`,`false`),f.hide()},toggle:()=>{let e=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,e?`false`:`true`),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}const ar=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:or,load:sr,provide:cr,getSync:lr}=v({fallbackImport:()=>import(`./chunk-BbXc58OA.js`)});let ur=null;const dr=/* @__PURE__ */ new Set,fr=e=>{if(ur)return ur;ur=e,e.initArtifactsUi({componentRegistry:ze,loadingLabels:Zn(),buttons:{createIconButton:nr,createLabelButton:B,createSplitButton:ir,createToggleGroup:rr}});for(let t of ar)ze.has(t)||ze.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Ne();t?e.__provideMarkdownParsers(t):Ue(()=>{let t=Ne();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader!==_&&e.__setIconsExtraLoader(y);let n=[...dr];dr.clear();for(let e of n)try{e()}catch{}return e},pr=()=>Promise.all([sr(),I()]).then(([e])=>fr(e)),mr=()=>{if(ur)return ur;if(!Zn())return null;let e=lr();return e?fr(e):null},hr=e=>ur?()=>{}:(dr.add(e),()=>{dr.delete(e)}),{setLoader:gr,load:_r,provide:vr,getSync:H}=v({fallbackImport:()=>import(`./chunk-BpjtKnGI.js`)}),yr=_r,br=H,{setLoader:xr,load:Sr,getSync:Cr}=v({fallbackImport:()=>import(`./chunk-D0tcIZJM.js`)}),wr=Sr,Tr=Cr;function Er(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||kr(e)!==kr(t)||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Dr(e){return e?.type===`runtype`||e?.type===`custom`}const Or=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function U(e){try{if(e?.type===`custom`&&e.custom){let t=e.custom,n=typeof t==`function`?t():t;return!!n&&typeof n.startListening==`function`}return e?.type===`runtype`&&e.runtype?!0:Or()}catch{return!1}}function kr(e){let t=e.voiceRecognition;return Dr(t?.provider)&&(t?.provider?.type!==`custom`||!!t.dictation?.provider||!t.dictation&&t.completionBehavior!==`review`)}const Ar=e=>{let t=[],n=(e,n,r)=>{e&&!n&&t.push(r())};n(!0,Jn(),qn),n(!0,Ne(),Oe);let r=e.turnActivity?.enabled===!0;n(r,Hn(),Vn);let i=r||e.features?.showToolCalls!==!1||e.features?.showReasoning!==!1;n(i,In(),Fn),n(i||e.loadingLabel?.animation!==`none`&&(!!e.loadingLabel?.animate||(e.loadingIndicator?.variant??(e.future?.v5Defaults?`label`:`dots`))===`label`),Zn(),I),n(e.voiceRecognition?.enabled!==!1,er(),$n),n(e.voiceRecognition?.enabled!==!1&&kr(e),Tr(),wr),n(e.features?.artifacts?.enabled===!0,mr(),pr),n(e.contextMentions?.enabled===!0,br(),yr);let a=w();return a&&t.push(a),t};function jr(){let e=null,t=()=>{e!==null&&cancelAnimationFrame(e),e=null};return{get active(){return e!==null},cancel:t,start(n,r,i,a,o,s=()=>!0){t();let c=n.scrollTop,l=performance.now();if(Math.abs(r()-c)<1){n.scrollTop=r(),a(),o();return}let u=d=>{if(!s()){t(),o();return}let f=Math.min(Math.max(0,(d-l)/i),1);n.scrollTop=c+(r()-c)*(1-(1-f)**3),a(),f<1?e=requestAnimationFrame(u):(e=null,o())};e=requestAnimationFrame(u)}}}function Mr(e,t,n,r,i){let a=jr(),o=!1,s,c=!1,l=e=>{e&&(c=!1),a.active&&(a.cancel(),s=e,c=!!e,i())},u=e=>{[`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`,` `].includes(e.key)&&l(e)},d=e=>{e.deltaY!==0&&l(e)};return e.addEventListener(`wheel`,d,{passive:!0}),e.addEventListener(`touchstart`,l,{passive:!0}),e.addEventListener(`pointerdown`,l,{passive:!0}),t.addEventListener(`keydown`,u),{get active(){return a.active},cancel:l,get interrupted(){return c},interruptedBy:e=>s===e,start(t){if(o)return;a.cancel(),c=!1,s=void 0;let i=(t.features?.scrollToBottom?.scrollBehavior??(t.future?.v5Defaults?`smooth`:`instant`))===`smooth`,l=t.features?.scrollToBottom?.scrollDurationMs??220,u=Number.isFinite(l)&&l>=0?l:220,d=typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches;!i||d||u===0?(e.scrollTop=Xe(e),n(),r()):a.start(e,()=>Xe(e),u,n,r)},destroy(){o=!0,a.cancel(),e.removeEventListener(`wheel`,d),e.removeEventListener(`touchstart`,l),e.removeEventListener(`pointerdown`,l),t.removeEventListener(`keydown`,u)}}}function Nr(e,t,n){let r=k(`button`,`persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer`);r.type=`button`,r.setAttribute(`data-persona-scroll-to-bottom-visible`,`false`),r.disabled=!0,r.tabIndex=-1,r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`data-persona-scroll-to-bottom`,`true`);let i=k(`span`,`persona-flex persona-items-center persona-justify-center`);i.setAttribute(`aria-hidden`,`true`);let a=k(`span`,``),o=k(`span`,``);o.setAttribute(`data-persona-scroll-to-bottom-count`,``),r.appendChild(i),r.appendChild(a),r.appendChild(o);let s={},c={activity:`idle`,visible:!1,hovered:!1,focused:!1,reducedMotion:!1},l,u,d,f=``,p=typeof matchMedia==`function`?matchMedia(`(prefers-reduced-motion: reduce)`):void 0;c.reducedMotion=p?.matches??!1;let m=e=>console.warn(`Persona scroll icon failed`,e),h=()=>({config:s,state:{...c},view:t,signal:d.signal}),g=()=>{d?.abort();try{u?.destroy?.()}catch(e){m(e)}u=void 0,d=void 0,i.innerHTML=``,f=``},_=()=>{if(u?.element)return;let t=s.features?.scrollToBottom,n=c.activity===`generating-below`&&(t?.streamingIndicator??(s.future?.v5Defaults?`dots`:`arrow`))===`dots`,r=n?`dots`:`arrow:${t?.iconName??`arrow-down`}`;if(f!==r){if(f=r,i.innerHTML=``,n){let e=k(`span`,`persona-scroll-to-bottom-dots`);for(let t=0;t<3;t++){let n=k(`span`,``);n.style.animationDelay=`${t*150}ms`,e.appendChild(n)}i.appendChild(e)}else{let n=e(t?.iconName??`arrow-down`,`14px`,`currentColor`,2);n&&i.appendChild(n)}}},v=e=>{let t=s.features?.scrollToBottom?.enabled===!1?void 0:s.features?.scrollToBottom?.renderIcon;if(t!==l){if(g(),l=t,l){d=new AbortController;try{let e=l(h());u=e&&`element`in e?e:e?{element:e}:void 0,u?.element&&i.appendChild(u.element)}catch(e){m(e),g()}}}else if(e&&u?.update)try{u.update(h())}catch(e){m(e),g()}_()},y=e=>Object.keys(e).some(t=>e[t]!==c[t]),b=e=>{let t=y(e);c=e,v(t)},x=()=>b({...c,hovered:!0}),S=()=>b({...c,hovered:!1}),C=()=>b({...c,focused:!0}),ee=()=>b({...c,focused:!1}),w=()=>b({...c,reducedMotion:p?.matches??!1}),T=new AbortController;for(let[e,t]of[[`mouseenter`,x],[`mouseleave`,S],[`focus`,C],[`blur`,ee]])r.addEventListener(e,t,{signal:T.signal});return p?.addEventListener?.(`change`,w),{element:r,update(e,t,i=!1,l=0){let u=s.features?.scrollToBottom,d=e.features?.scrollToBottom,f=s.future?.v5Defaults!==e.future?.v5Defaults||[`enabled`,`iconName`,`label`,`streamingIndicator`,`transition`,`scrollBehavior`,`scrollDurationMs`].some(e=>u?.[e]!==d?.[e]);s=e;let p=s.features?.scrollToBottom;t&&=p?.enabled!==!1;let m=r.getRootNode().activeElement===r;r.setAttribute(`data-persona-scroll-to-bottom-visible`,String(t));let h=p?.enabled===!1?`none`:p?.transition??(s.future?.v5Defaults?`fade`:`none`);r.setAttribute(`data-persona-scroll-to-bottom-transition`,h),i&&t?r.setAttribute(`data-persona-scroll-to-bottom-streaming`,``):r.removeAttribute(`data-persona-scroll-to-bottom-streaming`),r.style.display=!t&&h===`none`?`none`:``,r.disabled=!t,r.tabIndex=t?0:-1,r.setAttribute(`aria-hidden`,String(!t)),!t&&m&&(r.blur(),n&&(n.hasAttribute(`tabindex`)||(n.tabIndex=-1),n.focus({preventScroll:!0})));let g=p?.label??``,_=g||`Jump to latest`;r.setAttribute(`aria-label`,`${_}${l>0?` (${l} new)`:``}${i&&t?` (response streaming below)`:``}`),r.title=g,r.setAttribute(`data-persona-scroll-to-bottom-has-label`,String(!!g)),a.textContent=g,a.style.display=g?``:`none`,o.textContent=l>0?String(l):``,o.style.display=l>0?``:`none`;let b={...c,visible:t,hovered:t&&c.hovered,focused:t&&c.focused,activity:i&&t?`generating-below`:`idle`},x=f||y(b);c=b,v(x)},destroy(){g(),T.abort(),p?.removeEventListener?.(`change`,w),r.remove()}}}function Pr(e){let t=/* @__PURE__ */ new Map,n=(t,n)=>({slot:t,signal:n.abort.signal,config:e.config(),defaultContent:()=>e.defaultContent(t)}),r=(n,r)=>{t.delete(n),r.abort.abort();try{r.result.destroy?.()}catch(e){console.error(`[AgentWidget] Error destroying slot "${n}":`,e)}e.remove(n,r.result.element)};return{update(){let i=e.config().layout?.slots??{};for(let[e,n]of t)i[e]!==n.renderer&&r(e,n);for(let[a,o]of Object.entries(i)){if(!o)continue;let i=t.get(a);try{if(!i){i={renderer:o,abort:new AbortController,result:{element:null}},t.set(a,i);let e=o(n(a,i));i.result=e===null||`nodeType`in e?{element:e}:e}else if(i.result.update){let t=i.result.update(n(a,i));t!==void 0&&t!==i.result.element&&(e.remove(a,i.result.element),i.result.element=t)}i.result.element&&e.mount(a,i.result.element)}catch(e){i&&r(a,i),console.error(`[AgentWidget] Error rendering slot "${a}":`,e)}}},remount(){for(let[n,r]of t)r.result.element&&e.mount(n,r.result.element)},detach(n){for(let r of n){let n=t.get(r);n&&e.remove(r,n.result.element)}},destroy(){for(let[e,n]of t)r(e,n)}}}const Fr=`var(--persona-md-table-scroll-fade, 24px)`,Ir=/* @__PURE__ */ new WeakSet;function Lr(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(`persona-table-scroll`))return;let t=document.createElement(`div`);t.className=`persona-table-scroll`,e.replaceWith(t),t.appendChild(e)})}function Rr(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute(`data-persona-scroll-x`);return}e.setAttribute(`data-persona-scroll-x`,``);let n=getComputedStyle(e).direction===`rtl`?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty(`--persona-fade-l`,n<=1?`0px`:Fr),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:Fr)}function zr(e){Ir.has(e)||(Ir.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&Rr(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(Rr)}const{setLoader:Br,load:Vr,provide:Hr,getSync:Ur}=v({fallbackImport:()=>import(`./chunk-DNdeIFJ6.js`)}),Wr=Vr,Gr=Ur,{setLoader:Kr,load:qr,provide:Jr,getSync:Yr}=v({fallbackImport:()=>import(`./chunk-CjkechxR.js`)}),Xr=qr,Zr=Yr,{setLoader:Qr,load:$r}=v({fallbackImport:()=>import(`./chunk-CzLEhoB_.js`)}),ei=$r,{setLoader:ti,load:ni}=v({fallbackImport:()=>import(`./chunk-lA5CJCgK.js`)}),ri=ni;function ii(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function ai(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=ii(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=ii(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}const{setLoader:oi,load:si,provide:ci}=v({fallbackImport:()=>import(`./chunk-B9Zu-wrk.js`)}),li=si;var ui=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const di=e=>`reason`in e?e.reason:void 0;function fi(e){switch(e){case`json`:return yt;case`regex-json`:return N;case`xml`:return bt;default:return j}}var pi=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;constructor(e={},t={}){if(this.#f=0,this.#p=/* @__PURE__ */ new Set,this.#m=null,this.clientSession=null,this.#h=null,this.#g=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#_=null,this.#v=!1,this.#y=!1,this.#b=!1,this.#x=null,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#w=null,this.#U=null,this.#G=null,this.#i=e,this.#r=t,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":Dt,...e.headers},this.#n=!!e.debug,this.#a=e.streamParser??fi(e.parserType),this.#o=e.contextProviders??[],this.#s=e.requestMiddleware,this.#c=e.customFetch,this.#l=e.parseSSEEvent,this.#u=e.getHeaders,e.webmcp?.enabled===!0&&(this.#w=this.#E(e.webmcp))}#E(e){return ei().then(t=>{let n=new t.WebMcpBridge(e,{recordToolDisplayTitles:ot,getToolDisplayTitle:st,loadPolyfill:rt});return this.#T!==void 0&&n.setConfirmHandler(this.#T),this.webMcpBridge=n,n}).catch(e=>(this.#w=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#D(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.#i.webmcp?.enabled===!0?(this.#w||=this.#E(this.#i.webmcp),this.#w):Promise.resolve(null)}updateConfig(e){this.#i=e}setHistoryInternals(e){this.#r=e}cancelStreams(){if(this.#f+=1,this.#i.backgroundConversations)for(let e of this.#p)e.cancel().catch(()=>{})}setSSEEventCallback(e){this.#d=e}setWebMcpConfirmHandler(e){this.#T=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}getVoiceClientTools(){if(this.#i.webmcp?.enabled!==!0)return null;let e=()=>this.#D(),t={open:async e=>(await ri()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:at(t)}},onChange:t=>{let n=null,r=!1;return e().then(e=>{e&&!r&&(n=e.watchToolChanges(t))}),()=>{r=!0,n?.()}},execute:async(t,n,r)=>{let i=await e();return i?i.executeVoiceToolCall(t,n,r):{status:`failed`,error:{message:`WebMCP runtime failed to load.`}}}};return t}executeWebMcpToolCall(e,t,n,r){return this.#i.webmcp?.enabled===!0?this.#D().then(i=>i?i.executeToolCall(e,t,n,r):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#d}isClientTokenMode(){return!!this.#i.clientToken}#O(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.#i;if(!n)return{agentId:e,flowId:t};let i=ai(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.#i.agent||this.#O().agentId)}#k(){return this.#i.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#A(e){return`${this.#k()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new ui(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#k()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":Dt,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await li();t=await e.recoverFromUnauthorized(this.#K(),await e.readErrorCode(this.#K(),s),null,!0)}else{if(!s.ok)throw await(await li()).historyErrorFor(this.#K(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#h||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#g===e?null:(this.#g=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#h)return this.#h;let e=this.#h=this.#R().then(t=>this.#h===e?(this.clientSession=t,this.#g=!1,this.resetClientToolsFingerprint(),this.#i.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#h===e&&(this.#h=null)});return e}#j(){return this.#i.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#v}async readVisitorToken(){let e=this.#r.visitorStore;return e?(await e.ready,await e.get()??null):null}#M(){if(!this.#v){this.#I({state:`unavailable`,reason:`history_disabled`}),this.#v=!0,!this.#y&&typeof console<`u`&&(this.#y=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.#r.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#C])e(!1)}}getHistoryIdentityStatus(){return this.#x??this.#N()}subscribeHistoryIdentityStatus(e){return this.#S.add(e),()=>{this.#S.delete(e)}}subscribeHistoryAvailability(e){return this.#C.add(e),this.#v&&e(!1),()=>{this.#C.delete(e)}}#N(){return this.isClientTokenMode()?this.#i.features?.history?.enabled!==!0||this.#v?{state:`unavailable`,reason:`history_disabled`}:this.#P():{state:`unavailable`,reason:`ineligible_mode`}}#P(){let e=this.#x;return e?.state===`browser_only`?e:this.#F()}#F(){return this.#i.features?.history?.scope===`browser`?{state:`browser_only`,reason:`configured_browser_scope`}:this.#i.getIdentityProof?{state:`browser_only`,reason:`proof_unavailable_before_binding`}:{state:`browser_only`,reason:`no_identity_provider`}}#I(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&di(t)===di(e);if(this.#x=e,!n){this.#r.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#S])t(e)}}async#L(e){return new((Zr())??await(Xr())).ClientDispatch(this.#q()).createClientSession(e)}async#R(){return new((Zr())??await(Xr())).ClientDispatch(this.#q()).initializeSession()}async#z(e){let t=this.#i.getStoredSessionId?.()||null,n=this.#i.getStoredConversationId?.()||null,r=await this.#L({storedSessionId:t,identityProof:e}),i=this.#B(r,n,!1);return this.clientSession=i,this.#h=null,this.#g=!1,this.resetClientToolsFingerprint(),i}#B(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.#r.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.#i.setStoredSessionId?.(e.sessionId),r&&(this.#i.setStoredConversationId?.(r),this.#r.setStoredConversationRevision?.(e.conversationRevision??null)),e}#V(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#g=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#j())throw new ui(`history_disabled`,`Visitor history is disabled for this surface`);await this.#r.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new ui(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#L({conversationId:e,identityProof:n});return this.#V(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.#r.historyBootstrapReady;let e=await this.#L({});return this.#V(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#j()&&this.#I(this.#F())}clearClientSession(){this.clientSession=null,this.#h=null,this.#g=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#_=null}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);return new((Zr())??await(Xr())).ClientDispatch(this.#q()).sendFeedback(e)}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#H(e){e?.throwIfAborted();let t=this.#i.identityProvider;if(t===void 0)return;let n=this.#i.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#U;#W(){let e=this;return this.#U??={get config(){return e.#i},headers:this.#t,getHeaders:this.#u,debug:this.#n,clientApiBase:()=>e.#k(),getClientApiUrl:t=>e.#A(t),getWebMcpBridge:()=>e.#D(),sendWithClientToolsDiff:(t,n,r,i)=>e.#J(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#G;#K(){let e=this;return this.#G??={HistoryClientError:ui,get config(){return e.#i},get historyInternals(){return e.#r},get clientSession(){return e.clientSession},clientApiBase:()=>e.#k(),setHistoryIdentityStatus:t=>e.#I(t),browserOnlyStatus:()=>e.#P(),derivedBrowserOnly:()=>e.#F(),reinitWithProof:t=>e.#z(t),isHistoryCapable:()=>e.#j(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await li()).listConversations(this.#K(),e)}async getConversation(e,t){return(await li()).getConversation(this.#K(),e,t)}async finalizeDisplayProjections(e,t){return(await li()).finalizeDisplayProjections(this.#K(),e,t)}async deleteConversation(e,t){return(await li()).deleteConversation(this.#K(),e,t)}async deleteAllConversations(e){return(await li()).deleteAllConversations(this.#K(),e)}async resetVisitor(){return(await li()).resetVisitor(this.#K())}async dispatch(e,t){e.signal?.throwIfAborted(),Wr().catch(()=>{});let n=this.isClientTokenMode(),r=this.isAgentMode(),i=lt();n&&(this.#m=i),t({type:`status`,status:`connecting`});let a=Zr()??await Xr().catch(e=>{let r=e instanceof Error?e:Error(String(e));throw(!n||this.#m===i)&&t({type:`error`,error:r}),r});if(e.signal?.throwIfAborted(),n&&this.#m!==i)throw new DOMException(`Turn superseded`,`AbortError`);let o=new a.ClientDispatch(this.#q());return n?o.dispatchClientToken(e,t,i):r?o.dispatchAgent(e,t):o.dispatchProxy(e,t)}#q(){let e=this;return Object.setPrototypeOf({HistoryClientError:ui,get claimInFlight(){return e.#b},set claimInFlight(t){e.#b=t},get clientToolsFingerprintSessionId(){return e.clientToolsFingerprintSessionId},set clientToolsFingerprintSessionId(t){e.clientToolsFingerprintSessionId=t},get lastSentClientToolsFingerprint(){return e.lastSentClientToolsFingerprint},set lastSentClientToolsFingerprint(t){e.lastSentClientToolsFingerprint=t},get sentNonEmptyClientToolsSessionId(){return e.#_},set sentNonEmptyClientToolsSessionId(t){e.#_=t},get historyInternals(){return e.#r},markHistoryUnavailable:()=>e.#M(),apiUrl:this.#e,contextProviders:this.#o,requestMiddleware:this.#s,customFetch:this.#c,get clientSession(){return e.clientSession},set clientSession(t){e.clientSession=t},isCurrentTurn:t=>e.#m===t,isHistoryCapable:()=>e.#j(),createClientSession:t=>e.#L(t),finishInit:(t,n,r)=>e.#B(t,n,r),resetSessionWarmLatch:()=>{e.#g=!1},resetClientToolsFingerprint:()=>e.resetClientToolsFingerprint(),clearClientSession:()=>e.clearClientSession(),resolveChatIdentityProof:t=>e.#H(t),routing:()=>e.#O(),builtInClientTools:wt,streamResponse:(...t)=>e.#Y(...t)},this.#W())}async processStream(e,t,n,r,i,a,o){t({type:`status`,status:`connected`});try{await this.#Y(e,t,n,r,i,a,o)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t,n){return(await Wr()).resolveApproval(this.#W(),e,t,n)}async#J(e,t,n,r){return new((Zr())??await(Xr())).ClientDispatch(this.#q()).sendWithClientToolsDiff(e,t,n,r)}async resumeFlow(e,t,n){return(await Wr()).resumeFlow(this.#W(),e,t,n)}async#Y(e,t,n,r,i,a,o){let{streamResponse:s}=Gr()??await Wr();return s({config:()=>this.#i,streamGeneration:()=>this.#f,streamReaders:this.#p,createStreamParser:this.#a,parseSSEEvent:this.#l,onSSEEvent:(e,t)=>this.#d?.(e,t)},e,t,n,r,i,a,o)}};const{setLoader:mi,load:hi}=v({fallbackImport:()=>import(`./chunk-CsBLSRM_.js`)}),gi=hi,{setLoader:_i,load:vi,provide:W,getSync:G}=v({fallbackImport:()=>import(`./chunk-BL6v2bXy.js`)}),K=vi,yi=G,bi=e=>typeof e==`object`&&!!e&&!Array.isArray(e),xi=(e,t)=>{let n=/* @__PURE__ */ new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!bi(e))return[];let{toolCallId:r,name:i}=e;if(typeof r!=`string`||!r||typeof i!=`string`||!i||n.has(r))return[];n.add(r);let a=bi(e.arguments)?e.arguments:{},o=e.result??null;return[{id:`voice-tool-${r}`,role:`assistant`,variant:`tool`,content:``,createdAt:t,streaming:!1,toolCall:{id:r,name:i,status:`complete`,args:a,result:o},agentMetadata:{clientToolAnswer:{toolCallId:r,toolName:i,args:a,result:o}}}]})},Si=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function Ci(e){let t=e?.text?.trim()??``;return t?Lt(Si(e),t):``}function wi(e){let t=Ci(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[kt(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
2
2
 
3
3
  `)}:{}}function Ti(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Ei(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1||e[n].role!==`user`)return null;let r=n+1;for(;r<e.length&&e[r].role!==`user`;)r+=1;return{start:n,end:r}}function Di(e,t){let n=e.findIndex(e=>e.id===t);if(n<=0)return null;for(let t=n-1;t>=0;--t)if(e[t].role===`user`)return e[t].id;return null}function Oi(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`||n.streaming)return null;if(!(n.role!==`assistant`||n.variant))return Di(e,n.id)?n.id:null}return null}function ki(e){return e.role!==`user`||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content==`string`&&e.content.length>0}function Ai(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=Pe(n,e.component);if(!a){if(ar.includes(e.component)){pr().catch(()=>{});let e=k(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o=t.context??{message:r,config:n,signal:t.signal??new AbortController().signal,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function ji(e){if(typeof e.rawContent==`string`&&e.rawContent.length>0)return e.rawContent;if(typeof e.content==`string`){let t=e.content.trim();if(t.startsWith(`{`)||t.startsWith(`[`))return e.content}return null}function Mi(e){let t=ji(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function Ni(e){let t=ji(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}function Pi(e){for(let t of[`Microsoft Jenny Online (Natural) - English (United States)`,`Microsoft Aria Online (Natural) - English (United States)`,`Microsoft Guy Online (Natural) - English (United States)`,`Google US English`,`Google UK English Female`,`Ava (Premium)`,`Evan (Enhanced)`,`Samantha (Enhanced)`,`Samantha`,`Daniel`,`Karen`,`Microsoft David Desktop - English (United States)`,`Microsoft Zira Desktop - English (United States)`]){let n=e.find(e=>e.name===t);if(n)return n}return e.find(e=>e.lang.startsWith(`en`))??e[0]}var Fi=class e{constructor(e={}){this.options=e,this.id=`browser`,this.supportsPause=!0}static isSupported(){return typeof window<`u`&&`speechSynthesis`in window}speak(t,n){if(!e.isSupported()){n.onError?.(/* @__PURE__ */ Error(`Web Speech API is unavailable`));return}let r=window.speechSynthesis;r.cancel();let i=new SpeechSynthesisUtterance(t.text),a=r.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(i.voice=e)}else a.length>0&&(i.voice=this.options.pickVoice?this.options.pickVoice(a):Pi(a));t.rate!==void 0&&(i.rate=t.rate),t.pitch!==void 0&&(i.pitch=t.pitch),i.onend=()=>n.onEnd?.(),i.onerror=e=>{let t=e.error;t===`canceled`||t===`interrupted`?n.onEnd?.():n.onError?.(Error(t||`Speech synthesis failed`))},setTimeout(()=>{r.speak(i),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},Ii=class{#e=null;#t=null;#n=`idle`;#r=/* @__PURE__ */ new Set;#i=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#n:`idle`}activeMessageId(){return this.#t}onChange(e){return this.#r.add(e),()=>this.#r.delete(e)}toggle(e,t){if(this.#t===e){if(this.#n===`playing`){this.#e?.supportsPause?(this.#e.pause(),this.#o(e,`paused`)):this.stop();return}if(this.#n===`paused`){this.#e?.resume(),this.#o(e,`playing`);return}if(this.#n===`loading`){this.stop();return}}this.play(e,t)}async play(e,t){let n=++this.#i;this.#e?.stop(),this.#o(e,`loading`);try{if(!this.#e){let e=await this.#a();if(n!==this.#i)return;if(!e){this.#o(null,`idle`);return}this.#e=e}this.#e.speak(t,{onStart:()=>{n===this.#i&&this.#o(e,`playing`)},onEnd:()=>{n===this.#i&&this.#o(null,`idle`)},onError:()=>{n===this.#i&&this.#o(null,`idle`)}})}catch{n===this.#i&&this.#o(null,`idle`)}}stop(){this.#i++,this.#e?.stop(),this.#o(null,`idle`)}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#r.clear()}#o(e,t){this.#t=t===`idle`?null:e,this.#n=t;for(let e of this.#r)e(this.#t,this.#n)}},Li=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!this.#t&&(!e||!this.#e||e===this.#e)}};function Ri(e){if(!e)return``;let t=zi(e);return Bi(t===null?e:t)}function zi(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith(`{`))return null;try{let e=JSON.parse(t);if(e&&typeof e==`object`&&typeof e.text==`string`)return e.text}catch{}return null}function Bi(e){if(!e)return``;let t=e;return t=t.replace(/```[\s\S]*?```/g,` `),t=t.replace(/~~~[\s\S]*?~~~/g,` `),t=t.replace(/`([^`]+)`/g,`$1`),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,`$1`),t=t.replace(/<\/?[a-zA-Z][^>]*>/g,` `),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,``),t=t.replace(/^[ \t]*>[ \t]?/gm,``),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,``),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,``),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm,` `),t=t.replace(/(\*\*|__)(.*?)\1/g,`$2`),t=t.replace(/(\*|_)(.*?)\1/g,`$2`),t=t.replace(/~~(.*?)~~/g,`$1`),t=t.replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&nbsp;/g,` `),t=t.replace(/[ \t]+/g,` `),t=t.replace(/[ \t]*\n[ \t]*/g,`
4
4
  `),t=t.replace(/\n{2,}/g,`
5
- `),t.trim()}const Vi=()=>import(`./chunk-59UOGW9N.js`),{setLoader:Hi,load:Ui}=v({fallbackImport:()=>import(`./chunk-DvGdwBMD.js`)}),Wi=Ui,Gi=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.backgroundConversations.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function Ki(e,t){return Gi.some(n=>e[n]!==t[n])}var qi=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function Ji(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.`;return n.message?`${r}\n\n_Details: ${n.message}_`:r}const Yi=e=>it(e)||e===`suggest_replies`;var Xi=class e{#e;#t;#n;#r;#i(e){if(this.#a(`cancel`),this.#n=!1,this.#e={runId:`run-${dt()}`,timestamp:Date.now()},this.#t={run:this.#e,messageIds:/* @__PURE__ */ new Set},e)for(let t of this.messages)t.role===`assistant`&&t.agentMetadata?.executionId===e&&this.#t.messageIds.add(t.id);this.callbacks.onRunStarted?.({...this.#e})}#a(e,t=this.#e){if(t!==this.#e)return;this.#r!==null&&clearTimeout(this.#r),this.#r=null;let n=this.#e;if(this.#e=null,n){let t=n;t.timestamp=Date.now(),t.outcome=e,this.callbacks.onRunFinished?.(t)}}#o(){if(!this.#e||this.#r!==null)return;let e=this.#e;this.#r=setTimeout(()=>{this.#r=null,this.#e===e&&(!this.#n&&(this.streaming||this.#f||this.#_t()||this.webMcpAwaitBatches.size||this.webMcpResolveControllers.size)||this.#a(this.#n?`error`:`success`))},0)}#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.#e=null,this.#n=!1,this.#r=null,this.streaming=!1,this.#s=/* @__PURE__ */ new Map,this.abortController=null,this.#l=Date.now(),this.clientSession=null,this.agentExecution=null,this.#u=null,this.#d=null,this.#f=!1,this.#m=null,this.#h=null,this.#g=null,this.#_=null,this.#v=null,this.#y=null,this.artifacts=/* @__PURE__ */ new Map,this.#b=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#x=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#S=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#C=null,this.#w=null,this.#T=0,this.#E=0,this.#D=!1,this.#O=`disconnected`,this.#k=null,this.#A=null,this.#j=null,this.#M=0,this.#N=0,this.#P=null,this.#F=Promise.resolve(),this.#I=!1,this.#L=null,this.#R=!1,this.#z=null,this.#B=/* @__PURE__ */ new Map,this.#V=null,this.#H=/* @__PURE__ */ new Map,this.#U=null,this.#W=null,this.#G=!1,this.#K=null,this.#q=null,this.#J=!1,this.#Y=null,this.#Q=null,this.#$=null,this.#ee=new Li,this.#te=Promise.resolve(),this.#ne=null,this.#re=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Ii(()=>this.#ie()),this.#Ze=null,this.#Qe=0,this.handleEvent=(e,t=!1)=>{if(this.#m){this.#m.push({event:e,readOnlyReplay:t});return}let n=this.#re,r=!1;if(n&&(e.type===`error`||e.type===`status`&&e.status===`error`?n.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id),r=!0)),e.type===`message`){this.#e&&!t&&e.message.role===`assistant`&&this.#t?.messageIds.add(e.message.id),this.upsertMessage(e.message),(e.message.agentMetadata?.awaitingLocalTool||e.message.variant===`approval`&&e.message.approval?.status===`pending`)&&this.#dt(`needs-attention`),r&&n.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#s.set(e.message.id,this.#c),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#d=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&K().catch(()=>{});let i=e.message.toolCall,a=!!i?.name&&(it(i.name)||i.name===`suggest_replies`&&gt(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&a&&!t&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#et(e.message),e.message.agentMetadata?.executionId&&(!this.agentExecution||this.agentExecution.executionId!==e.message.agentMetadata.executionId?this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0}:e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration))}else if(e.type===`cursor`)this.#p=e.checkpoint,this.#ht(e.id);else if(e.type===`status`){if(e.executionId&&(this.agentExecution={executionId:e.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#dt(`running`)),e.status===`idle`&&!e.terminal&&this.#gt()){this.#vt();return}if(e.status===`error`?this.#dt(`failed`):e.terminal&&e.status===`idle`&&this.#dt(`completed`),this.#Ot(e.status),e.status===`connecting`)this.#kt(!0);else if(e.status===`idle`||e.status===`error`){this.#_t()||this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null,this.#He(),this.#Le());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#tt()}}else e.type===`error`?(this.#dt(`failed`),this.#Ot(`error`),this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!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.#ct(e)},this.historyInternals=this.#ue(n),this.messages=[...e.initialMessages??[]].map(e=>({...A(e),sequence:e.sequence??this.#It()})),this.messages=this.#Rt(this.messages),this.client=new pi(e,this.historyInternals),this.#Oe(),this.#Xe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#b=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#st(),this.callbacks.onStatusChanged(this.status),this.#Z(),this.#X()}#X(){this.config.voiceRecognition?.provider&&wr().catch(()=>{})}#Z(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&Vi().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 U(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#D}getVoiceStatus(){return this.#O}getVoiceNotice(){return this.#C?.takeNotice?.()??null}getVoiceDisclosure(){return this.#C?.getDisclosure?.()??null}getVoiceLevel(){return this.#C?.onLevel?this.#E:null}getVoiceInterruptionMode(){return this.#C?.getInterruptionMode?this.#C.getInterruptionMode():`none`}stopVoicePlayback(){this.#C?.stopPlayback&&(this.#ee.cancel(),this.#ne?.cancel(),this.#C.stopPlayback())}isBargeInActive(){return this.#C?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#C?.deactivateBargeIn&&await this.#C.deactivateBargeIn()}#Q;#$;#ee;#te;#ne;#re;#ie(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Fi.isSupported()?new Fi({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return Vi().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#te,r=++this.#T;this.#w=wr().then(async e=>{await n,r===this.#T&&this.#ae(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#T&&(this.#w=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#ae(e,t){this.#C=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#C,generation:()=>n.#T,get keyed(){return n.#ne},set keyed(e){n.#ne=e},get pendingUser(){return n.#Q},set pendingUser(e){n.#Q=e},get pendingAssistant(){return n.#$},set pendingAssistant(e){n.#$=e},turns:()=>n.#ee,busy:()=>n.#oe(),setStreaming:e=>n.#kt(e),setDelegation:e=>{n.#re=e},setLevel:e=>{n.#E=e},setStatus:e=>{n.#O=e,n.#D=e===`listening`},settlePending:e=>n.#ce(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){let e=this.#T;if(!this.#C&&this.#w&&await this.#w,e===this.#T){if(!this.#C)console.error(`Voice not configured`);else if(this.#D)await this.#C.stopListening();else{this.stopSpeaking();try{await this.#C.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}}prewarmVoice(){if(!Dr(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#T,t=()=>{let t=this.#C;t?.prewarm&&e===this.#T&&(this.#D||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#C&&this.#w?this.#w.then(t,()=>{}):t()}#oe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#f||this.status===`resuming`}cleanupVoice(){let e=this.#C!==null;if(this.#T++,this.#w=null,this.#C){let e=this.#C;this.#C=null,this.#te=this.#se(e)}this.#D=!1,this.#O=`disconnected`,this.#ce(!0),this.#ne?.settle(),this.#ne=null,this.#ee=new Li,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#se(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#ce(e){let t=e?this.#Q:null,n=this.#$;(t||n)&&(n&&this.#ee.cancel(),e&&(this.#Q=null),this.#$=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#kt(!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.#W=this.historyInternals.getStoredConversationRevision?.()??null,this.#G=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#le(e,t)}#le(e,t=!this.messages.length){if(this.#I||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#It()};this.#Pt(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){e.historyProvider!==this.historyInternals.historyProvider&&(this.#M+=1,this.#N+=1,this.config.backgroundConversations&&this.cancel(),this.#ut()),this.historyInternals=this.#ue(e),this.client.setHistoryInternals(this.historyInternals),this.#Oe()}destroy(){this.#ut(),this.#M+=1,this.#N+=1,this.cancel(),this.#t=void 0,this.cleanupVoice(),this.#K?.(),this.#K=null,this.#q=null}#ue(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#De(e),t?.(e)}}}get#de(){return this.historyInternals.historyProvider??null}#fe(){let e=this.#de;if(!e)throw new qi(`history_unavailable`,`No conversation history provider is installed`);return e}#pe(e){let t=this.#fe(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new Ot(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#k,conversationRevision:this.#A,nextMessageCursor:this.#j,recovery:this.#L,sendBlocked:this.#R}}getActiveConversationId(){return this.#k}#me(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#he(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#z;e&&await e.catch(()=>{});let t=this.#V;t&&await t.catch(()=>{})}#ge(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new qi(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#fe().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#pe(e?.scope)})}async openConversation(e,t){let n=this.#fe();t?.busy===`background`&&this.assertBackgroundSwitchable(),t?.busy===`stop`&&this.cancel(),t?.busy!==`background`&&this.#ge();let r=this.#pe(t?.scope),i=++this.#M,a=this.#N;if(t?.busy===`background`&&await this.#lt(),await this.awaitHistorySettled(),i!==this.#M)throw new qi(`superseded`,`A later selection won`);let o=await n.getPage(e,{context:r});if(i!==this.#M)throw new qi(`superseded`,`A later selection won`);let s=await n.prepareOpen(e,{context:r}),c=this.#F.then(async()=>{if(i!==this.#M)throw s.discard(),new qi(`superseded`,`A later selection won`);t?.busy===`stop`&&this.cancel();try{t?.busy===`background`?this.assertBackgroundSwitchable():this.#ge()}catch(e){throw s.discard(),e}let r=this.#k,c=this.#e;t?.onBeforeCommit?.(),t?.busy===`background`&&(this.#m=[]),this.#I=!0,this.#P=a;try{if(await this.#Ce(s),a!==this.#N||n!==this.#de)throw new qi(`superseded`,`The history identity changed`);if(t?.busy===`background`&&r&&this.#u){let e={conversationId:r,handle:this.#u,messages:this.messages,artifacts:this.getArtifacts(),selectedArtifactId:this.#b,streamCheckpoint:this.#p};this.#h?.save(e)}this.#k=s.conversationId||e,this.#A=s.conversationRevision||o.conversationRevision||null,this.#j=o.nextCursor,this.#L=null,this.#R=!1,this.#Te();for(let e of o.messages)this.#H.set(e.id,e.content);this.#we();let i=this.#h?.take(this.#k);return this.hydrateMessages(i?.messages??o.messages),i&&(this.hydrateArtifacts(i.artifacts,i.selectedArtifactId,!0),this.#mt(i)),t?.onCommitted?.(),this.#me(),{summary:o.summary,nextMessageCursor:o.nextCursor}}finally{this.#I=!1,this.#P=null;let e=this.#m;if(this.#m=null,e&&this.#e===c&&this.#k===r)for(let{event:t,readOnlyReplay:n}of e)this.handleEvent(t,n)}}),l=c.then(()=>{},()=>{});this.#F=l,this.#z=l;try{return await c}finally{this.#z===l&&(this.#z=null)}}loadOlderMessages(e,t,n){let r=this.#fe(),i=this.#pe(n?.scope),a=t??this.#j;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#B.get(o);if(s)return s;let c=this.#_e(r,e,a,i).finally(()=>{this.#B.delete(o)});return this.#B.set(o,c),c}async#_e(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#k&&this.#k!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ve(a.messages),s=Rt(this.messages,o);this.messages=this.#Rt(s.map(e=>this.#Ft(e))),this.#j=a.nextCursor;for(let e of a.messages)this.#H.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#me(),{messages:o,nextMessageCursor:a.nextCursor}}#ve(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&ct(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return A(e)})}async startNewConversation(e){let t=this.#fe(),n=this.#pe(e?.scope),r=++this.#M,i=this.#N;await this.awaitHistorySettled();let a=await t.prepareStartNew({context:n}),o=this.#F.then(async()=>{if(r!==this.#M)throw a.discard(),new qi(`superseded`,`A later action won`);e?.onBeforeCommit?.(),this.#I=!0,this.#P=i;try{await this.#Ce(a)}finally{this.#I=!1,this.#P=null}if(i!==this.#N||t!==this.#de)throw new qi(`superseded`,`The history identity changed`);this.#Ee(!1,!0),this.#k=a.conversationId||null,this.#A=a.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.clientSession&&this.#le(this.clientSession),e?.onCommitted?.(),this.#me()}),s=o.then(()=>{},()=>{});this.#F=s,this.#z=s;try{await o}finally{this.#z===s&&(this.#z=null)}}async#ye(e,t=!1){this.#Ee(t),await this.#Ce(e),this.#k=e.conversationId||null,this.#A=e.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.#me()}async deleteConversation(e,t){let n=this.#fe(),r=this.#pe(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),this.#h?.clear(e),e===this.#k&&await this.#be(r)}async updateConversation(e,t,n){let r=this.#fe();if(!r.update)throw new qi(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#pe(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#de?.update==`function`}async clearConversationHistory(e){let t=this.#fe(),n=this.#pe(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return this.#ut(),await this.#be(n),r}async resetHistoryDevice(){let e=this.#fe();if(!e.resetDevice)throw new qi(`history_unavailable`,`This history provider cannot reset the device`);this.#ut(),this.#M+=1,this.#N+=1,this.#V=null;try{return await e.resetDevice()}finally{this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#R=!1,this.#me()}}async#be(e){this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#R=!0,this.#L=null,this.#me(),await this.#xe(e)}async#xe(e){let t=this.#de;if(!t)this.#R=!1,this.#me();else try{let n=await t.prepareStartNew({context:e});await this.#ye(n)}catch{this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#Se(){if(this.#L===`new_conversation_required`&&this.#de&&(this.#L=null,await this.#xe(this.#pe()),this.#L===`new_conversation_required`))throw new qi(`new_conversation_required`,`A new conversation is required before sending`)}async#Ce(e){if(await e.commit(),this.#P!==null&&this.#P!==this.#N)return;let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){(this.#P===null||this.#P===this.#N)&&(this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#k=e.conversationId,this.#A=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#I||this.#le(e))}#we(){this.#k?this.config.setStoredConversationId?.(this.#k):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#A),this.historyInternals.setStoredMessageCursor?.(this.#j)}#Te(){this.#t=void 0,this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#ot(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#H.clear(),this.#Pe(null)}#Ee(e=!1,t=!1){this.client.cancelStreams(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#Tt(),this.#rt(),this.#Qe++,this.messages=[],this.#Te(),this.#B.clear(),t||this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),e||this.#kt(!1),this.#Ot(`idle`),this.callbacks.onMessagesChanged([...this.messages]),e||this.#a(`cancel`)}#De(e){this.#ut(),this.#M+=1,this.#N+=1,this.#V=null,this.#R=!0,this.#Ee(),this.#k=e.conversationId,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.#he(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#z=Promise.resolve().then(()=>{this.#R=!1,this.#z=null,this.#me()})}#Oe(){let e=this.historyInternals.visitorStore??null;e!==this.#q&&(this.#K?.(),this.#K=null,this.#q=e,e&&(this.#K=e.subscribe(e=>this.#ke(e))))}#ke(e){if(e.source!==`external`||e.previousToken===null)return;this.#ut(),this.clientSession=null,this.client.handleExternalCredentialChange(),this.#M+=1,this.#N+=1,this.#V=null,this.#J=!0,this.#Y=null;let t=this.messages.length>0;t||this.#k!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#Ee():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#B.clear(),this.#Pe(null)),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.callbacks.onHistoryScopeInvalidated?.(),t&&this.#he(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#Ae(){return this.#J?(this.#Y||=this.#je().finally(()=>{this.#Y=null}),this.#Y):Promise.resolve()}async#je(){if(!this.isClientTokenMode())this.#J=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#J=!1}catch{}}reconcileBootConversation(e){let t=this.#de,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#k;if(!t||!n)return Promise.resolve();let r=this.#pe(e?.scope);this.#R=!0,this.#me();let i=this.#Me(t,n,r).finally(()=>{this.#R=this.#L!==null,this.#z===i&&(this.#z=null),this.#me()});return this.#z=i,i}async#Me(e,t,n){this.#k=t;let r=this.clientSession?.conversationRevision??this.#A??null,i=this.#G?this.#W:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#G=!1,this.#j=this.historyInternals.getStoredMessageCursor?.()??this.#j,await this.replayPendingProjections(),r&&i&&r===i){this.#A=r;return}let a=await e.getPage(t,{context:n}),o=this.#ve(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#Ft(e));else{let e=this.#u?this.#d:null,t=this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l);u=Rt(t,o).map(e=>this.#Ft(e))}this.#j=a.nextCursor,this.#A=a.conversationRevision||r||null,this.#H.clear();for(let e of a.messages)this.#H.set(e.id,e.content);this.#we(),this.#t=void 0,this.messages=this.#Rt(u),this.callbacks.onMessagesChanged([...this.messages])}#Ne(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#Pe(e){this.#U=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Fe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#U}#Ie(e){if(this.#Ne())for(let t of e){let e=zt(t);e!==void 0&&this.#H.set(t.id,e)}}#Le(){if(!this.#Ne())return;let e=this.#k;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=zt(e);n!==void 0&&this.#H.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#Pe({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Re(e,t))}#Re(e,t){let n=(this.#V??Promise.resolve()).catch(()=>{}).then(()=>this.#ze(e,t,!1)).finally(()=>{this.#V===n&&(this.#V=null)});this.#V=n}async#ze(e,t,n){if(this.#k!==e)return;let r=t.filter(e=>this.#H.get(e.id)!==e.displayContent);if(r.length===0)this.#Ve(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#H.set(e.id,e.displayContent);this.#k===e&&n&&(this.#A=n),this.#Ve(e,t)}catch(i){if(!n&&this.#Be(i)){await this.#ze(e,r,!0);return}if(i instanceof ui&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#Ve(e,t);return}this.#he(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Be(e){return e instanceof ui?e.code===`request_failed`:e instanceof Error}#Ve(e,t){let n=this.#Fe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#Pe(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#Ne())return;let e=this.#Fe();if(!e)return;if(this.#k&&e.conversationId!==this.#k){this.#Pe(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#Pe(null):(this.#Re(e.conversationId,t),await this.#V?.catch(()=>{}))}#He(){this.#k&&(this.#A=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Ue(){await this.awaitHistorySettled(),await this.#Ae(),this.#L===`new_conversation_required`&&await this.#Se()}static#We(e){return e instanceof ui&&e.code===`conversation_deleted`}async#Ge(t,n,r,i,a){let o=this.#e,s=e=>{this.#e===o&&this.handleEvent(e)};this.#Ie(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s);return}catch(t){if(n.signal.aborted||this.#e!==o||!e.#We(t))throw t;let c=await this.#Ke(i);if(!c)throw t;this.#Ie([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s)}}async#Ke(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(!0),this.#k=null,this.#A=null,this.#j=null,this.#I=!0;try{let e=this.#de;if(e){let t=await e.prepareStartNew({context:this.#pe()});await this.#ye(t,!0)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#I=!1}return this.#Pt(n),this.#kt(!0),this.#he(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=Er(this.config,n),i=Ki(this.config,n);i&&(this.cancel(),this.#ut()),this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&kr(n)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#at();return}this.#rt(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.#M+=1,this.#N+=1,this.client=new pi(this.config,this.historyInternals),a&&this.#at(),this.#Xe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}getRunActivity(){return this.#t}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let t=this.#qe(e);return this.upsertMessage(t),t}#qe(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e;return{id:a??(t===`user`?ut():t===`assistant`?dt():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#It(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d},...e.dispatchError!==void 0&&{dispatchError:e.dispatchError}}}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=e.map(e=>this.#qe(e));return this.messages=this.#Rt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}updateComponentProps(e,t){let n=this.messages.find(t=>t.id===e),r=n&&Ni(n);return!n||n.role!==`assistant`||n.variant||!r?!1:(this.upsertMessage({...n,rawContent:JSON.stringify({text:n.content,component:r.component,props:t})}),!0)}removeComponentMessage(e){let t=this.messages.find(t=>t.id===e);return!t||t.role!==`assistant`||t.variant||!Ni(t)?!1:(this.messages=this.messages.filter(t=>t.id!==e),this.callbacks.onMessagesChanged([...this.messages]),!0)}async#Je(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
5
+ `),t.trim()}const Vi=()=>import(`./chunk-59UOGW9N.js`),{setLoader:Hi,load:Ui}=v({fallbackImport:()=>import(`./chunk-DvGdwBMD.js`)}),Wi=Ui,Gi=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.backgroundConversations.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function Ki(e,t){return Gi.some(n=>e[n]!==t[n])}var qi=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function Ji(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=n.message.trim(),i=/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.?)$/i.test(r),a=/^(Chat backend|Agent execution) request failed: \d{3}\b/.test(r),o=i?`Sorry: I couldn't reach the assistant. Please check your connection and try again.`:a?`Sorry: the chat service couldn't complete the request. Please try again.`:`Sorry: the chat encountered an unexpected error. Please reload the page and try again.`;return r?`${o}\n\n_Details: ${r}_`:o}const Yi=e=>it(e)||e===`suggest_replies`;var Xi=class e{#e;#t;#n;#r;#i(e){if(this.#a(`cancel`),this.#n=!1,this.#e={runId:`run-${dt()}`,timestamp:Date.now()},this.#t={run:this.#e,messageIds:/* @__PURE__ */ new Set},e)for(let t of this.messages)t.role===`assistant`&&t.agentMetadata?.executionId===e&&this.#t.messageIds.add(t.id);this.callbacks.onRunStarted?.({...this.#e})}#a(e,t=this.#e){if(t!==this.#e)return;this.#r!==null&&clearTimeout(this.#r),this.#r=null;let n=this.#e;if(this.#e=null,n){let t=n;t.timestamp=Date.now(),t.outcome=e,this.callbacks.onRunFinished?.(t)}}#o(){if(!this.#e||this.#r!==null)return;let e=this.#e;this.#r=setTimeout(()=>{this.#r=null,this.#e===e&&(!this.#n&&(this.streaming||this.#f||this.#_t()||this.webMcpAwaitBatches.size||this.webMcpResolveControllers.size)||this.#a(this.#n?`error`:`success`))},0)}#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.#e=null,this.#n=!1,this.#r=null,this.streaming=!1,this.#s=/* @__PURE__ */ new Map,this.abortController=null,this.#l=Date.now(),this.clientSession=null,this.agentExecution=null,this.#u=null,this.#d=null,this.#f=!1,this.#m=null,this.#h=null,this.#g=null,this.#_=null,this.#v=null,this.#y=null,this.artifacts=/* @__PURE__ */ new Map,this.#b=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#x=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#S=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#C=null,this.#w=null,this.#T=0,this.#E=0,this.#D=!1,this.#O=`disconnected`,this.#k=null,this.#A=null,this.#j=null,this.#M=0,this.#N=0,this.#P=null,this.#F=Promise.resolve(),this.#I=!1,this.#L=null,this.#R=!1,this.#z=null,this.#B=/* @__PURE__ */ new Map,this.#V=null,this.#H=/* @__PURE__ */ new Map,this.#U=null,this.#W=null,this.#G=!1,this.#K=null,this.#q=null,this.#J=!1,this.#Y=null,this.#Q=null,this.#$=null,this.#ee=new Li,this.#te=Promise.resolve(),this.#ne=null,this.#re=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Ii(()=>this.#ie()),this.#Ze=null,this.#Qe=0,this.handleEvent=(e,t=!1)=>{if(this.#m){this.#m.push({event:e,readOnlyReplay:t});return}let n=this.#re,r=!1;if(n&&(e.type===`error`||e.type===`status`&&e.status===`error`?n.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id),r=!0)),e.type===`message`){this.#e&&!t&&e.message.role===`assistant`&&this.#t?.messageIds.add(e.message.id),this.upsertMessage(e.message),(e.message.agentMetadata?.awaitingLocalTool||e.message.variant===`approval`&&e.message.approval?.status===`pending`)&&this.#dt(`needs-attention`),r&&n.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#s.set(e.message.id,this.#c),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#d=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&K().catch(()=>{});let i=e.message.toolCall,a=!!i?.name&&(it(i.name)||i.name===`suggest_replies`&&gt(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&a&&!t&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#et(e.message),e.message.agentMetadata?.executionId&&(!this.agentExecution||this.agentExecution.executionId!==e.message.agentMetadata.executionId?this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0}:e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration))}else if(e.type===`cursor`)this.#p=e.checkpoint,this.#ht(e.id);else if(e.type===`status`){if(e.executionId&&(this.agentExecution={executionId:e.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#dt(`running`)),e.status===`idle`&&!e.terminal&&this.#gt()){this.#vt();return}if(e.status===`error`?this.#dt(`failed`):e.terminal&&e.status===`idle`&&this.#dt(`completed`),this.#Ot(e.status),e.status===`connecting`)this.#kt(!0);else if(e.status===`idle`||e.status===`error`){this.#_t()||this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null,this.#He(),this.#Le());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#tt()}}else e.type===`error`?(this.#dt(`failed`),this.#Ot(`error`),this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!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.#ct(e)},this.historyInternals=this.#ue(n),this.messages=[...e.initialMessages??[]].map(e=>({...A(e),sequence:e.sequence??this.#It()})),this.messages=this.#Rt(this.messages),this.client=new pi(e,this.historyInternals),this.#Oe(),this.#Xe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#b=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#st(),this.callbacks.onStatusChanged(this.status),this.#Z(),this.#X()}#X(){this.config.voiceRecognition?.provider&&wr().catch(()=>{})}#Z(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&Vi().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 U(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#D}getVoiceStatus(){return this.#O}getVoiceNotice(){return this.#C?.takeNotice?.()??null}getVoiceDisclosure(){return this.#C?.getDisclosure?.()??null}getVoiceLevel(){return this.#C?.onLevel?this.#E:null}getVoiceInterruptionMode(){return this.#C?.getInterruptionMode?this.#C.getInterruptionMode():`none`}stopVoicePlayback(){this.#C?.stopPlayback&&(this.#ee.cancel(),this.#ne?.cancel(),this.#C.stopPlayback())}isBargeInActive(){return this.#C?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#C?.deactivateBargeIn&&await this.#C.deactivateBargeIn()}#Q;#$;#ee;#te;#ne;#re;#ie(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Fi.isSupported()?new Fi({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return Vi().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#te,r=++this.#T;this.#w=wr().then(async e=>{await n,r===this.#T&&this.#ae(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#T&&(this.#w=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#ae(e,t){this.#C=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#C,generation:()=>n.#T,get keyed(){return n.#ne},set keyed(e){n.#ne=e},get pendingUser(){return n.#Q},set pendingUser(e){n.#Q=e},get pendingAssistant(){return n.#$},set pendingAssistant(e){n.#$=e},turns:()=>n.#ee,busy:()=>n.#oe(),setStreaming:e=>n.#kt(e),setDelegation:e=>{n.#re=e},setLevel:e=>{n.#E=e},setStatus:e=>{n.#O=e,n.#D=e===`listening`},settlePending:e=>n.#ce(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){let e=this.#T;if(!this.#C&&this.#w&&await this.#w,e===this.#T){if(!this.#C)console.error(`Voice not configured`);else if(this.#D)await this.#C.stopListening();else{this.stopSpeaking();try{await this.#C.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}}prewarmVoice(){if(!Dr(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#T,t=()=>{let t=this.#C;t?.prewarm&&e===this.#T&&(this.#D||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#C&&this.#w?this.#w.then(t,()=>{}):t()}#oe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#f||this.status===`resuming`}cleanupVoice(){let e=this.#C!==null;if(this.#T++,this.#w=null,this.#C){let e=this.#C;this.#C=null,this.#te=this.#se(e)}this.#D=!1,this.#O=`disconnected`,this.#ce(!0),this.#ne?.settle(),this.#ne=null,this.#ee=new Li,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#se(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#ce(e){let t=e?this.#Q:null,n=this.#$;(t||n)&&(n&&this.#ee.cancel(),e&&(this.#Q=null),this.#$=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#kt(!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.#W=this.historyInternals.getStoredConversationRevision?.()??null,this.#G=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#le(e,t)}#le(e,t=!this.messages.length){if(this.#I||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#It()};this.#Pt(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){e.historyProvider!==this.historyInternals.historyProvider&&(this.#M+=1,this.#N+=1,this.config.backgroundConversations&&this.cancel(),this.#ut()),this.historyInternals=this.#ue(e),this.client.setHistoryInternals(this.historyInternals),this.#Oe()}destroy(){this.#ut(),this.#M+=1,this.#N+=1,this.cancel(),this.#t=void 0,this.cleanupVoice(),this.#K?.(),this.#K=null,this.#q=null}#ue(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#De(e),t?.(e)}}}get#de(){return this.historyInternals.historyProvider??null}#fe(){let e=this.#de;if(!e)throw new qi(`history_unavailable`,`No conversation history provider is installed`);return e}#pe(e){let t=this.#fe(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new Ot(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#k,conversationRevision:this.#A,nextMessageCursor:this.#j,recovery:this.#L,sendBlocked:this.#R}}getActiveConversationId(){return this.#k}#me(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#he(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#z;e&&await e.catch(()=>{});let t=this.#V;t&&await t.catch(()=>{})}#ge(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new qi(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#fe().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#pe(e?.scope)})}async openConversation(e,t){let n=this.#fe();t?.busy===`background`&&this.assertBackgroundSwitchable(),t?.busy===`stop`&&this.cancel(),t?.busy!==`background`&&this.#ge();let r=this.#pe(t?.scope),i=++this.#M,a=this.#N;if(t?.busy===`background`&&await this.#lt(),await this.awaitHistorySettled(),i!==this.#M)throw new qi(`superseded`,`A later selection won`);let o=await n.getPage(e,{context:r});if(i!==this.#M)throw new qi(`superseded`,`A later selection won`);let s=await n.prepareOpen(e,{context:r}),c=this.#F.then(async()=>{if(i!==this.#M)throw s.discard(),new qi(`superseded`,`A later selection won`);t?.busy===`stop`&&this.cancel();try{t?.busy===`background`?this.assertBackgroundSwitchable():this.#ge()}catch(e){throw s.discard(),e}let r=this.#k,c=this.#e;t?.onBeforeCommit?.(),t?.busy===`background`&&(this.#m=[]),this.#I=!0,this.#P=a;try{if(await this.#Ce(s),a!==this.#N||n!==this.#de)throw new qi(`superseded`,`The history identity changed`);if(t?.busy===`background`&&r&&this.#u){let e={conversationId:r,handle:this.#u,messages:this.messages,artifacts:this.getArtifacts(),selectedArtifactId:this.#b,streamCheckpoint:this.#p};this.#h?.save(e)}this.#k=s.conversationId||e,this.#A=s.conversationRevision||o.conversationRevision||null,this.#j=o.nextCursor,this.#L=null,this.#R=!1,this.#Te();for(let e of o.messages)this.#H.set(e.id,e.content);this.#we();let i=this.#h?.take(this.#k);return this.hydrateMessages(i?.messages??o.messages),i&&(this.hydrateArtifacts(i.artifacts,i.selectedArtifactId,!0),this.#mt(i)),t?.onCommitted?.(),this.#me(),{summary:o.summary,nextMessageCursor:o.nextCursor}}finally{this.#I=!1,this.#P=null;let e=this.#m;if(this.#m=null,e&&this.#e===c&&this.#k===r)for(let{event:t,readOnlyReplay:n}of e)this.handleEvent(t,n)}}),l=c.then(()=>{},()=>{});this.#F=l,this.#z=l;try{return await c}finally{this.#z===l&&(this.#z=null)}}loadOlderMessages(e,t,n){let r=this.#fe(),i=this.#pe(n?.scope),a=t??this.#j;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#B.get(o);if(s)return s;let c=this.#_e(r,e,a,i).finally(()=>{this.#B.delete(o)});return this.#B.set(o,c),c}async#_e(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#k&&this.#k!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ve(a.messages),s=Rt(this.messages,o);this.messages=this.#Rt(s.map(e=>this.#Ft(e))),this.#j=a.nextCursor;for(let e of a.messages)this.#H.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#me(),{messages:o,nextMessageCursor:a.nextCursor}}#ve(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&ct(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return A(e)})}async startNewConversation(e){let t=this.#fe(),n=this.#pe(e?.scope),r=++this.#M,i=this.#N;await this.awaitHistorySettled();let a=await t.prepareStartNew({context:n}),o=this.#F.then(async()=>{if(r!==this.#M)throw a.discard(),new qi(`superseded`,`A later action won`);e?.onBeforeCommit?.(),this.#I=!0,this.#P=i;try{await this.#Ce(a)}finally{this.#I=!1,this.#P=null}if(i!==this.#N||t!==this.#de)throw new qi(`superseded`,`The history identity changed`);this.#Ee(!1,!0),this.#k=a.conversationId||null,this.#A=a.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.clientSession&&this.#le(this.clientSession),e?.onCommitted?.(),this.#me()}),s=o.then(()=>{},()=>{});this.#F=s,this.#z=s;try{await o}finally{this.#z===s&&(this.#z=null)}}async#ye(e,t=!1){this.#Ee(t),await this.#Ce(e),this.#k=e.conversationId||null,this.#A=e.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.#me()}async deleteConversation(e,t){let n=this.#fe(),r=this.#pe(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),this.#h?.clear(e),e===this.#k&&await this.#be(r)}async updateConversation(e,t,n){let r=this.#fe();if(!r.update)throw new qi(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#pe(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#de?.update==`function`}async clearConversationHistory(e){let t=this.#fe(),n=this.#pe(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return this.#ut(),await this.#be(n),r}async resetHistoryDevice(){let e=this.#fe();if(!e.resetDevice)throw new qi(`history_unavailable`,`This history provider cannot reset the device`);this.#ut(),this.#M+=1,this.#N+=1,this.#V=null;try{return await e.resetDevice()}finally{this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#R=!1,this.#me()}}async#be(e){this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#R=!0,this.#L=null,this.#me(),await this.#xe(e)}async#xe(e){let t=this.#de;if(!t)this.#R=!1,this.#me();else try{let n=await t.prepareStartNew({context:e});await this.#ye(n)}catch{this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#Se(){if(this.#L===`new_conversation_required`&&this.#de&&(this.#L=null,await this.#xe(this.#pe()),this.#L===`new_conversation_required`))throw new qi(`new_conversation_required`,`A new conversation is required before sending`)}async#Ce(e){if(await e.commit(),this.#P!==null&&this.#P!==this.#N)return;let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){(this.#P===null||this.#P===this.#N)&&(this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#k=e.conversationId,this.#A=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#I||this.#le(e))}#we(){this.#k?this.config.setStoredConversationId?.(this.#k):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#A),this.historyInternals.setStoredMessageCursor?.(this.#j)}#Te(){this.#t=void 0,this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#ot(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#H.clear(),this.#Pe(null)}#Ee(e=!1,t=!1){this.client.cancelStreams(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#Tt(),this.#rt(),this.#Qe++,this.messages=[],this.#Te(),this.#B.clear(),t||this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),e||this.#kt(!1),this.#Ot(`idle`),this.callbacks.onMessagesChanged([...this.messages]),e||this.#a(`cancel`)}#De(e){this.#ut(),this.#M+=1,this.#N+=1,this.#V=null,this.#R=!0,this.#Ee(),this.#k=e.conversationId,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.#he(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#z=Promise.resolve().then(()=>{this.#R=!1,this.#z=null,this.#me()})}#Oe(){let e=this.historyInternals.visitorStore??null;e!==this.#q&&(this.#K?.(),this.#K=null,this.#q=e,e&&(this.#K=e.subscribe(e=>this.#ke(e))))}#ke(e){if(e.source!==`external`||e.previousToken===null)return;this.#ut(),this.clientSession=null,this.client.handleExternalCredentialChange(),this.#M+=1,this.#N+=1,this.#V=null,this.#J=!0,this.#Y=null;let t=this.messages.length>0;t||this.#k!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#Ee():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#B.clear(),this.#Pe(null)),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.callbacks.onHistoryScopeInvalidated?.(),t&&this.#he(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#Ae(){return this.#J?(this.#Y||=this.#je().finally(()=>{this.#Y=null}),this.#Y):Promise.resolve()}async#je(){if(!this.isClientTokenMode())this.#J=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#J=!1}catch{}}reconcileBootConversation(e){let t=this.#de,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#k;if(!t||!n)return Promise.resolve();let r=this.#pe(e?.scope);this.#R=!0,this.#me();let i=this.#Me(t,n,r).finally(()=>{this.#R=this.#L!==null,this.#z===i&&(this.#z=null),this.#me()});return this.#z=i,i}async#Me(e,t,n){this.#k=t;let r=this.clientSession?.conversationRevision??this.#A??null,i=this.#G?this.#W:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#G=!1,this.#j=this.historyInternals.getStoredMessageCursor?.()??this.#j,await this.replayPendingProjections(),r&&i&&r===i){this.#A=r;return}let a=await e.getPage(t,{context:n}),o=this.#ve(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#Ft(e));else{let e=this.#u?this.#d:null,t=this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l);u=Rt(t,o).map(e=>this.#Ft(e))}this.#j=a.nextCursor,this.#A=a.conversationRevision||r||null,this.#H.clear();for(let e of a.messages)this.#H.set(e.id,e.content);this.#we(),this.#t=void 0,this.messages=this.#Rt(u),this.callbacks.onMessagesChanged([...this.messages])}#Ne(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#Pe(e){this.#U=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Fe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#U}#Ie(e){if(this.#Ne())for(let t of e){let e=zt(t);e!==void 0&&this.#H.set(t.id,e)}}#Le(){if(!this.#Ne())return;let e=this.#k;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=zt(e);n!==void 0&&this.#H.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#Pe({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Re(e,t))}#Re(e,t){let n=(this.#V??Promise.resolve()).catch(()=>{}).then(()=>this.#ze(e,t,!1)).finally(()=>{this.#V===n&&(this.#V=null)});this.#V=n}async#ze(e,t,n){if(this.#k!==e)return;let r=t.filter(e=>this.#H.get(e.id)!==e.displayContent);if(r.length===0)this.#Ve(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#H.set(e.id,e.displayContent);this.#k===e&&n&&(this.#A=n),this.#Ve(e,t)}catch(i){if(!n&&this.#Be(i)){await this.#ze(e,r,!0);return}if(i instanceof ui&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#Ve(e,t);return}this.#he(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Be(e){return e instanceof ui?e.code===`request_failed`:e instanceof Error}#Ve(e,t){let n=this.#Fe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#Pe(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#Ne())return;let e=this.#Fe();if(!e)return;if(this.#k&&e.conversationId!==this.#k){this.#Pe(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#Pe(null):(this.#Re(e.conversationId,t),await this.#V?.catch(()=>{}))}#He(){this.#k&&(this.#A=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Ue(){await this.awaitHistorySettled(),await this.#Ae(),this.#L===`new_conversation_required`&&await this.#Se()}static#We(e){return e instanceof ui&&e.code===`conversation_deleted`}async#Ge(t,n,r,i,a){let o=this.#e,s=e=>{this.#e===o&&this.handleEvent(e)};this.#Ie(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s);return}catch(t){if(n.signal.aborted||this.#e!==o||!e.#We(t))throw t;let c=await this.#Ke(i);if(!c)throw t;this.#Ie([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s)}}async#Ke(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(!0),this.#k=null,this.#A=null,this.#j=null,this.#I=!0;try{let e=this.#de;if(e){let t=await e.prepareStartNew({context:this.#pe()});await this.#ye(t,!0)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#I=!1}return this.#Pt(n),this.#kt(!0),this.#he(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=Er(this.config,n),i=Ki(this.config,n);i&&(this.cancel(),this.#ut()),this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&kr(n)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#at();return}this.#rt(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.#M+=1,this.#N+=1,this.client=new pi(this.config,this.historyInternals),a&&this.#at(),this.#Xe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}getRunActivity(){return this.#t}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let t=this.#qe(e);return this.upsertMessage(t),t}#qe(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e;return{id:a??(t===`user`?ut():t===`assistant`?dt():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#It(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d},...e.dispatchError!==void 0&&{dispatchError:e.dispatchError}}}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=e.map(e=>this.#qe(e));return this.messages=this.#Rt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}updateComponentProps(e,t){let n=this.messages.find(t=>t.id===e),r=n&&Ni(n);return!n||n.role!==`assistant`||n.variant||!r?!1:(this.upsertMessage({...n,rawContent:JSON.stringify({text:n.content,component:r.component,props:t})}),!0)}removeComponentMessage(e){let t=this.messages.find(t=>t.id===e);return!t||t.role!==`assistant`||t.variant||!Ni(t)?!1:(this.messages=this.messages.filter(t=>t.id!==e),this.callbacks.onMessagesChanged([...this.messages]),!0)}async#Je(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
6
6
 
7
7
  `),a=[i,t].filter(Boolean).join(`
8
8
 
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}};const t=16e3,n=/* @__PURE__ */ new Map([[`idle_timeout`,`Voice call ended after a quiet period.`],[`max_duration`,`This voice call reached its time limit.`],[`provider_ended`,`The voice session ended.`],[`quota`,`Voice is unavailable right now.`],[`auth_expired`,`Voice session expired. Tap the mic to reconnect.`]]),r=[`provider_error`,`server_restart`],i=`Voice connection lost.`;function a(e,t){let n=t.slice(0,4e3).trim(),r=8e3-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>2e3&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
2
2
  `)}`]:[];return n&&a.push(n),a.join(`
3
3
 
4
- `)}function o(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===1380533830?new Uint8Array(e,44):new Uint8Array(e)}function s(e){let t=e.replace(/\/+$/,``);return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,`ws`):`${typeof window<`u`&&window.location?.protocol===`https:`?`wss:`:`ws:`}//${t}`}function c(e){return s(e).replace(/^ws/i,`http`)}function l(e){return typeof e!=`number`||!Number.isFinite(e)?3e4:Math.min(6e5,Math.max(3e4,Math.round(e)))}var u=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<3e4)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${c(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=l(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,5e3)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(e,t,n){let r=`partial_transcript,context`;this.bridge&&this.config?.clientDelegation!==!1&&(r+=`,client_delegation,delegation_update,delegation_read_back,delegation_stream`,this.bridge.clientTools?.()&&(r+=`,client_tools,prior_tool_results`)),n&&(r=`attach,${r}`);let i=new URLSearchParams({voiceProtocol:`runtype-browser-v1`,clientVersion:`persona/4.32.1`,voiceCapabilities:`full-duplex-v1`,clientCapabilities:r});return n?.forEach((e,t)=>i.set(t,e)),`${s(e)}/ws/agents/${encodeURIComponent(t)}/voice?${i}`}async startListening(){if(this.#l)return;let n=this.#A;n||(this.#k=!1,this.#D=null),this.#A=!1;let r=this.config?.agentId,a=this.config?.clientToken,o=this.config?.host;if(!r)throw Error(`Runtype voice requires an agentId`);if(!a)throw Error(`Runtype voice requires a clientToken`);if(!o)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let s=++this.#d;this.#f=!1,this.#l=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:t,channelCount:1,echoCancellation:!0}});if(s!==this.#d){c.getTracks().forEach(e=>e.stop());return}this.#r=c;let l=new(window.AudioContext||window.webkitAudioContext)({sampleRate:t});if(this.#t=l,l.state===`suspended`){if(await Promise.race([l.resume().catch(()=>{}),new Promise(e=>setTimeout(e,n?500:1e3))]),s!==this.#d)return;if(l.state!==`running`)throw Error(n?this.#D=`${i} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let u=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new e(24e3);if(s!==this.#d){u.destroy(),c.getTracks().forEach(e=>e.stop()),l.close().catch(()=>{});return}this.#c=u,this.#he(),this.#ie(l,c,s);let d=await this.#ee();if(s!==this.#d){d?.ws.close(1e3,`client ended call`);return}if(d){let{ws:e}=d;this.#e=e,this.#ne(e,s),d.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let f=new WebSocket(this.#te(o,r),[`runtype.bearer`,a]);f.binaryType=`arraybuffer`,this.#e=f,f.onopen=()=>{s===this.#d&&(this.#ae(f),this.#be(`listening`))},this.#ne(f,s)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let a=r.includes(e)&&!this.#k;if(this.#ye(),a)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${i} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(r.includes(e))return this.#D=i,this.#xe(/* @__PURE__ */ Error(i)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||n.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||`You're talking to an AI assistant. Voice is processed by OpenAI.`:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+2e3,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(4096,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>256e3;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*4));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[],priorToolResults:r.priorToolResults},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return a(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),2e3)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,54e4),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=o(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+300)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}},d=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}};function f(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new u(e.runtype);case`browser`:if(!d.isSupported())throw Error(`Browser speech recognition not supported`);return new d(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function p(e){if(e?.type===`custom`&&e.custom)return f({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return f({type:`runtype`,runtype:e.runtype});if(d.isSupported())return f({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function m(e){try{return p(e),!0}catch{return!1}}const h=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,``);var g=class{constructor(e){this.host=e,this.turns=/* @__PURE__ */ new Map,this.latestId=null,this.cancelled=/* @__PURE__ */ new Set}apply(e,t,n,r,i,a){let o=this.host;t=t.trim();let s=this.turns.get(r);if(s||(s={},this.turns.set(r,s),this.latestId=r),e===`user`){s.userFinal=n;let e=s.userId?o.find(s.userId):void 0;if(e){let r=s.userStartMs===void 0&&i!==void 0;r&&(s.userStartMs=i),o.upsert({...e,content:t,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else{s.userStartMs=i;let e=s.assistantId?o.find(s.assistantId):void 0;s.userId=o.inject({role:`user`,content:t,streaming:!1,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i)??e)}).id}}else if(!this.cancelled.has(r)){s.assistantFinal=n;let e=s.assistantId?o.find(s.assistantId):void 0;if(e){let r=s.assistantStartMs===void 0&&i!==void 0;r&&(s.assistantStartMs=i),o.upsert({...e,content:t,streaming:!n,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else t&&(s.assistantStartMs=i,s.assistantId=o.inject({role:`assistant`,content:t,streaming:!n,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i))}).id);n&&s.assistantId&&o.markSpoken(s.assistantId)}this.sync()}claimUserTurn(e,t=[]){let n=t[t.length-1];for(let e of t)e!==n&&(this.turns.has(e)||this.turns.set(e,{}),this.turns.get(e).claimed=!0);let r;if(n){if(r=this.turns.get(n),r||(r={},this.turns.set(n,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:`user`,content:e.trim()}).id)}else{let t=h(e),n=[...this.turns.values()].reverse().flatMap(e=>{let t=e.userId&&!e.claimed?this.host.find(e.userId):void 0;return t?[{turn:e,text:h(t.content)}]:[]}).filter(({text:e})=>e&&t);r=(n.find(({text:e})=>e===t)??n.find(({text:e})=>e.startsWith(t)||t.startsWith(e)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let e=this.inFlight();if(e.length===0){let t=this.awaiting();if(!t)return;e=[t]}for(let t of e)this.cancelled.add(t);this.closeReplies(e),this.sync()}fail(e){let t=this.awaiting(),n=this.inFlight();if(!t&&n.length===0)return;for(let e of n)this.turns.get(e).assistantFinal=!0;this.closeReplies(n);let r=this.host.inject({role:`assistant`,content:e,streaming:!1,voiceProcessing:!1}),i=t?this.turns.get(t):void 0;i&&(i.assistantId=r.id,i.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let e=this.pending(),t=/* @__PURE__ */ new Set;for(let e of this.turns.values())e.userId&&t.add(e.userId),e.assistantId&&(t.add(e.assistantId),this.host.markSpoken(e.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(t),e&&this.host.setStreaming(!1)}startedAfter(e){if(e===void 0)return;let t;for(let n of this.turns.values())for(let[r,i]of[[n.userId,n.userStartMs],[n.assistantId,n.assistantStartMs]])r&&i!==void 0&&i>e&&(!t||i<t.start)&&(t={start:i,id:r});return t&&this.host.find(t.id)}placeBefore(e){if(!e)return;let t=e.sequence??0,n=t-1;for(let r of this.turns.values())for(let i of[r.userId,r.assistantId]){let r=i?this.host.find(i):void 0,a=r?.sequence;r?.createdAt===e.createdAt&&a!==void 0&&a>n&&a<t&&(n=a)}return{createdAt:e.createdAt,sequence:(n+t)/2}}closeReplies(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.turns.get(n)?.assistantId;e&&(t.add(e),this.host.markSpoken(e))}t.size>0&&this.host.settle(t)}inFlight(){let e=[];for(let[t,n]of this.turns)n.assistantId&&!n.assistantFinal&&!this.cancelled.has(t)&&e.push(t);return e}awaiting(){let e=this.latestId;if(!e)return null;let t=this.turns.get(e);return t?.userFinal&&!t.assistantId&&!t.claimed&&!this.cancelled.has(e)?e:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}};const _=/* @__PURE__ */ new Set(/* @__PURE__ */ `mr,mrs,ms,dr,prof,sr,jr,st,mt,vs,etc,approx,inc,ltd,co,corp,no,nos,fig,ft,dept,est,min,max,e.g,i.e,a.m,p.m,u.s,u.k`.split(`,`)),v=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g;function y(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,``).toLowerCase();if(_.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let n=e.length-t.length;return n===0||/\n\s*$/.test(e.slice(0,n))}return!1}function*b(e,t){let n=new RegExp(v.source,`g`);for(let r=n.exec(e);r;r=n.exec(e)){let n=r[1];if(!e.slice(0,r.index+(n?.length??0)).trim()||n!==void 0&&(/^[,;:]$/.test(n)&&!t||n===`.`&&y(e.slice(0,r.index))))continue;let i=r.index+r[0].length;i<e.length&&(yield i)}}function x(e,t){let n=e.slice(0,t),r=0;for(let e of n.matchAll(/\s+/g))n.slice(0,e.index).trim()&&(r=e.index+e[0].length);return r}function S(e){let t=0;for(let n of b(e.slice(0,220),!0))t=n;if(t)return t;let n=x(e,220);if(n)return n;let r=e.charCodeAt(219);return r>=55296&&r<=56319?219:220}var C=class{#e=``;#t=!0;push(e){return this.#e+=e,this.#n()}flush(){let e=this.#n(),t=this.#e;if(this.#e=``,t.trim()){for(let n=0;n<t.length;){let r=t.slice(n),i=r.length>220?S(r):r.length;e.push(r.slice(0,i)),n+=i}this.#t=!1}return e}idle(){let e=this.#e;if(!e.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(e))return[];this.#e=``,this.#t=!1;let t=[];for(let n=0;n<e.length;){let r=e.slice(n),i=r.length>220?S(r):r.length;t.push(r.slice(0,i)),n+=i}return t}#n(){let e=[];for(let t=this.#r();t>0;t=this.#r())e.push(this.#e.slice(0,t)),this.#e=this.#e.slice(t),this.#t=!1;return e}#r(){let e=this.#e;if(!e.trim())return 0;let t=b(e,this.#t).next().value??0;if(t&&t<=220)return t;let n=/[.!?]["'”’)\]*_]*$/.test(e);if(this.#t&&!n){let t=e.match(/\S+\s+/g)?.length??0;if(e.trim().length>=30||t>=6){let t=x(e,220);if(t)return t}}return e.length>220?S(e):0}};const w=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n},T=`no|nope|never ?mind|decline(?: it| that)?|cancel(?: it| that| this)?(?: (?:the|my|that|this) (?:[a-z]+ )?(?:order|request))?|don'?t (?:do|place) (?:it|that|the (?:[a-z]+ )?order)`,E=RegExp(`^(?:${T})(?: (?:${T}))?(?: thanks| thank you)?$`),D=e=>E.test(e.toLowerCase().replace(/[^a-z' ]+/g,` `).replace(/\s+/g,` `).trim()),O=()=>new Promise(e=>setTimeout(e,50)),k=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e,A=e=>e.replace(/^webmcp:/,``).replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_\-.]+/g,` `).trim().toLowerCase();function j(e,t=0){if(e==null||e===``)return``;if(typeof e!=`object`)return String(e);if(t>2)return``;if(Array.isArray(e))return e.map(e=>j(e,t+1)).filter(Boolean).join(`, `);let n=e,r=n.quantity??n.qty??n.count,i=n.name??n.item??n.product??n.title;return r!=null&&i!=null&&typeof i!=`object`?`${r} ${i}`:Object.entries(n).filter(([e])=>!e.startsWith(`_`)).map(([e,n])=>{let r=j(n,t+1);return r&&(t?`${A(e)} ${r}`:`${A(e)}: ${r}`)}).filter(Boolean).join(t?`, `:`; `)}function M(e){let t=e.length>1?`These actions need the user's approval in the chat before they happen:`:`This action needs the user's approval in the chat before it happens:`,n=1e3-t.length-119-2;return`${t}\n${e.map(t=>{let r=[A(t.toolName)];t.description&&r.push(`(${k(t.description.trim(),160)})`);let i=j(t.parameters);return i&&r.push(`with ${i}`),t.reason&&r.push(`because: ${k(t.reason.trim(),160)}`),k(`- ${r.join(` `)}`,Math.floor(n/e.length)-1)}).join(`
4
+ `)}function o(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===1380533830?new Uint8Array(e,44):new Uint8Array(e)}function s(e){let t=e.replace(/\/+$/,``);return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,`ws`):`${typeof window<`u`&&window.location?.protocol===`https:`?`wss:`:`ws:`}//${t}`}function c(e){return s(e).replace(/^ws/i,`http`)}function l(e){return typeof e!=`number`||!Number.isFinite(e)?3e4:Math.min(6e5,Math.max(3e4,Math.round(e)))}var u=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<3e4)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${c(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=l(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,5e3)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(e,t,n){let r=`partial_transcript,context`;this.bridge&&this.config?.clientDelegation!==!1&&(r+=`,client_delegation,delegation_update,delegation_read_back,delegation_stream`,this.bridge.clientTools?.()&&(r+=`,client_tools,prior_tool_results`)),n&&(r=`attach,${r}`);let i=new URLSearchParams({voiceProtocol:`runtype-browser-v1`,clientVersion:`persona/4.32.2`,voiceCapabilities:`full-duplex-v1`,clientCapabilities:r});return n?.forEach((e,t)=>i.set(t,e)),`${s(e)}/ws/agents/${encodeURIComponent(t)}/voice?${i}`}async startListening(){if(this.#l)return;let n=this.#A;n||(this.#k=!1,this.#D=null),this.#A=!1;let r=this.config?.agentId,a=this.config?.clientToken,o=this.config?.host;if(!r)throw Error(`Runtype voice requires an agentId`);if(!a)throw Error(`Runtype voice requires a clientToken`);if(!o)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let s=++this.#d;this.#f=!1,this.#l=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:t,channelCount:1,echoCancellation:!0}});if(s!==this.#d){c.getTracks().forEach(e=>e.stop());return}this.#r=c;let l=new(window.AudioContext||window.webkitAudioContext)({sampleRate:t});if(this.#t=l,l.state===`suspended`){if(await Promise.race([l.resume().catch(()=>{}),new Promise(e=>setTimeout(e,n?500:1e3))]),s!==this.#d)return;if(l.state!==`running`)throw Error(n?this.#D=`${i} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let u=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new e(24e3);if(s!==this.#d){u.destroy(),c.getTracks().forEach(e=>e.stop()),l.close().catch(()=>{});return}this.#c=u,this.#he(),this.#ie(l,c,s);let d=await this.#ee();if(s!==this.#d){d?.ws.close(1e3,`client ended call`);return}if(d){let{ws:e}=d;this.#e=e,this.#ne(e,s),d.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let f=new WebSocket(this.#te(o,r),[`runtype.bearer`,a]);f.binaryType=`arraybuffer`,this.#e=f,f.onopen=()=>{s===this.#d&&(this.#ae(f),this.#be(`listening`))},this.#ne(f,s)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let a=r.includes(e)&&!this.#k;if(this.#ye(),a)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${i} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(r.includes(e))return this.#D=i,this.#xe(/* @__PURE__ */ Error(i)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||n.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||`You're talking to an AI assistant. Voice is processed by OpenAI.`:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+2e3,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(4096,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>256e3;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*4));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[],priorToolResults:r.priorToolResults},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return a(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),2e3)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,54e4),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=o(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+300)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}},d=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}};function f(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new u(e.runtype);case`browser`:if(!d.isSupported())throw Error(`Browser speech recognition not supported`);return new d(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function p(e){if(e?.type===`custom`&&e.custom)return f({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return f({type:`runtype`,runtype:e.runtype});if(d.isSupported())return f({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function m(e){try{return p(e),!0}catch{return!1}}const h=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,``);var g=class{constructor(e){this.host=e,this.turns=/* @__PURE__ */ new Map,this.latestId=null,this.cancelled=/* @__PURE__ */ new Set}apply(e,t,n,r,i,a){let o=this.host;t=t.trim();let s=this.turns.get(r);if(s||(s={},this.turns.set(r,s),this.latestId=r),e===`user`){s.userFinal=n;let e=s.userId?o.find(s.userId):void 0;if(e){let r=s.userStartMs===void 0&&i!==void 0;r&&(s.userStartMs=i),o.upsert({...e,content:t,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else{s.userStartMs=i;let e=s.assistantId?o.find(s.assistantId):void 0;s.userId=o.inject({role:`user`,content:t,streaming:!1,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i)??e)}).id}}else if(!this.cancelled.has(r)){s.assistantFinal=n;let e=s.assistantId?o.find(s.assistantId):void 0;if(e){let r=s.assistantStartMs===void 0&&i!==void 0;r&&(s.assistantStartMs=i),o.upsert({...e,content:t,streaming:!n,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else t&&(s.assistantStartMs=i,s.assistantId=o.inject({role:`assistant`,content:t,streaming:!n,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i))}).id);n&&s.assistantId&&o.markSpoken(s.assistantId)}this.sync()}claimUserTurn(e,t=[]){let n=t[t.length-1];for(let e of t)e!==n&&(this.turns.has(e)||this.turns.set(e,{}),this.turns.get(e).claimed=!0);let r;if(n){if(r=this.turns.get(n),r||(r={},this.turns.set(n,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:`user`,content:e.trim()}).id)}else{let t=h(e),n=[...this.turns.values()].reverse().flatMap(e=>{let t=e.userId&&!e.claimed?this.host.find(e.userId):void 0;return t?[{turn:e,text:h(t.content)}]:[]}).filter(({text:e})=>e&&t);r=(n.find(({text:e})=>e===t)??n.find(({text:e})=>e.startsWith(t)||t.startsWith(e)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let e=this.inFlight();if(e.length===0){let t=this.awaiting();if(!t)return;e=[t]}for(let t of e)this.cancelled.add(t);this.closeReplies(e),this.sync()}fail(e){let t=this.awaiting(),n=this.inFlight();if(!t&&n.length===0)return;for(let e of n)this.turns.get(e).assistantFinal=!0;this.closeReplies(n);let r=this.host.inject({role:`assistant`,content:e,streaming:!1,voiceProcessing:!1}),i=t?this.turns.get(t):void 0;i&&(i.assistantId=r.id,i.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let e=this.pending(),t=/* @__PURE__ */ new Set;for(let e of this.turns.values())e.userId&&t.add(e.userId),e.assistantId&&(t.add(e.assistantId),this.host.markSpoken(e.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(t),e&&this.host.setStreaming(!1)}startedAfter(e){if(e===void 0)return;let t;for(let n of this.turns.values())for(let[r,i]of[[n.userId,n.userStartMs],[n.assistantId,n.assistantStartMs]])r&&i!==void 0&&i>e&&(!t||i<t.start)&&(t={start:i,id:r});return t&&this.host.find(t.id)}placeBefore(e){if(!e)return;let t=e.sequence??0,n=t-1;for(let r of this.turns.values())for(let i of[r.userId,r.assistantId]){let r=i?this.host.find(i):void 0,a=r?.sequence;r?.createdAt===e.createdAt&&a!==void 0&&a>n&&a<t&&(n=a)}return{createdAt:e.createdAt,sequence:(n+t)/2}}closeReplies(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.turns.get(n)?.assistantId;e&&(t.add(e),this.host.markSpoken(e))}t.size>0&&this.host.settle(t)}inFlight(){let e=[];for(let[t,n]of this.turns)n.assistantId&&!n.assistantFinal&&!this.cancelled.has(t)&&e.push(t);return e}awaiting(){let e=this.latestId;if(!e)return null;let t=this.turns.get(e);return t?.userFinal&&!t.assistantId&&!t.claimed&&!this.cancelled.has(e)?e:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}};const _=/* @__PURE__ */ new Set(/* @__PURE__ */ `mr,mrs,ms,dr,prof,sr,jr,st,mt,vs,etc,approx,inc,ltd,co,corp,no,nos,fig,ft,dept,est,min,max,e.g,i.e,a.m,p.m,u.s,u.k`.split(`,`)),v=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g;function y(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,``).toLowerCase();if(_.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let n=e.length-t.length;return n===0||/\n\s*$/.test(e.slice(0,n))}return!1}function*b(e,t){let n=new RegExp(v.source,`g`);for(let r=n.exec(e);r;r=n.exec(e)){let n=r[1];if(!e.slice(0,r.index+(n?.length??0)).trim()||n!==void 0&&(/^[,;:]$/.test(n)&&!t||n===`.`&&y(e.slice(0,r.index))))continue;let i=r.index+r[0].length;i<e.length&&(yield i)}}function x(e,t){let n=e.slice(0,t),r=0;for(let e of n.matchAll(/\s+/g))n.slice(0,e.index).trim()&&(r=e.index+e[0].length);return r}function S(e){let t=0;for(let n of b(e.slice(0,220),!0))t=n;if(t)return t;let n=x(e,220);if(n)return n;let r=e.charCodeAt(219);return r>=55296&&r<=56319?219:220}var C=class{#e=``;#t=!0;push(e){return this.#e+=e,this.#n()}flush(){let e=this.#n(),t=this.#e;if(this.#e=``,t.trim()){for(let n=0;n<t.length;){let r=t.slice(n),i=r.length>220?S(r):r.length;e.push(r.slice(0,i)),n+=i}this.#t=!1}return e}idle(){let e=this.#e;if(!e.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(e))return[];this.#e=``,this.#t=!1;let t=[];for(let n=0;n<e.length;){let r=e.slice(n),i=r.length>220?S(r):r.length;t.push(r.slice(0,i)),n+=i}return t}#n(){let e=[];for(let t=this.#r();t>0;t=this.#r())e.push(this.#e.slice(0,t)),this.#e=this.#e.slice(t),this.#t=!1;return e}#r(){let e=this.#e;if(!e.trim())return 0;let t=b(e,this.#t).next().value??0;if(t&&t<=220)return t;let n=/[.!?]["'”’)\]*_]*$/.test(e);if(this.#t&&!n){let t=e.match(/\S+\s+/g)?.length??0;if(e.trim().length>=30||t>=6){let t=x(e,220);if(t)return t}}return e.length>220?S(e):0}};const w=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n},T=`no|nope|never ?mind|decline(?: it| that)?|cancel(?: it| that| this)?(?: (?:the|my|that|this) (?:[a-z]+ )?(?:order|request))?|don'?t (?:do|place) (?:it|that|the (?:[a-z]+ )?order)`,E=RegExp(`^(?:${T})(?: (?:${T}))?(?: thanks| thank you)?$`),D=e=>E.test(e.toLowerCase().replace(/[^a-z' ]+/g,` `).replace(/\s+/g,` `).trim()),O=()=>new Promise(e=>setTimeout(e,50)),k=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e,A=e=>e.replace(/^webmcp:/,``).replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_\-.]+/g,` `).trim().toLowerCase();function j(e,t=0){if(e==null||e===``)return``;if(typeof e!=`object`)return String(e);if(t>2)return``;if(Array.isArray(e))return e.map(e=>j(e,t+1)).filter(Boolean).join(`, `);let n=e,r=n.quantity??n.qty??n.count,i=n.name??n.item??n.product??n.title;return r!=null&&i!=null&&typeof i!=`object`?`${r} ${i}`:Object.entries(n).filter(([e])=>!e.startsWith(`_`)).map(([e,n])=>{let r=j(n,t+1);return r&&(t?`${A(e)} ${r}`:`${A(e)}: ${r}`)}).filter(Boolean).join(t?`, `:`; `)}function M(e){let t=e.length>1?`These actions need the user's approval in the chat before they happen:`:`This action needs the user's approval in the chat before it happens:`,n=1e3-t.length-119-2;return`${t}\n${e.map(t=>{let r=[A(t.toolName)];t.description&&r.push(`(${k(t.description.trim(),160)})`);let i=j(t.parameters);return i&&r.push(`with ${i}`),t.reason&&r.push(`because: ${k(t.reason.trim(),160)}`),k(`- ${r.join(` `)}`,Math.floor(n/e.length)-1)}).join(`
5
5
  `)}\n\nBriefly tell the user what you're about to do and ask them to approve or decline it in the chat. Don't claim it's done.`}const N=e=>e.variant===`approval`&&e.approval?.status===`pending`;function P(e){let t=null,n=null,r=()=>e.track(t??n),i=[],a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=(e,t)=>{a.set(e,[...a.get(e)??[],t]),a.size>32&&a.delete(a.keys().next().value)},c=t=>e.messages().find(e=>e.id===t),l=e=>e.approvals.filter(e=>c(e)?.approval?.status===`pending`),u=e=>A(c(e)?.approval?.toolName??``),d=(t,n,r)=>{t.outcome={status:n,text:r};for(let n of l(t))e.decide(n)},f=t=>t.flatMap(t=>e.messages().find(e=>e.id===t)??[]).filter(e=>!e.variant&&e.content.trim()).map(e=>e.content.trim()).join(`
6
6
 
7
7
  `),p=async t=>{do await O();while(e.busy()&&!(t&&(e.parked()||t.failed)))};return{clientTools:e.clientTools,recordDirectTurn:e.recordDirect,getHistory:()=>{let t=e.messages().filter(e=>(e.role===`user`||e.role===`assistant`)&&!e.variant&&!e.voiceProcessing&&!e.streaming&&e.content),n=!1,r=[];for(let e=t.length-1;e>=0;--e){let i=t[e];if(i.role===`user`)n=!1;else if(!i.voiceCaption)n=!0;else if(n)continue;r.unshift({role:i.role,content:i.content})}return r},dropDelegation(t,n){o.set(t,!!n),o.size>32&&o.delete(o.keys().next().value);let r=n&&i.find(e=>e.delegationId===t);r&&!r.outcome&&d(r,`timeout`,``);for(let n of a.get(t)??[])n.stopStream?.(),n.dropped=!0,n.ids.length&&e.unspoken(n.ids)},async runDelegatedTurn({delegationId:m,userText:h,userUtteranceIds:g,stream:_,priorToolResults:v}){let y=i.filter(e=>l(e).length),b=y.flatMap(l);if(b.length===1&&D(h)){let e=u(b[0]);return d(y[0],`denied`,``),{status:`denied`,text:`Okay, I cancelled the ${e} request. Nothing was done.`,inChat:!1}}let x=e.parked()&&e.messages().every(e=>!N(e)||b.includes(e.id));e.busy()&&!x&&await p();let S=new Set(e.messages().map(e=>e.id)),T=()=>e.messages().filter(e=>!S.has(e.id)&&e.variant===`approval`),E={ids:[],failed:!1},k=_?new C:null,j=``,P=``,F=!1,I=e=>{for(let t of e)P+=t,_(t)},L;k&&(E.onUpdate=()=>{if(F)return;let e=f(E.ids);if(!e.startsWith(j)){F=!0,clearTimeout(L);return}if(e.length===j.length)return;let t=e.slice(j.length);j=e,I(k.push(t)),clearTimeout(L),L=setTimeout(()=>{F||I(k.idle())},200)},E.stopStream=()=>{clearTimeout(L),F=!0,E.onUpdate=void 0}),s(m,E),t=E,r();try{await e.send(h,{userMessageId:e.claim(h,g),priorToolResults:v}),await p(E)}catch{E.failed=!0}finally{t=null,r()}k&&(E.onUpdate?.(),clearTimeout(L),F||I(k.flush()),E.onUpdate=void 0,E.stopStream=void 0);let R=e=>{let t=w(P,e);return t>0?{streamedChars:t}:{}},z=E.ids.flatMap(t=>e.messages().find(e=>e.id===t)??[]),B=f(E.ids),V=E.failed?[]:T().filter(N),H=new Set(V.map(e=>A(e.approval.toolName)));for(let t of y){if(t.outcome)continue;for(let n of l(t).filter(e=>H.has(u(e))))t.replaced.add(n),e.decide(n);let n=u(t.approvals[0]);(t.approvals.every(e=>t.replaced.has(e))||x&&t.approvals.every(e=>c(e)?.approval?.status===`denied`))&&(t.outcome={status:`cancelled`,text:`The earlier ${n} request was replaced by the new one; it was not done.`})}if(V.length){let c=new Set(V.map(e=>e.id)),p={delegationId:m,approvals:[...c],at:Date.now(),replaced:/* @__PURE__ */ new Set};return i.push(p),o.get(m)&&d(p,`timeout`,``),B=`${B}\n\n${M(V.map(e=>e.approval))}`.trim(),{status:`pending_approval`,text:B,...R(B),followUp:async({signal:o,approvalTimeoutMs:h=3e5,readBack:g=!0,onUpdate:_})=>{let v={ids:[],failed:!1};a.delete(m),s(m,v);let y=()=>T().filter(e=>c.has(e.id)||v.ids.includes(e.id)),b=()=>T().filter(e=>N(e)&&!c.has(e.id)&&!i.some(t=>t.approvals.includes(e.id))&&(v.ids.includes(e.id)||e.approval?.toolType===`webmcp`&&n===v)),x=()=>{n=v,r()};g&&x();try{for(;!o.aborted&&!p.outcome&&(t||e.busy()||y().some(N));){g&&n!==v&&!l(p).length&&x();let t=b();if(t.length){for(let e of t)c.add(e.id),p.approvals.push(e.id);p.at=Date.now(),_?.(M(t.map(e=>e.approval)))}if(Date.now()-p.at>=h&&l(p).length&&(!e.busy()||e.parked())){d(p,`timeout`,`That ${u(p.approvals[0])} request expired, so nothing was done.`);break}await O()}}finally{n===v&&(n=null,r()),i.splice(i.indexOf(p),1)}if(o.aborted)return null;if(p.outcome)return p.outcome;if(v.failed)return{status:`failed`,text:`The ${u(p.approvals[0])} request didn't complete.`};let S=y(),C=e=>S.filter(e).map(e=>A(e.approval.toolName)).join(`, `),w=S.some(e=>e.approval?.status===`approved`),E=C(e=>e.approval?.status===`denied`&&!p.replaced.has(e.id)),D=C(e=>p.replaced.has(e.id)),k=C(e=>e.approval?.status===`timeout`),j=[w?f(v.ids):``,E&&`The user declined the ${E} request in the chat, so ${w?`that part was not done`:`nothing was done`}.`,D&&`The earlier ${D} request was replaced by the new one; it was not done.`,k&&`The ${k} request timed out, so it was not done.`].filter(Boolean).join(`
@@ -1,4 +1,4 @@
1
- var e=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},t,n=e((()=>{t=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}})),r=`4.32.1`,i,a=e((()=>{i=r}));function o(e,t){let n=t.slice(0,P).trim(),r=N-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>F&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
1
+ var e=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},t,n=e((()=>{t=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}})),r=`4.32.2`,i,a=e((()=>{i=r}));function o(e,t){let n=t.slice(0,P).trim(),r=N-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>F&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
2
2
  `)}`]:[];return n&&a.push(n),a.join(`
3
3
 
4
4
  `)}function s(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===g?new Uint8Array(e,44):new Uint8Array(e)}function c(e){let t=e.replace(/\/+$/,``);return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,`ws`):`${typeof window<`u`&&window.location?.protocol===`https:`?`wss:`:`ws:`}//${t}`}function l(e){return c(e).replace(/^ws/i,`http`)}function u(e){return typeof e!=`number`||!Number.isFinite(e)?b:Math.min(S,Math.max(x,Math.round(e)))}var d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,P,F,I,ee=e((()=>{n(),a(),d=16e3,f=24e3,p=4096,m=d*2*8,h=4,g=1380533830,_=3e4,v=1e3,y=5e3,b=3e4,x=3e4,S=6e5,C=`full-duplex-v1`,w=300,T=2e3,E=2e3,D=`runtype-browser-v1`,O=54e4,k=`You're talking to an AI assistant. Voice is processed by OpenAI.`,A=/* @__PURE__ */ new Map([[`idle_timeout`,`Voice call ended after a quiet period.`],[`max_duration`,`This voice call reached its time limit.`],[`provider_ended`,`The voice session ended.`],[`quota`,`Voice is unavailable right now.`],[`auth_expired`,`Voice session expired. Tap the mic to reconnect.`]]),j=[`provider_error`,`server_restart`],M=`Voice connection lost.`,N=8e3,P=4e3,F=2e3,I=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<_)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${l(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=u(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,y)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(e,t,n){let r=`partial_transcript,context`;this.bridge&&this.config?.clientDelegation!==!1&&(r+=`,client_delegation,delegation_update,delegation_read_back,delegation_stream`,this.bridge.clientTools?.()&&(r+=`,client_tools,prior_tool_results`)),n&&(r=`attach,${r}`);let a=new URLSearchParams({voiceProtocol:D,clientVersion:`persona/${i}`,voiceCapabilities:C,clientCapabilities:r});return n?.forEach((e,t)=>a.set(t,e)),`${c(e)}/ws/agents/${encodeURIComponent(t)}/voice?${a}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let n=this.config?.agentId,r=this.config?.clientToken,i=this.config?.host;if(!n)throw Error(`Runtype voice requires an agentId`);if(!r)throw Error(`Runtype voice requires a clientToken`);if(!i)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let a=++this.#d;this.#f=!1,this.#l=!0;try{let o=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:d,channelCount:1,echoCancellation:!0}});if(a!==this.#d){o.getTracks().forEach(e=>e.stop());return}this.#r=o;let s=new(window.AudioContext||window.webkitAudioContext)({sampleRate:d});if(this.#t=s,s.state===`suspended`){if(await Promise.race([s.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:v))]),a!==this.#d)return;if(s.state!==`running`)throw Error(e?this.#D=`${M} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new t(f);if(a!==this.#d){c.destroy(),o.getTracks().forEach(e=>e.stop()),s.close().catch(()=>{});return}this.#c=c,this.#he(),this.#ie(s,o,a);let l=await this.#ee();if(a!==this.#d){l?.ws.close(1e3,`client ended call`);return}if(l){let{ws:e}=l;this.#e=e,this.#ne(e,a),l.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let u=new WebSocket(this.#te(i,n),[`runtype.bearer`,r]);u.binaryType=`arraybuffer`,this.#e=u,u.onopen=()=>{a===this.#d&&(this.#ae(u),this.#be(`listening`))},this.#ne(u,a)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=j.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${M} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(j.includes(e))return this.#D=M,this.#xe(/* @__PURE__ */ Error(M)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||A.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||k:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+T,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(p,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>m;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*h));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[],priorToolResults:r.priorToolResults},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return o(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),E)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,O),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=s(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+w)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}}})),L,te=e((()=>{L=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}}}));function R(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new I(e.runtype);case`browser`:if(!L.isSupported())throw Error(`Browser speech recognition not supported`);return new L(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function ne(e){if(e?.type===`custom`&&e.custom)return R({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return R({type:`runtype`,runtype:e.runtype});if(L.isSupported())return R({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function re(e){try{return ne(e),!0}catch{return!1}}var ie=e((()=>{ee(),te()})),z,ae,oe=e((()=>{z=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,``),ae=class{constructor(e){this.host=e,this.turns=/* @__PURE__ */ new Map,this.latestId=null,this.cancelled=/* @__PURE__ */ new Set}apply(e,t,n,r,i,a){let o=this.host;t=t.trim();let s=this.turns.get(r);if(s||(s={},this.turns.set(r,s),this.latestId=r),e===`user`){s.userFinal=n;let e=s.userId?o.find(s.userId):void 0;if(e){let r=s.userStartMs===void 0&&i!==void 0;r&&(s.userStartMs=i),o.upsert({...e,content:t,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else{s.userStartMs=i;let e=s.assistantId?o.find(s.assistantId):void 0;s.userId=o.inject({role:`user`,content:t,streaming:!1,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i)??e)}).id}}else if(!this.cancelled.has(r)){s.assistantFinal=n;let e=s.assistantId?o.find(s.assistantId):void 0;if(e){let r=s.assistantStartMs===void 0&&i!==void 0;r&&(s.assistantStartMs=i),o.upsert({...e,content:t,streaming:!n,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else t&&(s.assistantStartMs=i,s.assistantId=o.inject({role:`assistant`,content:t,streaming:!n,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i))}).id);n&&s.assistantId&&o.markSpoken(s.assistantId)}this.sync()}claimUserTurn(e,t=[]){let n=t[t.length-1];for(let e of t)e!==n&&(this.turns.has(e)||this.turns.set(e,{}),this.turns.get(e).claimed=!0);let r;if(n){if(r=this.turns.get(n),r||(r={},this.turns.set(n,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:`user`,content:e.trim()}).id)}else{let t=z(e),n=[...this.turns.values()].reverse().flatMap(e=>{let t=e.userId&&!e.claimed?this.host.find(e.userId):void 0;return t?[{turn:e,text:z(t.content)}]:[]}).filter(({text:e})=>e&&t);r=(n.find(({text:e})=>e===t)??n.find(({text:e})=>e.startsWith(t)||t.startsWith(e)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let e=this.inFlight();if(e.length===0){let t=this.awaiting();if(!t)return;e=[t]}for(let t of e)this.cancelled.add(t);this.closeReplies(e),this.sync()}fail(e){let t=this.awaiting(),n=this.inFlight();if(!t&&n.length===0)return;for(let e of n)this.turns.get(e).assistantFinal=!0;this.closeReplies(n);let r=this.host.inject({role:`assistant`,content:e,streaming:!1,voiceProcessing:!1}),i=t?this.turns.get(t):void 0;i&&(i.assistantId=r.id,i.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let e=this.pending(),t=/* @__PURE__ */ new Set;for(let e of this.turns.values())e.userId&&t.add(e.userId),e.assistantId&&(t.add(e.assistantId),this.host.markSpoken(e.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(t),e&&this.host.setStreaming(!1)}startedAfter(e){if(e===void 0)return;let t;for(let n of this.turns.values())for(let[r,i]of[[n.userId,n.userStartMs],[n.assistantId,n.assistantStartMs]])r&&i!==void 0&&i>e&&(!t||i<t.start)&&(t={start:i,id:r});return t&&this.host.find(t.id)}placeBefore(e){if(!e)return;let t=e.sequence??0,n=t-1;for(let r of this.turns.values())for(let i of[r.userId,r.assistantId]){let r=i?this.host.find(i):void 0,a=r?.sequence;r?.createdAt===e.createdAt&&a!==void 0&&a>n&&a<t&&(n=a)}return{createdAt:e.createdAt,sequence:(n+t)/2}}closeReplies(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.turns.get(n)?.assistantId;e&&(t.add(e),this.host.markSpoken(e))}t.size>0&&this.host.settle(t)}inFlight(){let e=[];for(let[t,n]of this.turns)n.assistantId&&!n.assistantFinal&&!this.cancelled.has(t)&&e.push(t);return e}awaiting(){let e=this.latestId;if(!e)return null;let t=this.turns.get(e);return t?.userFinal&&!t.assistantId&&!t.claimed&&!this.cancelled.has(e)?e:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}}}));function se(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,``).toLowerCase();if(W.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let n=e.length-t.length;return n===0||/\n\s*$/.test(e.slice(0,n))}return!1}function*ce(e,t){let n=new RegExp(G.source,`g`);for(let r=n.exec(e);r;r=n.exec(e)){let n=r[1];if(!e.slice(0,r.index+(n?.length??0)).trim()||n!==void 0&&(/^[,;:]$/.test(n)&&!t||n===`.`&&se(e.slice(0,r.index))))continue;let i=r.index+r[0].length;i<e.length&&(yield i)}}function B(e,t){let n=e.slice(0,t),r=0;for(let e of n.matchAll(/\s+/g))n.slice(0,e.index).trim()&&(r=e.index+e[0].length);return r}function V(e){let t=0;for(let n of ce(e.slice(0,220),!0))t=n;if(t)return t;let n=B(e,220);if(n)return n;let r=e.charCodeAt(219);return r>=55296&&r<=56319?219:220}var H,U,W,G,K,le=e((()=>{H=30,U=6,W=/* @__PURE__ */ new Set(/* @__PURE__ */ `mr,mrs,ms,dr,prof,sr,jr,st,mt,vs,etc,approx,inc,ltd,co,corp,no,nos,fig,ft,dept,est,min,max,e.g,i.e,a.m,p.m,u.s,u.k`.split(`,`)),G=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g,K=class{#e=``;#t=!0;push(e){return this.#e+=e,this.#n()}flush(){let e=this.#n(),t=this.#e;if(this.#e=``,t.trim()){for(let n=0;n<t.length;){let r=t.slice(n),i=r.length>220?V(r):r.length;e.push(r.slice(0,i)),n+=i}this.#t=!1}return e}idle(){let e=this.#e;if(!e.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(e))return[];this.#e=``,this.#t=!1;let t=[];for(let n=0;n<e.length;){let r=e.slice(n),i=r.length>220?V(r):r.length;t.push(r.slice(0,i)),n+=i}return t}#n(){let e=[];for(let t=this.#r();t>0;t=this.#r())e.push(this.#e.slice(0,t)),this.#e=this.#e.slice(t),this.#t=!1;return e}#r(){let e=this.#e;if(!e.trim())return 0;let t=ce(e,this.#t).next().value??0;if(t&&t<=220)return t;let n=/[.!?]["'”’)\]*_]*$/.test(e);if(this.#t&&!n){let t=e.match(/\S+\s+/g)?.length??0;if(e.trim().length>=H||t>=U){let t=B(e,220);if(t)return t}}return e.length>220?V(e):0}}}));function q(e,t=0){if(e==null||e===``)return``;if(typeof e!=`object`)return String(e);if(t>2)return``;if(Array.isArray(e))return e.map(e=>q(e,t+1)).filter(Boolean).join(`, `);let n=e,r=n.quantity??n.qty??n.count,i=n.name??n.item??n.product??n.title;return r!=null&&i!=null&&typeof i!=`object`?`${r} ${i}`:Object.entries(n).filter(([e])=>!e.startsWith(`_`)).map(([e,n])=>{let r=q(n,t+1);return r&&(t?`${Q(e)} ${r}`:`${Q(e)}: ${r}`)}).filter(Boolean).join(t?`, `:`; `)}function ue(e){let t=e.length>1?`These actions need the user's approval in the chat before they happen:`:`This action needs the user's approval in the chat before it happens:`,n=ge-t.length-119-2;return`${t}\n${e.map(t=>{let r=[Q(t.toolName)];t.description&&r.push(`(${Z(t.description.trim(),160)})`);let i=q(t.parameters);return i&&r.push(`with ${i}`),t.reason&&r.push(`because: ${Z(t.reason.trim(),160)}`),Z(`- ${r.join(` `)}`,Math.floor(n/e.length)-1)}).join(`